Improve assignment type inference (#21143)

This commit is contained in:
MartinGC94 authored and GitHub committed 2025-03-18 09:48:11 +05:00
1 parent 48c34fc3a7
commit 1edd258e3b
2 files changed
+32 -1

No files matched your search

@@ -1241,7 +1241,18 @@ namespace System.Management.Automation
object ICustomAstVisitor.VisitAssignmentStatement(AssignmentStatementAst assignmentStatementAst)
{
return assignmentStatementAst.Left.Accept(this);
ExpressionAst child = assignmentStatementAst.Left;
while (child is AttributedExpressionAst attributeChild)
{
if (attributeChild is ConvertExpressionAst convert)
{
return new List<PSTypeName>() { new(convert.Type.TypeName) };
}
child = attributeChild.Child;
}
return assignmentStatementAst.Right.Accept(this);
}
object ICustomAstVisitor.VisitPipeline(PipelineAst pipelineAst)
@@ -1469,6 +1469,26 @@ Describe "Type inference Tests" -tags "CI" {
$res.Count | Should -Be 0
}
It 'Infers right side of assignment expression' {
$res = [AstTypeInference]::InferTypeOf( { $Test1 = "Hello" }.Ast.Find({param($ast) $ast -is [Language.AssignmentStatementAst]}, $true))
$res.Count | Should -Be 1
$res.Name | Should -Be "System.String"
}
It 'Infers left side of assignment expression when it is a ConvertExpression' {
$res = [AstTypeInference]::InferTypeOf( { [string]$Test1 = 42 }.Ast.Find({param($ast) $ast -is [Language.AssignmentStatementAst]}, $true))
$res.Count | Should -Be 1
$res.Name | Should -Be "System.String"
}
It 'Infers left side of assignment expression when there is a ConvertExpression among other attributes' {
$res = [AstTypeInference]::InferTypeOf( {
[ValidateLength()] [string] [ValidatePattern()]$Test1 = 42
}.Ast.Find({param($ast) $ast -is [Language.AssignmentStatementAst]}, $true))
$res.Count | Should -Be 1
$res.Name | Should -Be "System.String"
}
It 'Infers type of all scope variable after variable assignment' {
$res = [AstTypeInference]::InferTypeOf( { $true = "Hello";$true }.Ast)
$res.Count | Should -Be 1