Skip to content

Add semantics for indexing into arrays with negative indices

Michael Aaron Murphy requested to merge huntergoldstein:negative_range_idx into master

Created by: huntergoldstein

Problem: There is no way to refer to, for example, the second to last element of an array aside from @array[len(array) - 2] where len gets the number of elements in an array.

Solution: Extend Ion's syntax to allow for this through negative indices, such as in Python:

$ let array = [ 1 2 3 4 5 6 ]
$ echo @array[-1]
6
$ echo @array[1..-2]
2 3 4

Changes introduced by this pull request:

  • Introduce new data structures that represent indexing from the end of an array
  • Update parsing of array ranges and indices to use these new structures

Drawbacks:

  • parser::shell_expand::words has become a bit of a mess with a bunch of Index named classes everywhere. As discussed in #263 (closed) it would be useful to refactor this and move some of the logic repeated at call-sites, but that's a little too broad for a single PR.

TODOs:

  • Outstanding bug where @array[2...-2] results in an empty output for arrays where it is well defined.
  • Add in more regression / unit tests, including failure-like cases

State: WIP

Blocking/related: Closes #263 (closed)

Merge request reports