iximeow / yaxpeax-arch

fundamental traits to describe an architecture in the yaxpeax project
BSD Zero Clause License
11 stars 2 forks source link

U8Reader type inference ergonomics #3

Open meithecatte opened 1 year ago

meithecatte commented 1 year ago

rustc demands this monstrosity of a type annotation:

use yaxpeax_arch::{Decoder, Reader, U8Reader};

fn main() {
    let data: &[u8] = &[0x31, 0xc0, 0x50, 0x58];
    let mut reader = U8Reader::new(data);
    let decoder = yaxpeax_x86::amd64::InstDecoder::default();

    for _ in 0..3 {
        let addr = <U8Reader<'_> as Reader<u64, u8>>::total_offset(&mut reader);
        let inst = decoder.decode(&mut reader).unwrap();
        println!("{addr:04x} {inst}");
    }
}

This is because let addr: u64 = reader.total_offset() contains no hints as to what Item should be in Reader<u64, Item>. Moreover this can vary per callsite, so there's no way to hint it once and then forget it.

Am I missing something?

iximeow commented 1 year ago

oooh, that's interesting. i've typically used U8Reader and Reader<Addr, Word> in places that are generic over Arch (and so, Arch's address and word types). so in those cases, this looks more like:

{other stuff elided}
    let addr: A::Address = reader.total_offset();
    // do _something_ with addr - index a hashmap, call `AddressBase::to_linear`, ...

so in fact i'd never seen the full name written out like that!

the fact that U8Reader doesn't have a hint about the item type is kind of intentional - my hope has been for the reader type to be interchangeable when you might switch between ISAs (think interleaved aarch32/thumb code, for example). that's really why it's not U8Reader<Address, Word>.

the x86 decoders, at least, have InstDecoder::decode_slice that more looks like the case you're working with. then you'd have to use yaxpeax_arch::LengthedInstruction and inst.len() to get lengths, but it's a little less... verbose.

i've been idly wondering if there's a nice way to fit this in interfaces defined by yaxpeax-arch, and i'm not super sure?