SemanticChecks: Avoid repeated type resolution of [ordered] (#17328)

This commit is contained in:
Mathias R. Jessen
2022-05-17 09:54:26 -07:00
committed by GitHub
parent 391e0806ec
commit afe99fcaea
2 changed files with 34 additions and 0 deletions
@@ -920,6 +920,13 @@ namespace System.Management.Automation.Language
ParserStrings.OrderedAttributeOnlyOnHashLiteralNode,
convertExpressionAst.Type.TypeName.FullName);
}
// Currently, the type name '[ordered]' is handled specially in PowerShell.
// When used in a conversion expression, it's only allowed on a hashliteral node, and it's
// always interpreted as an initializer for a case-insensitive
// 'System.Collections.Specialized.OrderedDictionary' by the compiler.
// So, we can return early from here.
return AstVisitAction.Continue;
}
if (typeof(PSReference) == convertExpressionAst.Type.TypeName.GetReflectionType())
@@ -41,4 +41,31 @@ Describe "Scripting.Followup.Tests" -Tags "CI" {
$obj.ForEach('p', 32) | Should -BeNullOrEmpty
$obj.p | Should -Be 32
}
It "Test the special type name 'ordered'" {
class ordered {
[hashtable] $Member
ordered([hashtable] $hash) {
$this.Member = $hash
}
}
## `<expr> -as\-is [ordered]` resolves 'ordered' as a normal type name.
$hash = @{ key = 2 }
$result = $hash -as [ordered]
$result.GetType().FullName | Should -BeExactly ([ordered].FullName)
$result -is [ordered] | Should -BeTrue
$result.Member['key'] | Should -Be 2
$result.Member.Count | Should -Be 1
## `[ordered]$hash` causes parsing error.
$err = $null
$null = [System.Management.Automation.Language.Parser]::ParseInput('[ordered]$hash', [ref]$null, [ref]$err)
$err.Count | Should -Be 1
$err[0].ErrorId | Should -BeExactly 'OrderedAttributeOnlyOnHashLiteralNode'
## `[ordered]@{ key = 1 }` creates 'OrderedDictionary'
$result = [ordered]@{ key = 1 }
$result | Should -BeOfType 'System.Collections.Specialized.OrderedDictionary'
}
}