1- use crate :: { engine:: translator:: utils:: OpPos , ir:: BranchOffset , Error } ;
1+ use crate :: { engine:: { translator:: utils:: OpPos , TranslationError } , ir:: BranchOffset , Error } ;
22use alloc:: vec:: Vec ;
33use core:: {
44 fmt:: { self , Display } ,
@@ -133,6 +133,24 @@ impl LabelRegistry {
133133 }
134134 }
135135
136+ /// Creates an initialized [`BranchOffset`] from `src` to `dst`.
137+ ///
138+ /// # Errors
139+ ///
140+ /// If the resulting [`BranchOffset`] is out of bounds.
141+ pub fn trace_branch_offset ( src : OpPos , dst : OpPos ) -> Result < BranchOffset , Error > {
142+ fn trace_offset32 ( src : OpPos , dst : OpPos ) -> Option < i32 > {
143+ let src = isize:: try_from ( usize:: from ( src) ) . ok ( ) ?;
144+ let dst = isize:: try_from ( usize:: from ( dst) ) . ok ( ) ?;
145+ let offset = dst. checked_sub ( src) ?;
146+ i32:: try_from ( offset) . ok ( )
147+ }
148+ let Some ( offset) = trace_offset32 ( src, dst) else {
149+ return Err ( Error :: from ( TranslationError :: BranchOffsetOutOfBounds ) )
150+ } ;
151+ Ok ( BranchOffset :: from ( offset) )
152+ }
153+
136154 /// Tries to resolve the `label`.
137155 ///
138156 /// Returns the proper `BranchOffset` in case the `label` has already been
@@ -147,7 +165,7 @@ impl LabelRegistry {
147165 ) -> Result < BranchOffset , Error > {
148166 let offset = match * self . get_label ( label) {
149167 Label :: Pinned ( target) => {
150- BranchOffset :: from_src_to_dst ( u32 :: from ( user) , u32 :: from ( target) ) ?
168+ Self :: trace_branch_offset ( user, target) ?
151169 }
152170 Label :: Unpinned => {
153171 self . users . push ( LabelUser :: new ( label, user) ) ;
@@ -205,8 +223,7 @@ impl Iterator for ResolvedUserIter<'_> {
205223 . registry
206224 . resolve_label ( next. label )
207225 . unwrap_or_else ( |err| panic ! ( "failed to resolve user: {err}" ) ) ;
208- let offset =
209- BranchOffset :: from_src_to_dst ( u32:: from ( src) , u32:: from ( dst) ) . map_err ( Into :: into) ;
226+ let offset = LabelRegistry :: trace_branch_offset ( src, dst) ;
210227 Some ( ( src, offset) )
211228 }
212229}
0 commit comments