From c0b68eb35e70c01be8456b96064463fd95af5466 Mon Sep 17 00:00:00 2001 From: overlookmotel <557937+overlookmotel@users.noreply.github.com> Date: Wed, 14 May 2025 01:16:03 +0000 Subject: [PATCH] refactor(lexer): harden safety of transmute (#11013) Follow-on after #10933. It's preferable to include explicit type params in calls to `mem::transmute` rather than relying on type inference. This ensures any later changes won't inadvertently cause UB. Also expand the safety comment. --- crates/oxc_parser/src/lexer/token.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/oxc_parser/src/lexer/token.rs b/crates/oxc_parser/src/lexer/token.rs index 80376b7ef442c..181af88bcb05c 100644 --- a/crates/oxc_parser/src/lexer/token.rs +++ b/crates/oxc_parser/src/lexer/token.rs @@ -1,5 +1,7 @@ //! Token +use std::mem; + use oxc_span::Span; use super::kind::Kind; @@ -55,9 +57,10 @@ impl Token { #[inline] pub fn kind(&self) -> Kind { - // SAFETY: This conversion is safe because `Kind` is `#[repr(u8)]`, - // and we ensure the value stored is a valid `Kind` variant - unsafe { std::mem::transmute(((self.0 >> KIND_SHIFT) & KIND_MASK) as u8) } + // SAFETY: `Kind` is `#[repr(u8)]`. Only `Token::set_kind` alters these bits, + // and it sets them to the `u8` value of an existing `Kind`. + // So transmuting these bits back to `Kind` must produce a valid `Kind`. + unsafe { mem::transmute::(((self.0 >> KIND_SHIFT) & KIND_MASK) as u8) } } #[inline]