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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
use std::fs::File;
use std::io::Read;
use std::{vec, fmt};
use std::path;
use std::io;
use std::cell::RefCell;
use std::collections::HashMap;
use std::ops::Deref;
use std::slice;
use std::cmp::{min, max};
use std::iter::{Fuse, Iterator};
use codeiter::StmtIndicesIter;
use typed_arena::Arena;
use scopes;
use nameres;
use ast;
use codecleaner;
#[derive(Debug,Clone,Copy,PartialEq)]
pub enum MatchType {
Struct,
Module,
MatchArm,
Function,
Crate,
Let,
IfLet,
WhileLet,
For,
StructField,
Impl,
Enum,
EnumVariant,
Type,
FnArg,
Trait,
Const,
Static
}
#[derive(Debug,Clone,Copy)]
pub enum SearchType {
ExactMatch,
StartsWith
}
#[derive(Debug,Clone,Copy)]
pub enum Namespace {
TypeNamespace,
ValueNamespace,
BothNamespaces
}
#[derive(Debug,Clone,Copy)]
pub enum CompletionType {
CompleteField,
CompletePath
}
#[derive(Clone)]
pub struct Match {
pub matchstr: String,
pub filepath: path::PathBuf,
pub point: usize,
pub local: bool,
pub mtype: MatchType,
pub contextstr: String,
pub generic_args: Vec<String>,
pub generic_types: Vec<PathSearch>,
}
impl Match {
pub fn with_generic_types(&self, generic_types: Vec<PathSearch>) -> Match {
Match {
matchstr: self.matchstr.clone(),
filepath: self.filepath.clone(),
point: self.point,
local: self.local,
mtype: self.mtype,
contextstr: self.contextstr.clone(),
generic_args: self.generic_args.clone(),
generic_types: generic_types,
}
}
}
impl fmt::Debug for Match {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Match [{:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?} |{}|]",
self.matchstr,
self.filepath.to_str(),
self.point,
self.local,
self.mtype,
self.generic_args,
self.generic_types,
self.contextstr)
}
}
#[derive(Clone)]
pub struct Scope {
pub filepath: path::PathBuf,
pub point: usize
}
impl Scope {
pub fn from_match(m: &Match) -> Scope {
Scope{ filepath: m.filepath.clone(), point: m.point }
}
}
impl fmt::Debug for Scope {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Scope [{:?}, {:?}]",
self.filepath.to_str(),
self.point)
}
}
#[derive(Debug,Clone)]
pub enum Ty {
TyMatch(Match),
TyPathSearch(Path, Scope),
TyTuple(Vec<Ty>),
TyMatchVec(Vec<Match>),
TyUnsupported
}
#[derive(Clone)]
pub struct Path {
pub global: bool,
pub segments: Vec<PathSegment>
}
impl Path {
pub fn generic_types(&self) -> ::std::slice::Iter<Path> {
self.segments[self.segments.len()-1].types.iter()
}
pub fn from_vec(global: bool, v: Vec<&str>) -> Path {
let segs = v
.into_iter()
.map(|x| PathSegment{ name: x.to_owned(), types: Vec::new() })
.collect::<Vec<_>>();
Path{ global: global, segments: segs }
}
pub fn from_svec(global: bool, v: Vec<String>) -> Path {
let segs = v
.into_iter()
.map(|x| PathSegment{ name: x, types: Vec::new() })
.collect::<Vec<_>>();
Path{ global: global, segments: segs }
}
}
impl fmt::Debug for Path {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "P["));
let mut first = true;
for seg in &self.segments {
if first {
try!(write!(f, "{}", seg.name));
first = false;
} else {
try!(write!(f, "::{}", seg.name));
}
if !seg.types.is_empty() {
try!(write!(f, "<"));
let mut tfirst = true;
for typath in &seg.types {
if tfirst {
try!(write!(f, "{:?}", typath));
tfirst = false;
} else {
try!(write!(f, ",{:?}", typath))
}
}
try!(write!(f, ">"));
}
}
write!(f, "]")
}
}
#[derive(Debug,Clone)]
pub struct PathSegment {
pub name: String,
pub types: Vec<Path>
}
#[derive(Clone)]
pub struct PathSearch {
pub path: Path,
pub filepath: path::PathBuf,
pub point: usize
}
impl fmt::Debug for PathSearch {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Search [{:?}, {:?}, {:?}]",
self.path,
self.filepath.to_str(),
self.point)
}
}
pub struct IndexedSource {
pub code: String,
pub idx: Vec<(usize, usize)>
}
#[derive(Clone,Copy)]
pub struct Src<'c> {
pub src: &'c IndexedSource,
pub from: usize,
pub to: usize
}
impl IndexedSource {
pub fn new(src: String) -> IndexedSource {
let indices = codecleaner::code_chunks(&src).collect();
IndexedSource {
code: src,
idx: indices
}
}
pub fn with_src(&self, new_src: String) -> IndexedSource {
IndexedSource {
code: new_src,
idx: self.idx.clone()
}
}
pub fn as_ref(&self) -> Src {
Src {
src: self,
from: 0,
to: self.len()
}
}
}
impl<'c> Src<'c> {
pub fn iter_stmts(&self) -> Fuse<StmtIndicesIter<CodeChunkIter>> {
StmtIndicesIter::from_parts(&self[..], self.chunk_indices())
}
pub fn from(&self, from: usize) -> Src<'c> {
Src {
src: self.src,
from: self.from + from,
to: self.to
}
}
pub fn to(&self, to: usize) -> Src<'c> {
Src {
src: self.src,
from: self.from,
to: self.from + to
}
}
pub fn from_to(&self, from: usize, to: usize) -> Src<'c> {
Src {
src: self.src,
from: self.from + from,
to: self.from + to
}
}
pub fn chunk_indices(&self) -> CodeChunkIter<'c> {
CodeChunkIter { src: *self, iter: self.src.idx.iter() }
}
}
pub struct CodeChunkIter<'c> {
src: Src<'c>,
iter: slice::Iter<'c, (usize, usize)>
}
impl<'c> Iterator for CodeChunkIter<'c> {
type Item = (usize, usize);
fn next(&mut self) -> Option<(usize, usize)> {
loop {
match self.iter.next() {
None => return None,
Some(&(start, end)) => {
if end < self.src.from {
continue;
}
if start > self.src.to {
return None;
} else {
return Some((
max(start, self.src.from) - self.src.from,
min(end, self.src.to) - self.src.from));
}
}
}
}
}
}
impl Deref for IndexedSource {
type Target = str;
fn deref(&self) -> &str {
&self.code
}
}
impl<'c> Deref for Src<'c> {
type Target = str;
fn deref(&self) -> &str {
&self.src.code[self.from..self.to]
}
}
pub fn new_source(src: String) -> IndexedSource {
IndexedSource::new(src)
}
pub struct FileCache<'c> {
arena: Arena<IndexedSource>,
raw_map: RefCell<HashMap<path::PathBuf, &'c IndexedSource>>,
masked_map: RefCell<HashMap<path::PathBuf, &'c IndexedSource>>,
allocations_available: RefCell<Vec<&'c mut IndexedSource>>,
allocations_freed: RefCell<Vec<&'c IndexedSource>>,
}
impl<'c> FileCache<'c> {
pub fn new<'a>() -> FileCache<'a> {
FileCache {
arena: Arena::new(),
raw_map: RefCell::new(HashMap::new()),
masked_map: RefCell::new(HashMap::new()),
allocations_available: RefCell::new(Vec::new()),
allocations_freed: RefCell::new(Vec::new()),
}
}
pub unsafe fn update_available_allocations(&self) {
let mut freed = self.allocations_freed.borrow_mut();
let mut available = self.allocations_available.borrow_mut();
while let Some(alloc) = freed.pop() {
let ptr = ::std::mem::transmute::<*const IndexedSource, *mut IndexedSource>(alloc);
available.push(&mut *ptr);
}
}
#[inline]
fn needs_alloc(&self) -> bool {
self.allocations_available.borrow().len() == 0
}
fn alloc(&self, value: IndexedSource) -> &mut IndexedSource {
if self.needs_alloc() {
self.arena.alloc(value)
} else {
unsafe {
let ptr: *mut IndexedSource = self.allocations_available.borrow_mut().pop().unwrap();
::std::mem::drop(::std::ptr::read(ptr));
::std::ptr::write(ptr, value);
&mut *ptr
}
}
}
pub fn cache_file_contents<T>(&'c self, filepath: &path::Path, buf: T)
where T: Into<String> {
{
let mut cache = self.raw_map.borrow_mut();
if let Some(prev) = cache.get(filepath) {
self.allocations_freed.borrow_mut().push(prev);
}
cache.insert(filepath.to_path_buf(), {
self.alloc(IndexedSource::new(buf.into()))
});
}
{
let mut cache = self.masked_map.borrow_mut();
if let Some(prev) = cache.get(filepath) {
self.allocations_freed.borrow_mut().push(prev);
}
cache.insert(filepath.to_path_buf(), {
let src = self.load_file(filepath);
self.alloc(src.src.with_src(scopes::mask_comments(src)))
});
}
}
pub fn open_file(&self, path: &path::Path) -> io::Result<File> {
File::open(path)
}
pub fn read_file(&self, path: &path::Path) -> Vec<u8> {
let mut rawbytes = Vec::new();
if let Ok(mut f) = self.open_file(path) {
f.read_to_end(&mut rawbytes).unwrap();
if rawbytes.len() > 2 && rawbytes[0..3] == [0xEF, 0xBB, 0xBF] {
let mut it = rawbytes.into_iter();
it.next(); it.next(); it.next();
it.collect()
} else {
rawbytes
}
} else {
error!("read_file couldn't open {:?}. Returning empty string", path);
Vec::new()
}
}
pub fn load_file(&'c self, filepath: &path::Path) -> Src<'c> {
let mut cache = self.raw_map.borrow_mut();
cache.entry(filepath.to_path_buf()).or_insert_with(|| {
let rawbytes = self.read_file(filepath);
let res = String::from_utf8(rawbytes).unwrap();
self.alloc(IndexedSource::new(res))
}).as_ref()
}
pub fn load_file_and_mask_comments(&'c self, filepath: &path::Path) -> Src<'c> {
let mut cache = self.masked_map.borrow_mut();
cache.entry(filepath.to_path_buf()).or_insert_with(|| {
let src = self.load_file(filepath);
self.alloc(src.src.with_src(scopes::mask_comments(src)))
}).as_ref()
}
}
pub struct Session<'c> {
query_path: path::PathBuf,
substitute_file: path::PathBuf,
cache: &'c FileCache<'c>
}
impl<'a> Drop for Session<'a> {
fn drop(&mut self) {
unsafe { self.cache.update_available_allocations(); }
}
}
impl<'c> fmt::Debug for Session<'c> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "Session({:?}, {:?})", self.query_path, self.substitute_file)
}
}
impl<'c> Session<'c> {
pub fn from_path(cache: &'c FileCache<'c>,
query_path: &path::Path,
substitute_file: &path::Path) -> Session<'c> {
Session {
query_path: query_path.to_path_buf(),
substitute_file: substitute_file.to_path_buf(),
cache: cache
}
}
pub fn cache_file_contents<T>(&self, filepath: &path::Path, buf: T)
where T: Into<String> {
self.cache.cache_file_contents(filepath, buf);
}
pub fn open_file(&self, path: &path::Path) -> io::Result<File> {
if path == self.query_path.as_path() {
self.cache.open_file(&self.substitute_file)
} else {
self.cache.open_file(path)
}
}
pub fn read_file(&self, path: &path::Path) -> Vec<u8> {
self.cache.read_file(path)
}
pub fn load_file(&self, filepath: &path::Path) -> Src<'c> {
self.cache.load_file(filepath)
}
pub fn load_file_and_mask_comments(&self, filepath: &path::Path) -> Src<'c> {
self.cache.load_file_and_mask_comments(filepath)
}
}
pub fn complete_from_file(src: &str, filepath: &path::Path, pos: usize, session: &Session) -> vec::IntoIter<Match> {
let start = scopes::get_start_of_search_expr(src, pos);
let expr = &src[start..pos];
let (contextstr, searchstr, completetype) = scopes::split_into_context_and_completion(expr);
debug!("{:?}: contextstr is |{}|, searchstr is |{}|", completetype, contextstr, searchstr);
let mut out = Vec::new();
match completetype {
CompletionType::CompletePath => {
let mut v = expr.split("::").collect::<Vec<_>>();
let mut global = false;
if v[0] == "" {
v.remove(0);
global = true;
}
let path = Path::from_vec(global, v);
for m in nameres::resolve_path(&path, filepath, pos,
SearchType::StartsWith, Namespace::BothNamespaces,
session) {
out.push(m);
}
},
CompletionType::CompleteField => {
let context = ast::get_type_of(contextstr.to_owned(), filepath, pos, session);
debug!("complete_from_file context is {:?}", context);
context.map(|ty| {
match ty {
Ty::TyMatch(m) => {
for m in nameres::search_for_field_or_method(m, searchstr, SearchType::StartsWith, session) {
out.push(m)
}
},
Ty::TyMatchVec(vm) => {
for m in vm{
for m in nameres::search_for_field_or_method(m, searchstr, SearchType::StartsWith, session) {
out.push(m)
}
}
},
_ => (),
}
});
}
}
out.into_iter()
}
pub fn find_definition(src: &str, filepath: &path::Path, pos: usize, session: &Session) -> Option<Match> {
find_definition_(src, filepath, pos, session)
}
pub fn find_definition_(src: &str, filepath: &path::Path, pos: usize, session: &Session) -> Option<Match> {
let (start, end) = scopes::expand_search_expr(src, pos);
let expr = &src[start..end];
let (contextstr, searchstr, completetype) = scopes::split_into_context_and_completion(expr);
debug!("find_definition_ for |{:?}| |{:?}| {:?}", contextstr, searchstr, completetype);
match completetype {
CompletionType::CompletePath => {
let mut v = expr.split("::").collect::<Vec<_>>();
let mut global = false;
if v[0] == "" {
v.remove(0);
global = true;
}
let segs = v
.into_iter()
.map(|x| PathSegment{ name: x.to_owned(), types: Vec::new() })
.collect::<Vec<_>>();
let path = Path{ global: global, segments: segs };
nameres::resolve_path(&path, filepath, pos,
SearchType::ExactMatch, Namespace::BothNamespaces,
session).nth(0)
},
CompletionType::CompleteField => {
let context = ast::get_type_of(contextstr.to_owned(), filepath, pos, session);
debug!("context is {:?}", context);
context.and_then(|ty| {
match ty {
Ty::TyMatch(m) => {
nameres::search_for_field_or_method(m, searchstr, SearchType::ExactMatch, session).nth(0)
}
_ => None
}
})
}
}
}