diff --git a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs index 6996b64eb2a..9d14d2a1b38 100644 --- a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs +++ b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs @@ -1241,7 +1241,18 @@ object ICustomAstVisitor.VisitDoUntilStatement(DoUntilStatementAst doUntilStatem 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() { new(convert.Type.TypeName) }; + } + + child = attributeChild.Child; + } + + return assignmentStatementAst.Right.Accept(this); } object ICustomAstVisitor.VisitPipeline(PipelineAst pipelineAst) diff --git a/test/powershell/engine/Api/TypeInference.Tests.ps1 b/test/powershell/engine/Api/TypeInference.Tests.ps1 index 2ab5681dddb..e134cfb97ed 100644 --- a/test/powershell/engine/Api/TypeInference.Tests.ps1 +++ b/test/powershell/engine/Api/TypeInference.Tests.ps1 @@ -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