mirror of
https://github.com/PowerShell/PowerShell
synced 2026-06-08 12:12:50 +00:00
Fix variable type inference precedence (#18691)
This commit is contained in:
@@ -2121,11 +2121,6 @@ namespace System.Management.Automation
|
||||
parent = parent.Parent;
|
||||
}
|
||||
|
||||
if (parent.Parent is FunctionDefinitionAst)
|
||||
{
|
||||
parent = parent.Parent;
|
||||
}
|
||||
|
||||
int startOffset = variableExpressionAst.Extent.StartOffset;
|
||||
var targetAsts = (List<Ast>)AstSearcher.FindAll(
|
||||
parent,
|
||||
@@ -2165,9 +2160,9 @@ namespace System.Management.Automation
|
||||
|
||||
// If any of the assignments lhs use a type constraint, then we use that.
|
||||
// Otherwise, we use the rhs of the "nearest" assignment
|
||||
foreach (var assignAst in assignAsts)
|
||||
for (int i = assignAsts.Length - 1; i >= 0; i--)
|
||||
{
|
||||
if (assignAst.Left is ConvertExpressionAst lhsConvert)
|
||||
if (assignAsts[i].Left is ConvertExpressionAst lhsConvert)
|
||||
{
|
||||
inferredTypes.Add(new PSTypeName(lhsConvert.Type.TypeName));
|
||||
return;
|
||||
@@ -2592,7 +2587,8 @@ namespace System.Management.Automation
|
||||
if (parameterAst != null)
|
||||
{
|
||||
return variableAstVariablePath.IsUnscopedVariable &&
|
||||
parameterAst.Name.VariablePath.UnqualifiedPath.Equals(variableAstVariablePath.UnqualifiedPath, StringComparison.OrdinalIgnoreCase);
|
||||
parameterAst.Name.VariablePath.UnqualifiedPath.Equals(variableAstVariablePath.UnqualifiedPath, StringComparison.OrdinalIgnoreCase) &&
|
||||
parameterAst.Parent.Parent.Extent.EndOffset > variableAst.Extent.StartOffset;
|
||||
}
|
||||
|
||||
if (ast is ForEachStatementAst foreachAst)
|
||||
|
||||
@@ -1385,6 +1385,24 @@ Describe "Type inference Tests" -tags "CI" {
|
||||
$res.Name -join ' ' | Should -Be "System.IO.FileInfo System.IO.DirectoryInfo"
|
||||
}
|
||||
|
||||
It 'Infers closest variable type' {
|
||||
$res = [AstTypeInference]::InferTypeOf( { [string]$TestVar = "";[hashtable]$TestVar = @{};$TestVar }.Ast)
|
||||
$res.Name | Select-Object -Last 1 | Should -Be "System.Collections.Hashtable"
|
||||
}
|
||||
|
||||
It 'Infers closest variable type and ignores unrelated param blocks' {
|
||||
$res = [AstTypeInference]::InferTypeOf( {
|
||||
[hashtable]$ParameterName=@{}
|
||||
function Verb-Noun {
|
||||
param
|
||||
(
|
||||
[string]$ParameterName
|
||||
)
|
||||
}
|
||||
$ParameterName }.Ast)
|
||||
$res.Name | Should -Be "System.Collections.Hashtable"
|
||||
}
|
||||
|
||||
It 'Infers type of $null after variable assignment' {
|
||||
$res = [AstTypeInference]::InferTypeOf( { $null = "Hello";$null }.Ast)
|
||||
$res.Count | Should -Be 0
|
||||
|
||||
Reference in New Issue
Block a user