rustlintrust-compiler-plugin

How to find out what type a rustc::middle::ty::Ty represents?


For writing yet another lint in Rust, I need to make sure that the type of an Expr is actually an Option<_> (or any pointer to one). I have already walked any ptrs and rptrs to their conclusion and am left with a rustc::middle::ty that in my test case debugs to (manually formatted for better readability):

TyS { 
  sty: ty_enum(
    DefId { 
      krate: 2, 
      node: 117199 
    }, 
    Substs { 
      types: VecPerParamSpace {
        TypeSpace: [
          TyS { 
            sty: ty_int(i32), 
            flags: 0, 
            region_depth: 0 
          }
        ],
        SelfSpace: [], 
        FnSpace: [], 
      }, 
      regions: NonerasedRegions(
        VecPerParamSpace {
          TypeSpace: [], 
          SelfSpace: [], 
          FnSpace: [], 
        }
      )
    }
  ), 
  flags: 0, 
  region_depth: 0 
}

However, now I'm a bit lost – how do I find out if the TyS is actually an Option<_> type?


Solution

  • You need use with_path on the DefId. You will be provided an iterator over PathElems which you must consume.

    The following is a rough sketch, but should give you an array of Names if you tweak it a bit.

    if let ty_enum(did, ..) = ty.sty {
      tcx.with_path(did, |iter| iter.map(|elem| elem.name())).collect::<Vec<Name>>;
    }