Skip to content

array access expression

Cameron Purdy edited this page Apr 8, 2020 · 2 revisions

The ArrayAccessExpression uses the square-bracket notation to access or modify an array. The form is well-known:

a[b]

For example:

color = colors[i];
colors[i] = Red;

Additionally, the ArrayAccessExpression can be used to slice an array:

Range<Int> indexes = selectRange();
Color[] slice1 = colors[indexes];

The slice can also be specified as either last-inclusive or last-exclusive:

firstFive = list[0..4];
remainder = list[i, list.size);  // exclude the element at index=list.size

While these examples refer to the Array type, the ArrayAccessExpression is not hard-coded to any particular type, and the operators are type-agnostic:

@Op Example Description
[] v = a[i] Access an element
[]= a[i] = v Store an element
[..] slice = a[range] Slice using a Range
[[..]] slice = a[0..4] Slice using an inclusive-end Range
[[..)] slice = a[0..a.size) Slice using an exclusive-end Range

Generally, element-based access is achieved by implementing the UniformIndexed or Sequence interface, and the slice capability is achieved by implementing the Sliceable interface. However, the operators can be implemented in a bespoke manner as well, such as in the Map interface:

Map<String, Person> contacts = loadContacts();
Person? person = contacts[name];

Despite appearing to be primitive-type operators, Ecstasy has no primitive type system, and the input and output types of these operators are defined entirely by the types against which the operators execute. Specifically, the type of the expression a must have an unambiguously single best operator method (selected by the operator symbol and method name) that takes an argument of the type of expression b. The implicit type of the expression is the return type of the operator method.

The execution of the expression is an invocation of the selected operator method, against a target reference yielded by the expression a, passing one argument as yielded by the expression b; the result of the expression is the return value from the operator method.

The expression short-circuits if either expression a or b short-circuits.

The expression uses the default left-to-right definite assignment rules:

  • The VAS before a is the VAS before the expression.
  • The VAS before b is the VAS after a.
  • The VAS after the expression is the VAS after b.
    ArrayAccessExpression:
        PostfixExpression ArrayIndexes
        
    ArrayIndexes:
        [ ExpressionList ]
        
    ExpressionList:
        Expression
        ExpressionList , Expression