B5122: a container's iteration functions might not visit its elements in order
Catalog status: active. Default severity: error. Stable name: iteration-order. Family: Contracts and termination.
Verada reasons about the elements of a container whose type has Iterable as the cursors that have an element (Has_Element), visited from First upwards by Next. A quantified expression or a reduction over the elements, in a contract or anywhere the prover reads it, relies on that. So where a program uses it, the prover proves it of the type's functions, for every container: the cursors that have an element are integers from First up with none missing, and Next of one is the next integer. When that might not hold, B5122 is reported at the type, and the program is not proved.
The library's vectors, ordered sets, maps and dictionaries number their elements from 1, and their functions are proved.
Example (Vada)
-- A container whose `Next` skips: the order Verada's model of its elements assumes is not proved.
package Bags is
type Store is array (1 .. 8) of Integer;
type Bag is record
Items : Store := [others => 0];
end record
with Iterable => (First => First, Next => Next, Has_Element => Has_Element, Element => Element);
function First (B : Bag) return Natural is (1);
function Next (B : Bag; P : Natural) return Natural is (if P < 7 then P + 2 else 9);
function Has_Element (B : Bag; P : Natural) return Boolean is (P in 1 .. 8);
function Element (B : Bag; P : Natural) return Integer is (B.Items (P))
with Pre => P in 1 .. 8;
end Bags;Next visits 1, 3, 5 and 7, but Has_Element admits 1 .. 8.
What to do
Make the functions agree: number the cursors from First, have Has_Element admit the numbers in use and no others, and have Next add one ((if P < Natural'Last then P + 1 else P)). To visit only some elements, filter them where they are used (for E of C when ...).
Regression source and further reading
Complete regression example: source, command arguments and expected results. The fixture deliberately reproduces this diagnostic.
See contracts and termination, the code index, and diagnostic interpretation for modes, replay, fix-its and JSON.