aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_analysis/src/roots.rs
blob: 208acc4c22f4d06bc23c633ecc9574d4fd6dc019 (plain)
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
use std::{
    sync::Arc,
    panic,
};

use once_cell::sync::OnceCell;
use rayon::prelude::*;
use rustc_hash::FxHashMap;
use ra_editor::LineIndex;
use ra_syntax::File;

use crate::{
    FileId,
    imp::FileResolverImp,
    symbol_index::SymbolIndex,
    descriptors::{ModuleDescriptor, ModuleTreeDescriptor},
    db::Db,
};

pub(crate) trait SourceRoot {
    fn contains(&self, file_id: FileId) -> bool;
    fn module_tree(&self) -> Arc<ModuleTreeDescriptor>;
    fn lines(&self, file_id: FileId) -> Arc<LineIndex>;
    fn syntax(&self, file_id: FileId) -> File;
    fn symbols(&self, acc: &mut Vec<Arc<SymbolIndex>>);
}

#[derive(Default, Debug)]
pub(crate) struct WritableSourceRoot {
    db: Db,
}

impl WritableSourceRoot {
    pub fn apply_changes(
        &self,
        changes: &mut dyn Iterator<Item=(FileId, Option<String>)>,
        file_resolver: Option<FileResolverImp>,
    ) -> WritableSourceRoot {
        let resolver_changed = file_resolver.is_some();
        let mut changed_files = Vec::new();
        let mut new_state = self.db.state().clone();

        for (file_id, text) in changes {
            changed_files.push(file_id);
            match text {
                Some(text) => {
                    new_state.file_map.insert(file_id, Arc::new(text));
                },
                None => {
                    new_state.file_map.remove(&file_id);
                }
            }
        }
        if let Some(file_resolver) = file_resolver {
            new_state.file_resolver = file_resolver
        }
        WritableSourceRoot {
            db: self.db.with_changes(new_state, &changed_files, resolver_changed)
        }
    }
}

impl SourceRoot for WritableSourceRoot {
    fn module_tree(&self) -> Arc<ModuleTreeDescriptor> {
        self.db.make_query(crate::module_map::module_tree)
    }

    fn contains(&self, file_id: FileId) -> bool {
        self.db.state().file_map.contains_key(&file_id)
    }
    fn lines(&self, file_id: FileId) -> Arc<LineIndex> {
        self.db.make_query(|ctx| crate::queries::file_lines(ctx, file_id))
    }
    fn syntax(&self, file_id: FileId) -> File {
        self.db.make_query(|ctx| crate::queries::file_syntax(ctx, file_id))
    }
    fn symbols<'a>(&'a self, acc: &mut Vec<Arc<SymbolIndex>>) {
        self.db.make_query(|ctx| {
            let file_set = crate::queries::file_set(ctx);
            let syms = file_set.0.iter()
                .map(|file_id| crate::queries::file_symbols(ctx, *file_id));
            acc.extend(syms);
        });
    }
}

#[derive(Debug)]
struct FileData {
    text: String,
    lines: OnceCell<Arc<LineIndex>>,
    syntax: OnceCell<File>,
}

impl FileData {
    fn new(text: String) -> FileData {
        FileData {
            text,
            syntax: OnceCell::new(),
            lines: OnceCell::new(),
        }
    }
    fn lines(&self) -> &Arc<LineIndex> {
        self.lines.get_or_init(|| Arc::new(LineIndex::new(&self.text)))
    }
    fn syntax(&self) -> &File {
        let text = &self.text;
        let syntax = &self.syntax;
        match panic::catch_unwind(panic::AssertUnwindSafe(|| syntax.get_or_init(|| File::parse(text)))) {
            Ok(file) => file,
            Err(err) => {
                error!("Parser paniced on:\n------\n{}\n------\n", text);
                panic::resume_unwind(err)
            }
        }
    }
}

#[derive(Debug)]
pub(crate) struct ReadonlySourceRoot {
    symbol_index: Arc<SymbolIndex>,
    file_map: FxHashMap<FileId, FileData>,
    module_tree: Arc<ModuleTreeDescriptor>,
}

impl ReadonlySourceRoot {
    pub(crate) fn new(files: Vec<(FileId, String)>, file_resolver: FileResolverImp) -> ReadonlySourceRoot {
        let modules = files.par_iter()
            .map(|(file_id, text)| {
                let syntax = File::parse(text);
                let mod_descr = ModuleDescriptor::new(syntax.ast());
                (*file_id, syntax, mod_descr)
            })
            .collect::<Vec<_>>();
        let module_tree = ModuleTreeDescriptor::new(
            modules.iter().map(|it| (it.0, &it.2)),
            &file_resolver,
        );

        let symbol_index = SymbolIndex::for_files(
            modules.par_iter().map(|it| (it.0, it.1.clone()))
        );
        let file_map: FxHashMap<FileId, FileData> = files
            .into_iter()
            .map(|(id, text)| (id, FileData::new(text)))
            .collect();

        ReadonlySourceRoot {
            symbol_index: Arc::new(symbol_index),
            file_map,
            module_tree: Arc::new(module_tree),
        }
    }

    fn data(&self, file_id: FileId) -> &FileData {
        match self.file_map.get(&file_id) {
            Some(data) => data,
            None => panic!("unknown file: {:?}", file_id),
        }
    }
}

impl SourceRoot for ReadonlySourceRoot {
    fn module_tree(&self) -> Arc<ModuleTreeDescriptor> {
        Arc::clone(&self.module_tree)
    }
    fn contains(&self, file_id: FileId) -> bool {
        self.file_map.contains_key(&file_id)
    }
    fn lines(&self, file_id: FileId) -> Arc<LineIndex> {
        Arc::clone(self.data(file_id).lines())
    }
    fn syntax(&self, file_id: FileId) -> File {
        self.data(file_id).syntax().clone()
    }
    fn symbols(&self, acc: &mut Vec<Arc<SymbolIndex>>) {
        acc.push(Arc::clone(&self.symbol_index))
    }
}