rust-lang / rust-lang/rust

`final fn` and vtables

Open
#160,552 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-discussion F-final_associated_functions T-lang
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

It seems like there's a couple different visions for final fn related to dyn Trait, and I think we need to resolve them.

Is it:

  • Always statically dispatched, like it was on an extension trait?
  • Always in the vtable, like it was a normal method?
  • Something in between depending whether the method is dyn-safe?

Notably, just because it can't be overridden doesn't mean that there's no reason to put it in the vtable, since the entry in the vtable can be substantially more optimized.

For example, https://doc.rust-lang.org/nightly/std/slice/fn.range.html is currently a function in the module because people depend on it for unsoundness. One reason to have final fn is that it'd let us move it into RangeBounds since people wouldn't be able to override the provided implementation and thus wouldn't be able to cause unsoundness.

But consider what happens if the dyn RangeBounds<usize> in question is actually RangeFull:

  • With slice_range not in the vtable, then contains needs to make two vtable calls then match on the Bound<&usize> that comes back in order to create the Range<usize>.
  • With slice_range in the vtable, then contains makes only one vtable call, which trivially returns the correct Range<usize> without needing any matching at all because the slice_range in the vtable is optimized knowing that it's a RangeFull and thus it just returns 0..bounds.end without doing any matching or comparing.

So it would be a shame, IMHO, if we made final fn have to be the things that performs worse. After all, there are other ways to add helpers, but not other ways to have things in the vtable.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by comparing the issue's three proposed dispatch models for final fn on dyn Trait, using RangeBounds, slice_range, contains, and RangeFull as the concrete example. Determine whether the intended design places methods in vtables based on dyn-safety and optimization, then document a resolved rule and its implications for the example.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Quiet
Clarity
Needs clarification
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.