-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathparsed_document.rs
More file actions
380 lines (328 loc) · 10.7 KB
/
parsed_document.rs
File metadata and controls
380 lines (328 loc) · 10.7 KB
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
use std::sync::Arc;
use pgt_diagnostics::serde::Diagnostic as SDiagnostic;
use pgt_fs::PgTPath;
use pgt_query_ext::diagnostics::SyntaxDiagnostic;
use pgt_text_size::{TextRange, TextSize};
use crate::workspace::ChangeFileParams;
use super::{
annotation::AnnotationStore,
change::StatementChange,
document::{Document, StatementIterator},
pg_query::PgQueryStore,
sql_function::SQLFunctionBodyStore,
statement_identifier::StatementId,
tree_sitter::TreeSitterStore,
};
pub struct ParsedDocument {
#[allow(dead_code)]
path: PgTPath,
doc: Document,
ast_db: PgQueryStore,
cst_db: TreeSitterStore,
sql_fn_db: SQLFunctionBodyStore,
annotation_db: AnnotationStore,
}
impl ParsedDocument {
pub fn new(path: PgTPath, content: String, version: i32) -> ParsedDocument {
let doc = Document::new(content, version);
let cst_db = TreeSitterStore::new();
let ast_db = PgQueryStore::new();
let sql_fn_db = SQLFunctionBodyStore::new();
let annotation_db = AnnotationStore::new();
doc.iter().for_each(|(stmt, _, content)| {
cst_db.add_statement(&stmt, content);
});
ParsedDocument {
path,
doc,
ast_db,
cst_db,
sql_fn_db,
annotation_db,
}
}
/// Applies a change to the document and updates the CST and AST databases accordingly.
///
/// Note that only tree-sitter cares about statement modifications vs remove + add.
/// Hence, we just clear the AST for the old statements and lazily load them when requested.
///
/// * `params`: ChangeFileParams - The parameters for the change to be applied.
pub fn apply_change(&mut self, params: ChangeFileParams) {
for c in &self.doc.apply_file_change(¶ms) {
match c {
StatementChange::Added(added) => {
tracing::debug!(
"Adding statement: id:{:?}, text:{:?}",
added.stmt,
added.text
);
self.cst_db.add_statement(&added.stmt, &added.text);
}
StatementChange::Deleted(s) => {
tracing::debug!("Deleting statement: id {:?}", s,);
self.cst_db.remove_statement(s);
self.ast_db.clear_statement(s);
self.sql_fn_db.clear_statement(s);
self.annotation_db.clear_statement(s);
}
StatementChange::Modified(s) => {
tracing::debug!(
"Modifying statement with id {:?} (new id {:?}). Range {:?}, Changed from '{:?}' to '{:?}', changed text: {:?}",
s.old_stmt,
s.new_stmt,
s.change_range,
s.old_stmt_text,
s.new_stmt_text,
s.change_text
);
self.cst_db.modify_statement(s);
self.ast_db.clear_statement(&s.old_stmt);
self.sql_fn_db.clear_statement(&s.old_stmt);
self.annotation_db.clear_statement(&s.old_stmt);
}
}
}
}
pub fn get_document_content(&self) -> &str {
&self.doc.content
}
pub fn document_diagnostics(&self) -> &Vec<SDiagnostic> {
&self.doc.diagnostics
}
pub fn find<'a, M>(&'a self, id: StatementId, mapper: M) -> Option<M::Output>
where
M: StatementMapper<'a>,
{
self.iter_with_filter(mapper, IdFilter::new(id)).next()
}
pub fn iter<'a, M>(&'a self, mapper: M) -> ParseIterator<'a, M, NoFilter>
where
M: StatementMapper<'a>,
{
self.iter_with_filter(mapper, NoFilter)
}
pub fn iter_with_filter<'a, M, F>(&'a self, mapper: M, filter: F) -> ParseIterator<'a, M, F>
where
M: StatementMapper<'a>,
F: StatementFilter<'a>,
{
ParseIterator::new(self, mapper, filter)
}
#[allow(dead_code)]
pub fn count(&self) -> usize {
self.iter(DefaultMapper).count()
}
}
pub trait StatementMapper<'a> {
type Output;
fn map(
&self,
parser: &'a ParsedDocument,
id: StatementId,
range: TextRange,
content: &str,
) -> Self::Output;
}
pub trait StatementFilter<'a> {
fn predicate(&self, id: &StatementId, range: &TextRange) -> bool;
}
pub struct ParseIterator<'a, M, F> {
parser: &'a ParsedDocument,
statements: StatementIterator<'a>,
mapper: M,
filter: F,
pending_sub_statements: Vec<(StatementId, TextRange, String)>,
}
impl<'a, M, F> ParseIterator<'a, M, F> {
pub fn new(parser: &'a ParsedDocument, mapper: M, filter: F) -> Self {
Self {
parser,
statements: parser.doc.iter(),
mapper,
filter,
pending_sub_statements: Vec::new(),
}
}
}
impl<'a, M, F> Iterator for ParseIterator<'a, M, F>
where
M: StatementMapper<'a>,
F: StatementFilter<'a>,
{
type Item = M::Output;
fn next(&mut self) -> Option<Self::Item> {
// First check if we have any pending sub-statements to process
if let Some((id, range, content)) = self.pending_sub_statements.pop() {
if self.filter.predicate(&id, &range) {
return Some(self.mapper.map(self.parser, id, range, &content));
}
// If the sub-statement doesn't pass the filter, continue to the next item
return self.next();
}
// Process the next top-level statement
let next_statement = self.statements.next();
if let Some((root_id, range, content)) = next_statement {
// If we should include sub-statements and this statement has an AST
let content_owned = content.to_string();
if let Ok(ast) = self
.parser
.ast_db
.get_or_cache_ast(&root_id, &content_owned)
.as_ref()
{
// Check if this is a SQL function definition with a body
if let Some(sub_statement) =
self.parser
.sql_fn_db
.get_function_body(&root_id, ast, &content_owned)
{
// Add sub-statements to our pending queue
self.pending_sub_statements.push((
root_id.create_child(),
// adjust range to document
sub_statement.range + range.start(),
sub_statement.body.clone(),
));
}
}
// Return the current statement if it passes the filter
if self.filter.predicate(&root_id, &range) {
return Some(self.mapper.map(self.parser, root_id, range, content));
}
// If the current statement doesn't pass the filter, try the next one
return self.next();
}
None
}
}
pub struct DefaultMapper;
impl<'a> StatementMapper<'a> for DefaultMapper {
type Output = (StatementId, TextRange, String);
fn map(
&self,
_parser: &'a ParsedDocument,
id: StatementId,
range: TextRange,
content: &str,
) -> Self::Output {
(id, range, content.to_string())
}
}
pub struct ExecuteStatementMapper;
impl<'a> StatementMapper<'a> for ExecuteStatementMapper {
type Output = (
StatementId,
TextRange,
String,
Option<pgt_query_ext::NodeEnum>,
);
fn map(
&self,
parser: &'a ParsedDocument,
id: StatementId,
range: TextRange,
content: &str,
) -> Self::Output {
let ast_result = parser.ast_db.get_or_cache_ast(&id, content);
let ast_option = match &*ast_result {
Ok(node) => Some(node.clone()),
Err(_) => None,
};
(id, range, content.to_string(), ast_option)
}
}
pub struct AsyncDiagnosticsMapper;
impl<'a> StatementMapper<'a> for AsyncDiagnosticsMapper {
type Output = (
StatementId,
TextRange,
String,
Option<pgt_query_ext::NodeEnum>,
Arc<tree_sitter::Tree>,
);
fn map(
&self,
parser: &'a ParsedDocument,
id: StatementId,
range: TextRange,
content: &str,
) -> Self::Output {
let content_owned = content.to_string();
let ast_result = parser.ast_db.get_or_cache_ast(&id, &content_owned);
let ast_option = match &*ast_result {
Ok(node) => Some(node.clone()),
Err(_) => None,
};
let cst_result = parser.cst_db.get_or_cache_tree(&id, &content_owned);
(id, range, content_owned, ast_option, cst_result)
}
}
pub struct SyncDiagnosticsMapper;
impl<'a> StatementMapper<'a> for SyncDiagnosticsMapper {
type Output = (
StatementId,
TextRange,
Option<pgt_query_ext::NodeEnum>,
Option<SyntaxDiagnostic>,
);
fn map(
&self,
parser: &'a ParsedDocument,
id: StatementId,
range: TextRange,
content: &str,
) -> Self::Output {
let ast_result = parser.ast_db.get_or_cache_ast(&id, content);
let (ast_option, diagnostics) = match &*ast_result {
Ok(node) => (Some(node.clone()), None),
Err(diag) => (None, Some(diag.clone())),
};
(id, range, ast_option, diagnostics)
}
}
pub struct GetCompletionsMapper;
impl<'a> StatementMapper<'a> for GetCompletionsMapper {
type Output = (StatementId, TextRange, String, Arc<tree_sitter::Tree>);
fn map(
&self,
parser: &'a ParsedDocument,
id: StatementId,
range: TextRange,
content: &str,
) -> Self::Output {
let cst_result = parser.cst_db.get_or_cache_tree(&id, content);
(id, range, content.to_string(), cst_result)
}
}
pub struct NoFilter;
impl<'a> StatementFilter<'a> for NoFilter {
fn predicate(&self, _id: &StatementId, _range: &TextRange) -> bool {
true
}
}
pub struct CursorPositionFilter {
pos: TextSize,
}
impl CursorPositionFilter {
pub fn new(pos: TextSize) -> Self {
Self { pos }
}
}
impl<'a> StatementFilter<'a> for CursorPositionFilter {
fn predicate(&self, _id: &StatementId, range: &TextRange) -> bool {
range.contains(self.pos)
}
}
pub struct IdFilter {
id: StatementId,
}
impl IdFilter {
pub fn new(id: StatementId) -> Self {
Self { id }
}
}
impl<'a> StatementFilter<'a> for IdFilter {
fn predicate(&self, id: &StatementId, _range: &TextRange) -> bool {
*id == self.id
}
}