In nqp, you can create an iterator on an nqp hash, or on an nqp list. I would like to be able to find out if a given nqp iterator is iterating over a hash or a list. Alas, I have not find a way to do that. They even seem to share the same name:
use nqp;
dd nqp::iterator(nqp::hash).^name; # BOOTIter
dd nqp::iterator(nqp::list).^name; # BOOTiter
Such an nqp iterator does appear to know of itself what type it is:
use nqp;
nqp::iterkey_s(nqp::iterator(nqp::list));
# This is not a hash iterator, it's a VMIter (BOOTIter)
Suggestions welcome!
I don't think you can at the moment at the nqp level except by doing as you've done:
use nqp;
nqp::iterkey_s(nqp::iterator(...));
CATCH {
when /'not a hash'/ { say 'list?' }
default { say 'hash?' }
}
That said, I don't know enough about nqp and nqp::hash
in particular to figure out how to get iterkey_s
to actually work.
Based on my investigations NQP has essentially no API for nqp::iterator
beyond just using it. And it just maps its iterator
op to the underlying VM.
The following is not a suggestion. I could say it's mostly to sympathize with your plight and encourage everyone to see the sheer simplicity and beauty of managed exceptions, but it's also a crazy thought about someone diving into MoarVM's guts to implement a horrible hack that might work on MoarVM if they were (un)lucky.
Suppose one could write:
class VMIter is repr('VMIter') { ... }
and then layout the class so it corresponds to the VMIter
struct defined in MoarVM.
Then, presuming that could be done, and the class could be mapped to the actual struct generated by MoarVM, then P6 code could read the hash vs array mode in the embedded MVMIterBody
struct.
And if that could be done, or were even contemplated, then perhaps I need to emphasize that folk shouldn't do crazy non-portable guts poking stuff like I just described.
Instead, there should be a sensible API that allows nqp iterator
s to distinguish between hashes and arrays in a way that can be used in nqp code. I'm sure that's what you wanted. Exploring the nqp sources and commits and doc suggests it's not there at the moment.
(And one closing far out there thought. What if one day there were is repr
variations that could also map to the native memory layouts of other underlying VMs like node or JVM? Does that even make sense? Sometime in the next decade? Maybe?)