Add support for making functions const#1536
Merged
bors merged 6 commits intorust-lang:masterfrom Nov 18, 2019
Merged
Conversation
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
PR rust-lang/rust#64906 adds the ability to write
const extern fnandconst unsafe extern fn, which will allow manys functions inlibcto becomeconst.This is particuarly useful for functions which correspond to C macros (e.g.
CMSG_SPACE). In C, these macros are constant expressions, allowing them to be used when declaring arrays. However, since the correspondinglibcfunctions are notconst, writing equivalent Rust code is impossible. Users must either perform an unecessary heap allocation, or pull inbindgento evaluate the macro for specific values (e.g.CMSG_SPACE(1)).However, the syntax
const extern fnis not currently parsed by rust. To allow libc to use this without breaking backwards compatibility (i.e. bumping the minimum Rust version), I've taken the following approach:extern-const-fnis added tolibc.f!macro has two versions, selected at compile-time by acfg_if. Whenextern-const-fnis enabled, the declaredf!macro passes through theconstkeyword from the macro user to the final definition (pub const unsafe extern fn foo. Whenextern-const-fnis disabled, theconstkeyword passed by the macro user is discarded, resulting in a plainpub extern const fnbeing declared.Unfortunately, I couldn't manage to get
macro_rulesto accept a normalconsttoken in the proper place (afterpub). I had to resort to placing it in curly brackets:The
f!macro then translates this to a function definition withconstin the proper position.I'd appreciate it if someone who's more familiar with
macro_rules!could see if I missed a way to get the desired syntax.