Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 309
llogiq Avatar asked Jun 04 '15 15:06

llogiq


People also ask

What does rustc do?

Rust alters the appearance of metal components. Rust replaces the sleek look of metal with a rougher, irregular surface. Rust also discolors the surface of metal objects. Rusted metal acquires a reddish or orange color.

How Rust code is compiled?

Rust code is monomorphized, which means making copies of all the generic code with the type parameters replaced by concrete types. To do this, we need to collect a list of what concrete types to generate code for. This is called monomorphization collection and it happens at the MIR level.

Is the Rust compiler written in Rust?

The Rust compiler is written in Rust, but I'm not sure what that has to do with the existence of beta or nightly, or why their existence would refute anything. Nightly exists so people can try new features and changes as they are being developed.


1 Answers

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>>;
}
like image 148
Manishearth Avatar answered Dec 07 '22 13:12

Manishearth