-
Notifications
You must be signed in to change notification settings - Fork 9
/
jumptodefmap.rs
360 lines (314 loc) · 12.1 KB
/
jumptodefmap.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
use std::io;
use rf_common::*;
use syntax::ast;
use rustc::middle::{ty,typeck};
use syntax::codemap::{BytePos, Pos};
use rsfind::ShowDefMode;
use std::hash::Hash;
//use rustc::middle::typeck::*;-
use find_ast_node::{FNodeInfoMap, FNodeInfo, AstNode_, NodeTreeLoc, find_node_tree_loc_at_byte_pos,
build_node_info_map, get_node_source, astnode_expr,
ToJsonStr, ToJsonStrFc, AstNodeAccessors};
use rustfindctx::{RustFindCtx,get_source_loc};
use codemaput::{ZTextFilePos,byte_pos_from_text_file_pos_str};
use rf_ast_ut::*;
use util::flatten_to_str_ng; //todo - why is qualifying manually not working?!
use timer::Timer;
//use super::rf_use_ast;
//todo - simple declartions of types shouldn't mean bringing in associated code modules ?
// a user that needs the type JumpToDefMap needn't necaserily need all its functions...
pub macro_rules! if_some {
($b:ident in $a:expr then $c:expr)=>(
match $a {
Some($b)=>$c,
None=>{}
}
);
}
// todo - a multi-crate build might want refs outside the crate?
pub type JumpToRefMap = MultiMap<ast::NodeId, ast::NodeId>;
pub type JumpToDefMap = HashMap<ast::NodeId,ast::DefId> ;
/// NodeMaps, collects together:
/// FNodeInfoMap - map{NodeIds=>FNodeInfo} - universal AST node wrappers
/// JumpToDefMap - connects nodes to DefIds (external nodes)
/// JumpToRefMap - inverse of JumpToDefMap, but only needs internal crate nodes.
pub fn lookup_def_of_expr(dc:&RustFindCtx, expr:&ast::Expr, nodeinfomap:&FNodeInfoMap, _: &HashMap<ast::NodeId,ast::DefId>)->Option<ast::DefId>
{
match expr.node {
// handle methods-calls
ast::ExprMethodCall(ref call_ident, ref call_type_params, ref call_args)=>{
// Currently unused
// let rec_ty_node= astnode_expr(*receiver).ty_node_id();
// let rec_ty_node1= dc.tycx.node_types.find(&(*id as uint));
let method_map =&dc.ca.ty_cx.method_map;
let method_call=typeck::MethodCall{expr_id:expr.id, autoderef:0}; // TODO is that e.id or call_ident...
//cfg[DEBUG] io::println(format!("e.id={:?} call_ident={:?}", e.id, call_ident.name));
match method_map.borrow().get(&method_call).origin {
typeck::MethodStatic(def_id)=>
return Some(def_id),
typeck::MethodObject(_)=>
return None,
typeck::MethodParam(mp)=>{
let trait_method_def_ids = dc.tycx_ref().trait_method_def_ids.borrow();
match trait_method_def_ids.find(&mp.trait_id) {
None=>{},
Some(method_def_ids)=>{
return Some(*method_def_ids.get(mp.method_num))
}
}
}
}
},
// handle struct-fields? "object.field"
ast::ExprField(ref object_expr, ref ident, _)=>{
// we want the type of the object..
let node_types = dc.tycx_ref().node_types.borrow();
let obj_ty=node_types.find(&(object_expr.id as uint));
let tydef=/*rf_ast_ut::*/auto_deref_ty(ty::get(*obj_ty.unwrap()));
match tydef.sty {
ty::ty_struct(def,_)=> {
let node_to_show=/*rf_ast_ut::*/find_named_struct_field(dc.tycx_ref(), def.node, ident).unwrap_or(def);
return Some(node_to_show);//mk_result(dc,m,node_spans,node_to_show,"(struct_field)");
},
_=>return None
}
},
_=>{}
};
None
}
// TODO - Do this job as a visitor of the original rust AST.
pub fn lookup_def_node_of_node(dc:&RustFindCtx,node:&AstNode_, nodeinfomap:&FNodeInfoMap, ndm: &HashMap<ast::NodeId,ast::DefId>)->Option<ast::DefId> {
match *node {
astnode_expr(e)=>{
match lookup_def_of_expr(dc, e, nodeinfomap, ndm) {
Some(x)=>return Some(x),
None=>{}
}
},
_=>{},
};
// handle everything else
match node.rf_ty_node_id() {
Some(id) =>{
let (def_id, _)= def_info_from_node_id(dc,nodeinfomap,id);
return if def_id != ast::DefId{krate:0,node:id} {Some(def_id)} else {None}
},
None=> {}
};
return None;
}
pub fn build_jump_to_def_map(dc:&RustFindCtx, nim: &FNodeInfoMap,nd:&HashMap<ast::NodeId,ast::DefId>)->Box<JumpToDefMap>{
// todo: NodeId->AStNode .. lookup_def_ inner functionality extracted
let prof=::timer::Profiler::new("build_jump_to_def_map");
let mut jdm=box HashMap::new();
for (k,node_info) in nim.iter() {
match lookup_def_node_of_node(dc,&node_info.rf_node(), nim,nd) {
None=>{},
Some(def_node_id)=>{
{
jdm.insert(*k,def_node_id);
}
}
}
}
jdm
}
// Replacement to eliminate our AST copy!
/*
struct JumpToDefMapVisitor {
dc:&RustFindCtx,
nim:&FNodeInfoMap,
nd:&HashMap<st::NodeId,asd::DefId>,
}
impl<E> Visitor<E> for JumpToDefMapVisitor {
fn visit_expr(&mut self, expr:&Expr, e:E) {
// continue...
walk_expr(self,expr,e);
}
}
*/
pub fn def_info_from_node_id<'a,'b>(dc:&'a RustFindCtx, node_info:&'b FNodeInfoMap, id:ast::NodeId)->(ast::DefId,Option<&'b FNodeInfo>) {
let crate_num=0;
let def_map = dc.tycx_ref().def_map.borrow();
match def_map.find(&id) { // finds a def..
Some(a)=>{
match get_def_id(crate_num,*a){
Some(b)=>
(b,node_info.find(&b.node)),
// match b.crate {
// 0=>(b.node,node_info.find(&b.node)),
// _ => (id as int, None)
// },
None=>(ast::DefId{krate:0,node:id},None)
}
},
None=>(ast::DefId{krate:0,node:id},None)
}
}
pub fn dump_json(dc:&RustFindCtx) {
// TODO: full/partial options - we currently wwrite out all the nodes we find.
// need option to only write out nodes that map to definitons.
io::println("{");
io::println("\tcode_map:[");
// for dc.sess.codemap.files.iter().advance |f| {
let files = dc.codemap().files.borrow();
for f in files.iter() {
let lines = f.lines.borrow();
print!("\t\t\\{ name:\"{}\"", f.name);
print!("\tglobal_start_pos:{},", f.start_pos.to_uint().to_str());
print!("\tlength:{},", (f.src.len()).to_str());
print!("\tnum_lines:{},", lines.len().to_str());
print!("\tlines:[\n{},", flatten_to_str_ng(&*lines, |&x|{(x-f.start_pos).to_uint()} ,","));
print!("\n\t\t]\n\t\\},\n");
}
io::println("\t]");
io::println("\tnode_spans:");
let nim=build_node_info_map(dc.crate_);
let node_def_node = build_node_def_node_table(dc);
let jdm=build_jump_to_def_map(dc, &nim,node_def_node);
io::println(nim.to_json_str(dc).as_slice());
io::println(",");
io::println("\tnode_defs [\n");
io::println(jdm.to_json_str().as_slice());
io::println("\t],\n");
io::println("\tdef_ids:");
io::println(node_def_node.to_json_str().as_slice());
io::println("}");
}
pub fn lookup_def_at_text_file_pos(dc:&RustFindCtx, tfp:&ZTextFilePos, show_mode:ShowDefMode)->Option<StrBuf> {
match tfp.to_byte_pos(dc.tycx_ref()) {
None=>None,
Some(bp)=>lookup_def_at_byte_pos(dc,bp,show_mode)
}
}
pub fn lookup_def_at_text_file_pos_str(dc:&RustFindCtx,file_pos_str:&str, show_mode:ShowDefMode)->Option<StrBuf> {
match byte_pos_from_text_file_pos_str(dc,file_pos_str) {
None=>None,
Some(bp)=>lookup_def_at_byte_pos(dc,bp,show_mode),
}
}
pub fn node_id_from_text_file_pos_str(dc:&RustFindCtx, file_pos_str:&str)->Option<ast::NodeId> {
match node_from_text_file_pos_str(dc, file_pos_str) {
None=>None,
Some(an)=>an.rf_get_id()
}
}
pub fn node_from_text_file_pos_str(dc:&RustFindCtx, file_pos_str:&str)->Option<AstNode_> {
match byte_pos_from_text_file_pos_str(dc,file_pos_str) {
Some(bp)=>{let ndt=find_node_tree_loc_at_byte_pos(dc.crate_,bp); Some(*ndt.last().get_ref().clone())},
None=>None
}
}
pub fn lookup_def_at_byte_pos(dc:&RustFindCtx, bp:BytePos, m:ShowDefMode)->Option<StrBuf> {
let ndt=find_node_tree_loc_at_byte_pos(dc.crate_,bp);
lookup_def_of_node_tree_loc(dc,&ndt,m)
}
pub fn lookup_def_of_node_tree_loc(dc:&RustFindCtx,node_tree_loc:&NodeTreeLoc,m:ShowDefMode)->Option<StrBuf> {
lookup_def_of_node(dc,*node_tree_loc.last().get_ref(),m)
}
pub fn lookup_def_of_node(dc: &RustFindCtx, node: &AstNode_, m: ShowDefMode)->Option<StrBuf> {
io::println("def of node:"+node.rf_get_id().unwrap_or(0).to_str());
let node_spans=build_node_info_map(dc.crate_);
let node_def_node = build_node_def_node_table(dc);
lookup_def_of_node_sub(dc,node,m,&node_spans,node_def_node)
}
pub fn lookup_def_of_node_sub(dc:&RustFindCtx,node:&AstNode_,m:ShowDefMode,nim:&FNodeInfoMap, node_def_node:&HashMap<ast::NodeId,ast::DefId>)->Option<StrBuf> {
// TODO - cache outside?
fn mk_result(dc:&RustFindCtx, m:ShowDefMode, nim:&FNodeInfoMap, def_node_id:ast::DefId, _: &str)->Option<StrBuf> {
if def_node_id.krate != 0 {
Some(StrBuf::from_str("{cross-crate-def not implemented, ").append(def_node_id.to_str().as_slice()).append("}"))
}
else {
match nim.find(&def_node_id.node) {
None=>None,
Some(def_info)=>{
let loc=get_source_loc(dc,def_info.rf_span().lo);
let def_pos_str=
StrBuf::new()
.append(loc.file.name.as_slice())
.append(":")
.append(loc.line.to_str().as_slice())
.append(": ")
.append(
match m {
SDM_LineCol=>loc.col.to_uint().to_str().to_strbuf().append(": "),
_ =>StrBuf::new()
}.as_slice()
)
.append("\n");
return match m{
SDM_Source=>Some(def_pos_str.append( get_node_source(dc.tycx_ref(),nim, def_node_id).as_slice()).append("\n") ),
SDM_GeditCmd=>Some(StrBuf::from_str("+").append(loc.line.to_str().as_slice()).append(" ").append(loc.file.name.as_slice()).append(" ")),
_ => Some(def_pos_str)
};
}
}
}
}
match lookup_def_node_of_node(dc, node, nim, node_def_node) {
None=>None,
Some(def_node_id)=>mk_result(dc,m, nim,def_node_id, "")
}
}
pub fn make_jump_to_def_map(dc:&RustFindCtx)->( FNodeInfoMap, Box<HashMap<ast::NodeId,ast::DefId>>,Box<JumpToDefMap>)
{
let t = Profiler::new("make_jdm");
let nim=build_node_info_map(dc.crate_);
let ndm=build_node_def_node_table(dc);
let jdm=build_jump_to_def_map(dc, &nim,ndm);
(nim,ndm,jdm)
}
/// K:[V] insert(K, V) for many V; find(K)->[V]
/// todo - can just compose it as hashmap<K,Vec<V>>
pub struct MultiMap<K,V> {
next_index:uint,
indices:HashMap<K,uint>,
items:Vec<Vec<V>>,
empty:Vec<V>
}
impl<'a,K:Hash+TotalEq,V> MultiMap<K,V> {
pub fn new()->MultiMap<K,V> {
MultiMap{ next_index:0, indices:HashMap::new(), items:Vec::new(), empty:Vec::new() }
}
pub fn find(&'a self, k:K)->&'a Vec<V> {
// TODO - return iterator, not collection
match self.indices.find(&k) {
None=>&self.empty,
Some(&ix)=>self.items.get(ix)
}
}
pub fn insert(&'a mut self, k:K,v:V) {
let ix=match self.indices.find(&k) {
None=>{ self.indices.insert(k,self.next_index); self.next_index+=1; self.items.push(Vec::new()); self.next_index-1},
Some(&ix)=> ix
};
self.items.get_mut(ix).push(v);
}
}
pub fn build_node_def_node_table(dc:&RustFindCtx)->Box<HashMap<ast::NodeId, ast::DefId>>
{
let mut r=box HashMap::new();
let curr_crate_id_hack=0; // TODO WHAT IS CRATE ID REALLY?!
for (id, _t) in dc.tycx_ref().node_types.borrow().iter() { //range(0, dc.tycx.next_id.get() as uint) {
//let id = id as ast::NodeId;
if_some!(def in dc.tycx_ref().def_map.borrow().find(&(*id as u32)) then { // finds a def..
if_some!(did in get_def_id(curr_crate_id_hack,*def) then {
r.insert(*id as ast::NodeId,did);
})
});
}
r
}
pub fn def_node_id_from_node_id(dc:&RustFindCtx, id:ast::NodeId)->ast::NodeId {
let crate_num=0; // TODO - whats crate Id really???
match dc.tycx_ref().def_map.borrow().find(&id) { // finds a def..
Some(a)=>{
match get_def_id(crate_num,*a) {
Some(b)=>b.node,
None=>id
}
},
None=>(id) // no definition? say its its own definition
}
}