Skip to content

Use ptr::addr_of for offset calculations in Traverse's walk_* functions #17

@overlookmotel

Description

@overlookmotel

Traverse's walk_* functions are currently full of code like this:

walk_expression(
    traverser,
    (node as *mut u8).add(ancestor::OFFSET_BINARY_EXPRESSION_LEFT) as *mut Expression,
    ctx,
);

Ancestor methods contain similar code:

pub fn left(&self) -> &Expression<'a> {
    unsafe {
        &*((self.0 as *const u8).add(OFFSET_BINARY_EXPRESSION_LEFT) as *const Expression<'a>)
    }
}

Could probably use std::ptr::addr_of! and std::ptr::addr_of_mut! for these instead:

use std::ptr::addr_of_mut;

walk_expression(
    traverser,
    addr_of_mut!((*node).left),
    ctx,
);
use std::ptr::addr_of;

pub fn left(&self) -> &Expression<'a> {
    let node = self.0;
    unsafe { &*addr_of!((*node).left) }
}

Much easier to read, and can get rid of all the OFFSET_* constants.

I hadn't clocked that you can use addr_of! starting with another pointer, and deref that pointer without actually deref-ing it.

https://doc.rust-lang.org/std/ptr/macro.addr_of.html

However, I'd like to implement more transformers using upwards seeking first and run it through Miri before making any changes. Also addr_of! may affect performance (either positively or negatively).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Priority

    None yet

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions