Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

gccrs#4574: Add lang owned box and box expression

Link: Rust-GCC/gccrs#4574

Note

This is important.

Box definition:

#![allow(unused)]
fn main() {
#[lang = "owned_box"]
#[fundamental]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Box<
    T: ?Sized,
    #[unstable(feature = "allocator_api", issue = "32838")] A: AllocRef = Global,
>(Unique<T>, A);
}

Box expression:

#![allow(unused)]
fn main() {
impl<T> Box<T> {
    pub fn new(x: T) -> Self {
        box x // box expression looks like this
    }
}
}

Objective

This PR implements the owned_box lang item and adds compiler support for box expressions.

Changes Made

  • Written AST -> HIR lowering for box expressions from scratch (including a new HIR class).
  • Completed the HIR -> GENERIC backend translation.
  • Added helper methods to resolve nested structures within boxes.
  • Implemented auto-deref logic for Box.

Why is this needed for alloc?

Box<T> is the core type for dynamic memory allocation in Rust. Supporting its specific compiler intrinsics and expressions is mandatory for the alloc crate.

Test Case

struct NonCopyStruct {
    id: i32,
}

impl NonCopyStruct {
    fn get_id(&self) -> i32 {
        self.id
    }
}

fn main() {
    let my_box: Box<NonCopyStruct> = Box::new(NonCopyStruct { id: 42 });
    let _moved_val = *my_box;

    let my_box2: Box<NonCopyStruct> = Box::new(NonCopyStruct { id: 100 });

    let val_id = my_box2.id;

    let val_method_id = my_box2.get_id();

    println!("id: {val_id}");
    println!("get_id: {val_method_id}");
}

The compiler can now correctly handle the instantiation of boxes, move semantics (*my_box), field accesses, and method calls on boxed types using the newly added auto-deref logic.