Skip to content

Commit

Permalink
fix(syntax): prevent creating invalid u32 IDs (#4675)
Browse files Browse the repository at this point in the history
Panic if try to create an `AstNodeId`, `ReferenceId`, `ScopeId` or `SymbolId` from a `usize` which can't be stored as a `u32`.

Previously we checked for `u32::MAX`, but didn't check for numbers larger than that.
  • Loading branch information
overlookmotel committed Aug 6, 2024
1 parent e3abdfa commit 9f8f299
Show file tree
Hide file tree
Showing 4 changed files with 12 additions and 4 deletions.
4 changes: 3 additions & 1 deletion crates/oxc_syntax/src/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@ impl AstNodeId {
impl Idx for AstNodeId {
#[allow(clippy::cast_possible_truncation)]
fn from_usize(idx: usize) -> Self {
Self(NonMaxU32::new(idx as u32).unwrap())
assert!(idx < u32::MAX as usize);
// SAFETY: We just checked `idx` is valid for `NonMaxU32`
Self(unsafe { NonMaxU32::new_unchecked(idx as u32) })
}

fn index(self) -> usize {
Expand Down
4 changes: 3 additions & 1 deletion crates/oxc_syntax/src/reference.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ pub struct ReferenceId(NonMaxU32);
impl Idx for ReferenceId {
#[allow(clippy::cast_possible_truncation)]
fn from_usize(idx: usize) -> Self {
Self(NonMaxU32::new(idx as u32).unwrap())
assert!(idx < u32::MAX as usize);
// SAFETY: We just checked `idx` is valid for `NonMaxU32`
Self(unsafe { NonMaxU32::new_unchecked(idx as u32) })
}

fn index(self) -> usize {
Expand Down
4 changes: 3 additions & 1 deletion crates/oxc_syntax/src/scope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@ impl ScopeId {
impl Idx for ScopeId {
#[allow(clippy::cast_possible_truncation)]
fn from_usize(idx: usize) -> Self {
Self(NonMaxU32::new(idx as u32).unwrap())
assert!(idx < u32::MAX as usize);
// SAFETY: We just checked `idx` is valid for `NonMaxU32`
Self(unsafe { NonMaxU32::new_unchecked(idx as u32) })
}

fn index(self) -> usize {
Expand Down
4 changes: 3 additions & 1 deletion crates/oxc_syntax/src/symbol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ pub struct SymbolId(NonMaxU32);
impl Idx for SymbolId {
#[allow(clippy::cast_possible_truncation)]
fn from_usize(idx: usize) -> Self {
Self(NonMaxU32::new(idx as u32).unwrap())
assert!(idx < u32::MAX as usize);
// SAFETY: We just checked `idx` is valid for `NonMaxU32`
Self(unsafe { NonMaxU32::new_unchecked(idx as u32) })
}

fn index(self) -> usize {
Expand Down

0 comments on commit 9f8f299

Please sign in to comment.