@@ -14,10 +14,7 @@ use rustc_hir as hir;
14
14
use rustc_macros:: HashStable ;
15
15
use rustc_session:: CtfeBacktrace ;
16
16
use rustc_span:: { def_id:: DefId , Pos , Span } ;
17
- use std:: {
18
- any:: { Any , TypeId } ,
19
- fmt, mem,
20
- } ;
17
+ use std:: { any:: Any , fmt, mem} ;
21
18
22
19
#[ derive( Debug , Copy , Clone , PartialEq , Eq , HashStable , RustcEncodable , RustcDecodable ) ]
23
20
pub enum ErrorHandled {
@@ -513,32 +510,26 @@ impl fmt::Debug for ResourceExhaustionInfo {
513
510
}
514
511
}
515
512
513
+ /// A trait to work around not having trait object upcasting.
514
+ pub trait AsAny : Any {
515
+ fn as_any ( & self ) -> & dyn Any ;
516
+ }
517
+
518
+ impl < T : Any > AsAny for T {
519
+ #[ inline( always) ]
520
+ fn as_any ( & self ) -> & dyn Any {
521
+ self
522
+ }
523
+ }
524
+
516
525
/// A trait for machine-specific errors (or other "machine stop" conditions).
517
- pub trait MachineStopType : Any + fmt:: Debug + Send { }
526
+ pub trait MachineStopType : AsAny + fmt:: Debug + Send { }
518
527
impl MachineStopType for String { }
519
528
520
- // Copy-pasted from `any.rs`; there does not seem to be a way to re-use that.
521
529
impl dyn MachineStopType {
522
- pub fn is < T : Any > ( & self ) -> bool {
523
- // Get `TypeId` of the type this function is instantiated with.
524
- let t = TypeId :: of :: < T > ( ) ;
525
-
526
- // Get `TypeId` of the type in the trait object (`self`).
527
- let concrete = self . type_id ( ) ;
528
-
529
- // Compare both `TypeId`s on equality.
530
- t == concrete
531
- }
532
-
530
+ #[ inline( always) ]
533
531
pub fn downcast_ref < T : Any > ( & self ) -> Option < & T > {
534
- if self . is :: < T > ( ) {
535
- // SAFETY: just checked whether we are pointing to the correct type, and we can rely on
536
- // that check for memory safety because `Any` is implemented for all types; no other
537
- // impls can exist as they would conflict with our impl.
538
- unsafe { Some ( & * ( self as * const dyn MachineStopType as * const T ) ) }
539
- } else {
540
- None
541
- }
532
+ self . as_any ( ) . downcast_ref ( )
542
533
}
543
534
}
544
535
0 commit comments