Fix indexing for arrays with non-zero base #1824
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Currently IronPython ignores the lowerbound of a CLI array and always treats the array as 0-based. Assume
arr
is a 1-based 2x2 matrix. UsingSetValue
orGetValue
requires using 1-based indices, but when using subscripts all indices are must be shifted down by 1. This is not .NET-compliant.After this PR:
This puts IronPython on par with C#:
Notes on indexing in C#
The only way to create non-zero-based arrays in C# is by using
Array.CreateInstance
, which returns an object of abstract typeArray
. This type does not implement the index operator; to use it, the array has to be downcast to the concrete (native) type. Hence the cast to(string[,])
above is necessary.Actually, the concrete type of an non-zero-based array is not
string[,]
butstring[*,*]
. But a cast(string[*,*])
in C# is syntactically invalid. The compiler accepts cast(string[,])
but interprets it as(string[*,*])
. That is,var arr
isstring[*,*] arr
as it were.Surprisingly, this is only supported for higher dimensional arrays; for 1-dimensional arrays casting from 1-based string array to
string[]
results in a compile error of invalid cast fromstring[*]
tostring[]
. In practice this means that 1-based 1-dimentional arrays cannot be indexed in C# using the index operator. I can only speculate why it is so.IronPython, being a dynamic language, does not require casting and an array of any type can be indexed using the index operator.
Summary of indexing of CLI arrays in IronPython:
Comparison to indexing in C# and CPython:
System.Index
with 1-dim arrays only; then IronPython indexing is C# compliant (as well as CPython compliant) in principle (support forSystem.Index
is not implemented).For more detailed explanation of indexing see #1828 (comment)