Skip to content

Use from_fn for non-Copyable Rust types#192

Merged
nunoplopes merged 12 commits into
Cpp2Rust:masterfrom
lucic71:from_fn-non-copy
Jun 13, 2026
Merged

Use from_fn for non-Copyable Rust types#192
nunoplopes merged 12 commits into
Cpp2Rust:masterfrom
lucic71:from_fn-non-copy

Conversation

@lucic71

@lucic71 lucic71 commented Jun 12, 2026

Copy link
Copy Markdown
Contributor

In Rust, a struct is Copyable if it explicitly derives or implements Copy. All fields being Copy is not enough.

Add the derives attribute in the IR that lists all traits that a mapped Rust type derives. For example rustls_slice_bytes, a struct with Copyable fields, doesn't derive Copy. So derives contains only Default.

User defined types and builtin types also have their derives field filled. The entire PR is built around the following check:

    if (auto *rec = element_type->getAsRecordDecl()) {
      if (!RecordDerivesCopy(rec)) {
        return std::format("std::array::from_fn::<_, {}, _>(|_| {})",
                           size_as_string.c_str(), element_type_as_string);
      }
    }

Arrays of non-copyable types cannot be initialized with [non_copyable_default, N], they have to use the std::array:from_fn format.

@lucic71 lucic71 force-pushed the from_fn-non-copy branch 2 times, most recently from f11f71d to 71c227e Compare June 12, 2026 20:17
}
}
unsafe fn main_0() -> i32 {
let mut arr: [NonCopy; 3] = std::array::from_fn::<_, 3, _>(|_| <NonCopy>::default());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Uhm, I think we can use just let _arr: [NonCopy; 3] = Default::default();. No need for from_fn?

@lucic71 lucic71 Jun 12, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unfortunately no, Default::default() only works for array sizes < 32: https://godbolt.org/z/c5T6boGbq

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ahah, ok

@lucic71 lucic71 force-pushed the from_fn-non-copy branch from 71c227e to 4c56665 Compare June 12, 2026 21:18
@nunoplopes nunoplopes merged commit 8f79a34 into Cpp2Rust:master Jun 13, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants