apple/pkl · error

elementIndexOutOfRange

elementIndexOutOfRange

Error message

elementIndexOutOfRange

What it means

Thrown by Set.split(index) when the split index is out of range. The index must satisfy 0 <= index <= set.length; the error reports the offending index, the valid minimum 0, and the set's length, plus the collection itself.

Solutions

  1. Check 0 <= index <= set.length before calling split
  2. Clamp the index: math.max(0, math.min(idx, set.length))
  3. Verify any computed split point against the actual set length (see the 'Collection' value in the error)
  4. Remember split(n) with n == set.length is legal and yields (set, empty set)

Example fix

// before
set.split(set.length + 1)
// after
set.split(math.min(idx, set.length))
Defensive patterns

Strategy: validation

Validate before calling

function canSplit(s: Set, i: Int): Boolean = i >= 0 && i <= s.length

Type guard

function isValidSplitIndex(s: Set, i: Int): Boolean = i >= 0 && i <= s.length

Prevention

When it happens

Trigger: Calling someSet.split(n) where n < 0 or n > set.length. split(n) returns a pair of the first n elements and the rest, so only positions at or before the end are valid.

Common situations: Off-by-one errors using set.length as if it were invalid (it is valid — end split), computing the split point from another collection's size, or negative results from subtraction that were meant to be clamped.

Related errors


AI-assisted analysis of apple/pkl@f3efcbfc9b (2026-09-08). Data as JSON: /api/errors/a1ea768302125127. Report an issue: GitHub.

Appendix: source

Thrown at pkl-core/src/main/java/org/pkl/core/stdlib/base/SetNodes.java:139

    @Specialization
    protected boolean eval(VmSet self, VmCollection other) {
      return self.startsWith(other);
    }
  }

  public abstract static class endsWith extends ExternalMethod1Node {
    @Specialization
    protected boolean eval(VmSet self, VmCollection other) {
      return self.endsWith(other);
    }
  }

  public abstract static class split extends ExternalMethod1Node {
    @Specialization
    protected VmPair eval(VmSet self, long index) {
      if (index < 0 || index > self.getLength()) {
        CompilerDirectives.transferToInterpreter();
        throw exceptionBuilder()
            .evalError("elementIndexOutOfRange", index, 0, self.getLength())
            .withProgramValue("Collection", self)
            .build();
      }
      return self.split(index);
    }
  }

  public abstract static class splitOrNull extends ExternalMethod1Node {
    @Specialization
    protected Object eval(VmSet self, long index) {
      return self.splitOrNull(index);
    }
  }

  public abstract static class partition extends ExternalMethod1Node {
    @Child private ApplyVmFunction1Node applyLambdaNode = ApplyVmFunction1Node.create();

View on GitHub (pinned to f3efcbfc9b)