You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Is there a good reason not to allow direct access to properties whose name starts with a digit? #6946
Issue-Questionideally support can be provided via other mechanisms, but sometimes folks do open an issue to get aResolution-AnsweredThe question is answered.WG-Enginecore PowerShell engine, interpreter, and runtimeWG-Languageparser, language semantics
@george-chakhidze $obj.{1a} works because the string value for the scriptblock [1a} is '1a'. So it's essentially equivalent to $obj.'1a'`.
Michael Klement (@mklement0) It's not allowed because it's sufficiently anomalous that it's probably a mistake. Cat's walking on keyboards should not produce valid programs. If you really want to do it, then you have to make it explicit with quoting as in the case of this StackOverflow question (I assume this is what prompted the question?)
Now as it happens, $foo.123 works fine. This is because we allow expressions of the LHS of . and, of course, 123 is a legal expression.
Good to know that $obj.{1a} only works accidentally, as a by-product of script-block stringification (I've updated the original post).
... as in the case of this StackOverflow question. I assume this is what prompted the question?
Yes.
And it is tangible evidence that not only cats walking on keyboards produce such property names, especially in the world of JSON.
It's not allowed because it's sufficiently anomalous that it's probably a mistake.
If that is truly the intent - and I don't think it should be - please provide a more meaningful error message.
Now as it happens, $foo.123 works fine. This is because we allow expressions of the LHS of . and, of course, 123 is a legal expression.
Yes, as it happens - and I suggest not relying on things that happen.
Let me ask the opposite question: with respect to property access on objects, what good reason is there to interpret what's to the right of . as anything other than a property name, i.e., a string (leaving property paths aside)?
(Hashtable keys are a different story).
Michael Klement (@mklement0) The issue in the stackoverflow question was not difficulty in figuring out that quoting the anomalous property name was required. The problem was that there was a typo in that name. Quoted or not made no difference since the property didn't exist.
especially in the world of JSON.
Interestingly, JavaScript doesn't allow property names to start with a number either. You have you have to use indexing instead. That would seem to discourage the use of such names in JSON.
If that is truly the intent - and I don't think it should be - please provide a more meaningful error message
As one of the people making that decision and the person who wrote the original code, I can say - yes, that is the intent. The error message is currently that the property is missing. I suppose we could change it to "missing or invalid".
Yes, as it happens - and I suggest not relying on things that happen
Poor phrasing on my part. It's not an accident, it's the expected consequence of the explicit decision to allow expressions on the LHS of '.', which in turn was done, in part, to deal with scenarios where objects might have non-conforming property names. As is the case in the stackoverflow question.
The problem was that there was a typo in that name.
Yes, the issue turned out to be a typo, but the fact remains that (a) digit-prefixed property names do occur, and (b) you do need explicit quoting to access them, and that may be surprising.
True, but JSON has long since outgrown use in the context of JavaScript only.
And, given that var o = JSON.parse('{ "1a": "value" }') works just fine even in JavaScript, you could similarly ask why JavaScript doesn't allow o.1a and instead requires o['1a'] - but that's obviously a separate debate.
The error message is currently that the property is missing. I suppose we could change it to "missing or invalid".
That would certainly help, though to be truly helpful it would have to say something along the lines of "when in doubt, quote the name".
which in turn was done, in part, to deal with scenarios where objects might have non-conforming property names. As is the case in the stackoverflow question.
Yet, typo aside, it is that very decision - treating what's to the right of . as an expression ONLY - that prevents the use of the non-conforming property name at hand.
Note that falling back to [string] interpretation - if interpretation as an expression doesn't work - makes perfect sense, as that is already happening for non-digit-prefixed barewords a.k.a regular property access:
$co.foo# .foo is *implicitly* treated like .'foo', because foo by itself is not an expression$co.1a# Why shouldn't this be treated like .'1a', if it can't be interpreted as an expression?
With property access, the advantage of being able to use an expression to the right of . is solely to calculate a property name - so that (ultimately) treating what's to the right as anything other than a string makes no sense.
Off the top of my head, I can't think of a single language that allows property names to start with a digit.
Note that falling back to [string] interpretation - if interpretation as an expression doesn't work - makes perfect sense, as that is already happening for non-digit-prefixed barewords a.k.a regular property access
That's not what happens. The parser looks for either a propertyname token or a unary expression. If a propertyname token is found, it is used to look up the property. If an expression is found, that expression is evaluated, the result is converted to a string by calling .ToString() and that string is used to look up the property.
that (ultimately) treating what's to the right as anything other than a string makes no sense.
So you're saying that in $x.abc+5 the property name should be abc+5?. That would make things rather awkward.
I can't think of a single language that allows property names to start with a digit.
We need to be careful to distinguish between allowing the definition of a property with a name that starts with a digit in principle on the one hand and allowing that name to be accessed with a bareword on the other hand.
As the JavaScript example showed, JavaScript supports the former, but not the latter, and that is currently also true of PowerShell.
The overall question, however, is whether there is a good reason for this asymmetry.
PowerShell is already unusual in allowing expressions in lieu of name literals as accessors, the way you describe.
So you're saying that in $x.abc+5 the property name should be abc+5
No, it should be parsed as $x.abc + 5, which is indeed what happens already.
$x.(abc+5) - explicit use of (...) - is a different story, and there the current behavior makes sense too: abc+5 is interpreted as a command and causes an error (unless there is a command literally named abc+5).
The parser looks for either a propertyname token or a unary expression
Well, 1a is, by the current rules, neither, so the question is what behavior makes sense in that case:
Since the result of the expression is converted to a string, as you state, so as to be interpreted as a property name, it seems to me that giving up on something that looks like a unary numeric expression at first glance but then cannot be evaluated as such is unhelpful (especially with the current error message).
Use of a unary numeric expression as a property accessor seems unlikely to be helpful in most cases and it's far from obvious that this kind of interpretation does take place - in contrast with more readily recognizable expressions such as $obj.$propName or $obj.('foo' + 2) -
I see the following ways to address this (there may be subtleties I'm missing):
(a) expand the definition of a property-name token to allow a leading digit.
(b) fall back to interpretation as a string literal if expression evaluation fails.
(c) report a meaningful error (it seems that we've already found common ground there).
Even with (b) in place the behavior could still be surprising, however:
$o= [pscustomobject] @{ '1e2'='hi' }
$o.1e2# !! $null, because `1e2` is interpreted as [double] 100
What muddies the waters is that for hashtable keys, which can be of any type, it does make sense to distinguish between @{ '1e2' = 'hi' } ([string] key) and @{ 1e2 = 'hi' } ([double] key, interpretation as unary expression that is a number literal), although you could argue that @{ 1a = 'hi' } - currently a different, but similarly obscure error (Missing closing '}' in statement block or type definition) - too should fall back to interpreting 1a as a string.
With hashtables too, if I were to guess, many users are unaware that keys are parsed as expressions if they don't start with a letter.
The ship has sailed, but I'd say that defaulting to string-literal interpretation with explicit opt-in to expression evaluation - similar to how $ and ( at the start of tokens in argument mode signal a non-literal argument - would have made for a model that's easier to grasp and remember.
I'm inclined to agree with that, really. It should default to string interpretation unless explicitly cast otherwise. However, it becomes tricky to distinguish there between what is intended to be a variable cast and what is simply part of a string.
If you allow expressions to be recognised as strings in hashtable literals, then how is it supposed to treat type casts correctly?
$TypeHash=@{
[int]32="hello!"
}
# should this work?$TypeHash.'[int]32'# because it's not so simple to ensure that that's not the case if we just # say 'parse everything as strings, unless... unless what, exactly?'
Yes, bringing hashtables into the picture complicates the situation, especially since Powershell - generally commendably - makes it so easy to treat them the same syntactically and even to convert one type to the other.
As for syntax: The ambiguity would go away if you:
default to string interpretation to the right of .
except if the 1st char is either $ or (, in which case the variable reference / subexpression / expression should be evaluated and the result as-is be used as a hashtable key / the stringified result be used as a property name.
In fact, all of the above already works, except that in the absence of either $ or (, a digit too as the 1st char. to the . right too causes evaluation as en expression, and that's where the trouble starts.
Why? Because the parser only considers a token that starts with a letter a member-name (property-name) token, as the following example shows:
PS> (([system.management.automation.psparser]::Tokenize('$obj.a1', [ref] $null)).Type)[-1]
Member # OK, recognized as a member name: 'a1' starts with with a *letter*
PS> (([system.management.automation.psparser]::Tokenize('$obj.1a', [ref] $null)).Type)[-1]
CommandArgument # NOT recognized as member name: '1a' starts with a *digit*.
In the latter case - and for any token that doesn't parse as Member - PowerShell then evaluates the token as a unary expression (if I understood Bruce Payette (@BrucePay) correctly).
In the case of property access, that currently gives us counter-intuitive behaviors in two scenarios:
$obj= [pscustomobject] @{ '1a'='one A'; '1e2'='one E two'; '100'='hundred' }
# As detailed in the original post:# An unexpected and confusing error, because 1a is interpreted as an *expression* and *fails*.
PS>$obj.1a
... Missing property name after reference operator. ...
PS>$obj.1e2
hundred # !! because $obj.1e2 turned into $obj.'100', # !! given that 1e2 as an expression becomes [double] 100, which stringifies to '100'
In the case of hashtable-key access, interpretation as a a numeric expression makes comparatively more sense, but you could argue that even there, for any non-string key, you should use:
either: $hash.([int] 32]), as shown (explicit expression use with (...))
or: [...]: $hash[[int] 32], [...] is an always-expression-only context
Limiting the syntax to that makes sense, especially considering that .-based hashtable-entry access is syntactic sugar borrowed from PROPERTY access for the unambiguous original[...] syntax - the latter explicitly and unambiguously allows only expressions.
In conclusion:
Changing the parsing to the right of . to require explicit opt-in to expression evaluation via $ or (:
is probably fine for property access, because it's hard to imagine anyone having relied on $obj.1e2 accessing property '100'.
is problematic for hashtable-key access, because existing code does rely on being able to specify numeric keys - see below.
Given the latter, the question is whether introducing divergent behavior (changing only property access) is ultimately more confusing than helpful.
Here's an example where existing code relies on numeric keys with .:
$null='abc'-match'(b)'; $Matches.1
b # OK - currently the same as: $Matches[1]
$Matches is a hashtable with integer keys containing the overall regex match (key 0), the 1st capture group (1), ...
If we changed the interpretation of .1 do refer to a string key '1', the above code would break (you'd have to use $Matches[1] or $Matches.(1) instead).
I always wondered how $Matches managed to work almost like an array, but still function as a hashtable. Very interesting... I'll have to keep that in mind.
All said, I personally have no qualms with how it currently functions. It could be improved a little, perhaps, but it's pretty consistent as it is, and it does seem like changing the behaviour for, say, a specific use case, seems to be... Unwise, and liable to cause other problems.
Yes, unfortunately; arguably, the . syntactic sugar for hashtables keys should have applied string-only interpretation from the start (and required differently typed keys to be accessed with [...] or even .(...)), but that ship has sailed.
say, a specific use case
It's more than a specific use case, but it is not common.
The best we can do under the circumstances is to provide a meaningful error message - see #6959
Issue-Questionideally support can be provided via other mechanisms, but sometimes folks do open an issue to get aResolution-AnsweredThe question is answered.WG-Enginecore PowerShell engine, interpreter, and runtimeWG-Languageparser, language semantics
Activity
BrucePay commentedon May 28, 2018
@george-chakhidze
$obj.{1a}works because the string value for the scriptblock[1a}is'1a'. So it's essentially equivalent to$obj.'1a'`.Michael Klement (@mklement0) It's not allowed because it's sufficiently anomalous that it's probably a mistake. Cat's walking on keyboards should not produce valid programs. If you really want to do it, then you have to make it explicit with quoting as in the case of this StackOverflow question (I assume this is what prompted the question?)
Now as it happens,
$foo.123works fine. This is because we allow expressions of the LHS of.and, of course,123is a legal expression.mklement0 commentedon May 28, 2018
Bruce Payette (@BrucePay):
Good to know that
$obj.{1a}only works accidentally, as a by-product of script-block stringification (I've updated the original post).Yes.
And it is tangible evidence that not only cats walking on keyboards produce such property names, especially in the world of JSON.
If that is truly the intent - and I don't think it should be - please provide a more meaningful error message.
Yes, as it happens - and I suggest not relying on things that happen.
Let me ask the opposite question: with respect to property access on objects, what good reason is there to interpret what's to the right of
.as anything other than a property name, i.e., a string (leaving property paths aside)?(Hashtable keys are a different story).
BrucePay commentedon May 28, 2018
Michael Klement (@mklement0) The issue in the stackoverflow question was not difficulty in figuring out that quoting the anomalous property name was required. The problem was that there was a typo in that name. Quoted or not made no difference since the property didn't exist.
Interestingly, JavaScript doesn't allow property names to start with a number either. You have you have to use indexing instead. That would seem to discourage the use of such names in JSON.
As one of the people making that decision and the person who wrote the original code, I can say - yes, that is the intent. The error message is currently that the property is missing. I suppose we could change it to "missing or invalid".
Poor phrasing on my part. It's not an accident, it's the expected consequence of the explicit decision to allow expressions on the LHS of '.', which in turn was done, in part, to deal with scenarios where objects might have non-conforming property names. As is the case in the stackoverflow question.
mklement0 commentedon May 28, 2018
Bruce Payette (@BrucePay):
Yes, the issue turned out to be a typo, but the fact remains that (a) digit-prefixed property names do occur, and (b) you do need explicit quoting to access them, and that may be surprising.
True, but JSON has long since outgrown use in the context of JavaScript only.
And, given that
var o = JSON.parse('{ "1a": "value" }')works just fine even in JavaScript, you could similarly ask why JavaScript doesn't allowo.1aand instead requireso['1a']- but that's obviously a separate debate.That would certainly help, though to be truly helpful it would have to say something along the lines of "when in doubt, quote the name".
Yet, typo aside, it is that very decision - treating what's to the right of
.as an expression ONLY - that prevents the use of the non-conforming property name at hand.Note that falling back to
[string]interpretation - if interpretation as an expression doesn't work - makes perfect sense, as that is already happening for non-digit-prefixed barewords a.k.a regular property access:With property access, the advantage of being able to use an expression to the right of
.is solely to calculate a property name - so that (ultimately) treating what's to the right as anything other than a string makes no sense.BrucePay commentedon May 29, 2018
Off the top of my head, I can't think of a single language that allows property names to start with a digit.
That's not what happens. The parser looks for either a propertyname token or a unary expression. If a propertyname token is found, it is used to look up the property. If an expression is found, that expression is evaluated, the result is converted to a string by calling
.ToString()and that string is used to look up the property.So you're saying that in
$x.abc+5the property name should beabc+5?. That would make things rather awkward.mklement0 commentedon May 29, 2018
We need to be careful to distinguish between allowing the definition of a property with a name that starts with a digit in principle on the one hand and allowing that name to be accessed with a bareword on the other hand.
As the JavaScript example showed, JavaScript supports the former, but not the latter, and that is currently also true of PowerShell.
The overall question, however, is whether there is a good reason for this asymmetry.
PowerShell is already unusual in allowing expressions in lieu of name literals as accessors, the way you describe.
No, it should be parsed as
$x.abc + 5, which is indeed what happens already.$x.(abc+5)- explicit use of(...)- is a different story, and there the current behavior makes sense too:abc+5is interpreted as a command and causes an error (unless there is a command literally namedabc+5).Well,
1ais, by the current rules, neither, so the question is what behavior makes sense in that case:Since the result of the expression is converted to a string, as you state, so as to be interpreted as a property name, it seems to me that giving up on something that looks like a unary numeric expression at first glance but then cannot be evaluated as such is unhelpful (especially with the current error message).
Use of a unary numeric expression as a property accessor seems unlikely to be helpful in most cases and it's far from obvious that this kind of interpretation does take place - in contrast with more readily recognizable expressions such as
$obj.$propNameor$obj.('foo' + 2)-I see the following ways to address this (there may be subtleties I'm missing):
(a) expand the definition of a property-name token to allow a leading digit.
(b) fall back to interpretation as a string literal if expression evaluation fails.
(c) report a meaningful error (it seems that we've already found common ground there).
Even with (b) in place the behavior could still be surprising, however:
What muddies the waters is that for hashtable keys, which can be of any type, it does make sense to distinguish between
@{ '1e2' = 'hi' }([string]key) and@{ 1e2 = 'hi' }([double]key, interpretation as unary expression that is a number literal), although you could argue that@{ 1a = 'hi' }- currently a different, but similarly obscure error (Missing closing '}' in statement block or type definition) - too should fall back to interpreting1aas a string.With hashtables too, if I were to guess, many users are unaware that keys are parsed as expressions if they don't start with a letter.
The ship has sailed, but I'd say that defaulting to string-literal interpretation with explicit opt-in to expression evaluation - similar to how
$and(at the start of tokens in argument mode signal a non-literal argument - would have made for a model that's easier to grasp and remember.vexx32 commentedon May 30, 2018
I'm inclined to agree with that, really. It should default to string interpretation unless explicitly cast otherwise. However, it becomes tricky to distinguish there between what is intended to be a variable cast and what is simply part of a string.
If you allow expressions to be recognised as strings in hashtable literals, then how is it supposed to treat type casts correctly?
mklement0 commentedon May 30, 2018
Thanks, Rain Sallow (/u/ta11ow) (@vexx32).
Yes, bringing hashtables into the picture complicates the situation, especially since Powershell - generally commendably - makes it so easy to treat them the same syntactically and even to convert one type to the other.
As for syntax: The ambiguity would go away if you:
default to string interpretation to the right of
.except if the 1st char is either
$or(, in which case the variable reference / subexpression / expression should be evaluated and the result as-is be used as a hashtable key / the stringified result be used as a property name.Applied to your example:
In fact, all of the above already works, except that in the absence of either
$or(, a digit too as the 1st char. to the.right too causes evaluation as en expression, and that's where the trouble starts.Why? Because the parser only considers a token that starts with a letter a member-name (property-name) token, as the following example shows:
In the latter case - and for any token that doesn't parse as
Member- PowerShell then evaluates the token as a unary expression (if I understood Bruce Payette (@BrucePay) correctly).In the case of property access, that currently gives us counter-intuitive behaviors in two scenarios:
In the case of hashtable-key access, interpretation as a a numeric expression makes comparatively more sense, but you could argue that even there, for any non-string key, you should use:
$hash.([int] 32]), as shown (explicit expression use with(...))[...]:$hash[[int] 32],[...]is an always-expression-only contextLimiting the syntax to that makes sense, especially considering that
.-based hashtable-entry access is syntactic sugar borrowed from PROPERTY access for the unambiguous original[...]syntax - the latter explicitly and unambiguously allows only expressions.In conclusion:
Changing the parsing to the right of
.to require explicit opt-in to expression evaluation via$or(:is probably fine for property access, because it's hard to imagine anyone having relied on
$obj.1e2accessing property'100'.is problematic for hashtable-key access, because existing code does rely on being able to specify numeric keys - see below.
Given the latter, the question is whether introducing divergent behavior (changing only property access) is ultimately more confusing than helpful.
Here's an example where existing code relies on numeric keys with
.:$Matchesis a hashtable with integer keys containing the overall regex match (key0), the 1st capture group (1), ...If we changed the interpretation of
.1do refer to a string key'1', the above code would break (you'd have to use$Matches[1]or$Matches.(1)instead).vexx32 commentedon May 30, 2018
I always wondered how
$Matchesmanaged to work almost like an array, but still function as a hashtable. Very interesting... I'll have to keep that in mind.All said, I personally have no qualms with how it currently functions. It could be improved a little, perhaps, but it's pretty consistent as it is, and it does seem like changing the behaviour for, say, a specific use case, seems to be... Unwise, and liable to cause other problems.
I don't really see an elegant solution here.
mklement0 commentedon May 30, 2018
Rain Sallow (/u/ta11ow) (@vexx32)
Yes, unfortunately; arguably, the
.syntactic sugar for hashtables keys should have applied string-only interpretation from the start (and required differently typed keys to be accessed with[...]or even.(...)), but that ship has sailed.It's more than a specific use case, but it is not common.
The best we can do under the circumstances is to provide a meaningful error message - see #6959