Skip to content

Commit c0b68eb

Browse files
committed
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.
1 parent cc0112f commit c0b68eb

1 file changed

Lines changed: 6 additions & 3 deletions

File tree

crates/oxc_parser/src/lexer/token.rs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
//! Token
22
3+
use std::mem;
4+
35
use oxc_span::Span;
46

57
use super::kind::Kind;
@@ -55,9 +57,10 @@ impl Token {
5557

5658
#[inline]
5759
pub fn kind(&self) -> Kind {
58-
// SAFETY: This conversion is safe because `Kind` is `#[repr(u8)]`,
59-
// and we ensure the value stored is a valid `Kind` variant
60-
unsafe { std::mem::transmute(((self.0 >> KIND_SHIFT) & KIND_MASK) as u8) }
60+
// SAFETY: `Kind` is `#[repr(u8)]`. Only `Token::set_kind` alters these bits,
61+
// and it sets them to the `u8` value of an existing `Kind`.
62+
// So transmuting these bits back to `Kind` must produce a valid `Kind`.
63+
unsafe { mem::transmute::<u8, Kind>(((self.0 >> KIND_SHIFT) & KIND_MASK) as u8) }
6164
}
6265

6366
#[inline]

0 commit comments

Comments
 (0)