Given an expression of the form
for $p at $i in SEQ
where $i = EXP
Saxon performs an incorrect optimization rewrite in the case where EXP contains a reference to the variable $p. The expression is rewritten as
for $p in SEQ[position() = EXP]
which makes the reference to $p out of scope, causing the error message
*** Internal Saxon error: Unbound local variable encountered
A fix is in Subversion. Test case qxmp340 added.