rust - How to look up a method within the compiler given the type and a name? -


i have lint warns on x.len() == 0, suggesting use x.is_empty() instead. however, wanted rid of false positives if x has no is_empty(self: &self) method.

thus began quest methods within rustc.

first step, x: matched node of expr exprmethodcall(ref method, _, ref args) (and made sure args.len() == 1 , method.node.as_str() == "len") , used &*args[0], call expr on.

next step, type of x: can done using rustc::middle::ty::expr_ty(cx.tcx, expr). note rustc::middle::ty::ty (and not syntax::ast::ty, led confusion).

to methods, ctxt.impl_items , ctxt.trait_item_def_ids looked promising, defid type rustc::middle::ty::ty::ty_to_def_id(ty) , try ids. however, approach has few problems:

for

let x = [1, 2]; x.len() == 2 // <- lookee here 

i have no defid. ok though, because have ty_vec in case, , std::vec::vec known have both len() , is_empty().

the message ctxt.trait_item_def_ids has suitable entry trait is_empty method. alas, following example:

struct one; impl 1 { fn is_empty(self: &self) -> bool { false } } 

i got no traitoritemid impl item, bit unfortunate. can privy rustc me find impl items?

i got it! problem trying defid type, not impl. going through cx.tcx.inherent_impls.get(id) gave me vec of defids inherent impls, query via impl_items lookup implemented.

look in rust-clippy/src/len_zero.rs example implementation. edit: note implementation o(n) n number of methods of type (either direct impl or traits) – perhaps rustc someday allow faster lookup...


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -