This repository has been archived by the owner on Oct 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueries.rs
651 lines (596 loc) · 24.9 KB
/
queries.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
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 crate::{AmlError, FunctionInfo, Location, Result, FUNC_NAME_CAPTURE};
use log::{trace, warn};
use tree_sitter::{Node, Parser, Query};
use tree_sitter_rust::language;
const ANNOTATED_IMPL_NAME_CAPTURE: &str = "type.impl";
const ANNOTATED_IMPL_METHOD_NAME_CAPTURE: &str = "inner.func.name";
const MOD_NAME_CAPTURE: &str = "mod.name";
const MOD_CONTENTS_CAPTURE: &str = "mod.contents";
const IMPL_NAME_CAPTURE: &str = "impl.type";
const IMPL_CONTENTS_CAPTURE: &str = "impl.contents";
const GRAMMAR_IMPL_ITEM_NODE_KIND: &str = "impl_item";
const GRAMMAR_MOD_ITEM_NODE_KIND: &str = "mod_item";
fn new_parser() -> Result<Parser> {
let mut parser = Parser::new();
parser.set_language(language())?;
Ok(parser)
}
fn is_within_mod_item(node: Node, max_parent: Option<Node>, source: &str) -> bool {
let mut walk = node;
loop {
if walk.kind() == GRAMMAR_MOD_ITEM_NODE_KIND {
trace!(
"Node was inside a mod.\nNode:{}\nMax Parent:{}\n",
node.utf8_text(source.as_bytes())
.map(ToString::to_string)
.unwrap(),
if let Some(node) = max_parent {
node.utf8_text(source.as_bytes())
.map(ToString::to_string)
.unwrap()
} else {
source.to_string()
}
);
break true;
}
if let Some(parent) = walk.parent() {
if max_parent.map_or(false, |max_parent| parent.id() == max_parent.id()) {
break false;
}
walk = parent;
continue;
}
break false;
}
}
fn is_within_impl_item(node: Node, max_parent: Option<Node>, source: &str) -> bool {
let mut walk = node;
loop {
if walk.kind() == GRAMMAR_IMPL_ITEM_NODE_KIND {
trace!(
"Node was inside a impl block.\nNode:{}\nMax Parent:{}\n",
node.utf8_text(source.as_bytes())
.map(ToString::to_string)
.unwrap(),
if let Some(node) = max_parent {
node.utf8_text(source.as_bytes())
.map(ToString::to_string)
.unwrap()
} else {
source.to_string()
}
);
break true;
}
if let Some(parent) = walk.parent() {
if max_parent.map_or(false, |max_parent| parent.id() == max_parent.id()) {
break false;
}
walk = parent;
continue;
}
break false;
}
}
/// Query wrapper for "all autometrics functions in source"
#[derive(Debug)]
pub(super) struct AmQuery {
query: Query,
/// Index of the capture for a function name.
func_name_idx: u32,
/// Index of the capture for the type name of an `#[autometrics]`-annotated impl block
///
/// This is an option, because when we want to list all functions, we do not want to use
/// this capture ever (we will instead recurse into every impl block.)
annotated_impl_type_name_idx: u32,
/// Index of the capture for a method name within an `#[autometrics]`-annotated impl block
///
/// This is an option, because when we want to list all functions, we do not want to use
/// this capture ever (we will instead recurse into every impl block.)
annotated_impl_method_name_idx: u32,
/// Index of the capture for the name of a module that is defined in file.
mod_name_idx: u32,
/// Index of the capture for the contents of a module that is defined in file.
mod_contents_idx: u32,
/// Index of a capture for the type name associated to any impl block in the file.
impl_type_idx: u32,
/// Index of a capture for the contents (the declarations) associated to any impl block in the file.
impl_contents_idx: u32,
}
impl AmQuery {
/// Failible constructor.
///
/// The constructor only fails if the given tree-sitter query does not have the
/// necessary named captures.
pub fn try_new() -> Result<Self> {
let query = Query::new(
language(),
include_str!("../../runtime/queries/rust/autometrics.scm"),
)?;
let func_name_idx = query
.capture_index_for_name(FUNC_NAME_CAPTURE)
.ok_or_else(|| AmlError::MissingNamedCapture(FUNC_NAME_CAPTURE.into()))?;
let annotated_impl_type_name_idx = query
.capture_index_for_name(ANNOTATED_IMPL_NAME_CAPTURE)
.ok_or_else(|| AmlError::MissingNamedCapture(ANNOTATED_IMPL_NAME_CAPTURE.into()))?;
let annotated_impl_method_name_idx = query
.capture_index_for_name(ANNOTATED_IMPL_METHOD_NAME_CAPTURE)
.ok_or_else(|| {
AmlError::MissingNamedCapture(ANNOTATED_IMPL_METHOD_NAME_CAPTURE.into())
})?;
let mod_name_idx = query
.capture_index_for_name(MOD_NAME_CAPTURE)
.ok_or_else(|| AmlError::MissingNamedCapture(MOD_NAME_CAPTURE.into()))?;
let mod_contents_idx = query
.capture_index_for_name(MOD_CONTENTS_CAPTURE)
.ok_or_else(|| AmlError::MissingNamedCapture(MOD_NAME_CAPTURE.into()))?;
let impl_type_idx = query
.capture_index_for_name(IMPL_NAME_CAPTURE)
.ok_or_else(|| AmlError::MissingNamedCapture(IMPL_NAME_CAPTURE.into()))?;
let impl_contents_idx = query
.capture_index_for_name(IMPL_CONTENTS_CAPTURE)
.ok_or_else(|| AmlError::MissingNamedCapture(IMPL_CONTENTS_CAPTURE.into()))?;
Ok(Self {
query,
func_name_idx,
annotated_impl_type_name_idx,
annotated_impl_method_name_idx,
mod_name_idx,
mod_contents_idx,
impl_type_idx,
impl_contents_idx,
})
}
pub fn list_function_names(
&self,
file_name: &str,
module: String,
source: &str,
) -> Result<Vec<FunctionInfo>> {
let mut parser = new_parser()?;
let parsed_source = parser.parse(source, None).ok_or(AmlError::Parsing)?;
self.list_function_rec(file_name, module, None, parsed_source.root_node(), source)
}
fn list_function_rec(
&self,
file_name: &str,
current_module: String,
current_type: Option<String>,
node: Node,
source: &str,
) -> Result<Vec<FunctionInfo>> {
let mut res = Vec::new();
let mut cursor = tree_sitter::QueryCursor::new();
// Detect all functions directly in module scope
let direct_names = self.list_direct_function_names(
&mut cursor,
node,
file_name,
source,
¤t_type,
¤t_module,
);
res.extend(direct_names);
// Detect all methods from annotated impl blocks directly in module scope
let impl_block_methods = self.list_annotated_impl_block_methods(
&mut cursor,
node,
file_name,
source,
¤t_module,
);
res.extend(impl_block_methods);
// Detect all functions in submodule scope
for capture in cursor.matches(&self.query, node, source.as_bytes()) {
if let Some(mod_name_node) = capture.nodes_for_capture_index(self.mod_name_idx).next() {
// We only want to consider module nodes that are direct children of the currently iterating node,
// because the recursion will cleanly look for deeply nested module declarations.
if mod_name_node
.parent()
.unwrap_or_else(|| panic!("The rust tree-sitter grammar guarantees that a mod_item:name has a mod_item as parent. {} capture is supposed to capture a mod_item:name", MOD_NAME_CAPTURE))
.parent() != Some(node) {
continue;
}
let mod_name = {
match mod_name_node
.utf8_text(source.as_bytes())
.map(ToString::to_string)
{
Ok(val) => val,
Err(e) => {
warn!("Error while extracting the module name: {e}");
continue;
}
}
};
if let Some(contents_node) = capture
.nodes_for_capture_index(self.mod_contents_idx)
.next()
{
let new_module = if current_module.is_empty() {
mod_name
} else {
format!("{current_module}::{mod_name}")
};
trace!(
"Recursing into mod {}\n{}\n\n\n",
new_module,
contents_node
.utf8_text(source.as_bytes())
.map(ToString::to_string)
.unwrap()
);
let inner = self.list_function_rec(
file_name,
new_module,
current_type.clone(),
contents_node,
source,
)?;
res.extend(inner)
}
}
if let Some(impl_type_node) = capture.nodes_for_capture_index(self.impl_type_idx).next()
{
// We only want to consider impl blocks that are direct children of the currently iterating node,
// because the recursion will cleanly look for deeply nested module declarations.
if impl_type_node
.parent()
.unwrap_or_else(|| panic!("The rust tree-sitter grammar guarantees that a impl_item:type_identifier has a impl_item as parent. {} capture is supposed to capture a mod_item:name", MOD_NAME_CAPTURE))
.parent() != Some(node) {
continue;
}
let type_name = {
match impl_type_node
.utf8_text(source.as_bytes())
.map(ToString::to_string)
{
Ok(val) => val,
Err(e) => {
warn!("Error extracting the struct name: {e}");
continue;
}
}
};
if let Some(contents_node) = capture
.nodes_for_capture_index(self.impl_contents_idx)
.next()
{
trace!(
"Recursing into impl block {}::{}\n{}\n\n\n",
current_module,
type_name,
contents_node
.utf8_text(source.as_bytes())
.map(ToString::to_string)
.unwrap()
);
let inner = self.list_function_rec(
file_name,
current_module.clone(),
Some(type_name),
contents_node,
source,
)?;
res.extend(inner)
}
}
}
Ok(res)
}
fn list_direct_function_names(
&self,
cursor: &mut tree_sitter::QueryCursor,
node: Node,
file_name: &str,
source: &str,
current_type: &Option<String>,
current_module: &str,
) -> Vec<FunctionInfo> {
cursor
.matches(&self.query, node, source.as_bytes())
.filter_map(|capture| -> Option<FunctionInfo> {
let fn_node: Node = capture.nodes_for_capture_index(self.func_name_idx).next()?;
// Ignore the matches that are within a mod_item, as the recursion will catch it later with the fully qualified module name.
if is_within_mod_item(fn_node, Some(node), source) {
return None;
}
// Ignore the matches that are within a impl_item, as the impl_block_names variable below catches those, applying the
// fully qualified module name.
if is_within_impl_item(fn_node, Some(node), source) {
return None;
}
let start = fn_node.start_position();
let end = fn_node.end_position();
let instrumentation = Some(Location::from((file_name, start, end)));
let definition = Some(Location::from((file_name, start, end)));
let fn_name: std::result::Result<String, std::str::Utf8Error> = fn_node
.utf8_text(source.as_bytes())
.map(ToString::to_string);
let type_prefix: String = current_type
.as_ref()
.map(|t| format!("{t}::"))
.unwrap_or_default();
match fn_name {
Ok(f) => Some(FunctionInfo {
id: (current_module, format!("{type_prefix}{f}")).into(),
instrumentation,
definition,
}),
Err(e) => {
warn!("Could not get the method name: {e}");
None
}
}
})
.collect()
}
fn list_annotated_impl_block_methods(
&self,
cursor: &mut tree_sitter::QueryCursor,
node: Node,
file_name: &str,
source: &str,
current_module: &str,
) -> Vec<FunctionInfo> {
cursor
.matches(&self.query, node, source.as_bytes())
.filter_map(|capture| -> Option<FunctionInfo> {
let fn_node: Node = capture
.nodes_for_capture_index(self.annotated_impl_method_name_idx)
.next()?;
// Ignore the matches that are within a mod_item, as the recursion will catch it later with the fully qualified module name.
if is_within_mod_item(fn_node, Some(node), source) {
return None;
}
let fn_name = fn_node
.utf8_text(source.as_bytes())
.map(ToString::to_string);
let struct_name = capture
.nodes_for_capture_index(self.annotated_impl_type_name_idx)
.next()
.map(|node| node.utf8_text(source.as_bytes()).map(ToString::to_string))?;
let start = fn_node.start_position();
let end = fn_node.end_position();
let instrumentation = Some(Location::from((file_name, start, end)));
let definition = Some(Location::from((file_name, start, end)));
match (struct_name, fn_name) {
(Ok(s), Ok(f)) => Some(FunctionInfo {
id: (current_module, format!("{s}::{f}")).into(),
instrumentation,
definition,
}),
(Err(e), _) => {
warn!("Could not extract the name of the struct: {e}");
None
}
(_, Err(e)) => {
warn!("Could not extract the name of the method: {e}");
None
}
}
})
.collect()
}
}
/// Query wrapper for "all functions in source"
#[derive(Debug)]
pub(super) struct AllFunctionsQuery {
query: Query,
/// Index of the capture for a function name.
func_name_idx: u32,
/// Index of the capture for the name of a module that is defined in file.
mod_name_idx: u32,
/// Index of the capture for the contents of a module that is defined in file.
mod_contents_idx: u32,
/// Index of a capture for the type name associated to any impl block in the file.
impl_type_idx: u32,
/// Index of a capture for the contents (the declarations) associated to any impl block in the file.
impl_contents_idx: u32,
}
impl AllFunctionsQuery {
/// Failible constructor.
///
/// The constructor only fails if the given tree-sitter query does not have the
/// necessary named captures.
pub fn try_new() -> Result<Self> {
let query = Query::new(
language(),
include_str!("../../runtime/queries/rust/all_functions.scm"),
)?;
let func_name_idx = query
.capture_index_for_name(FUNC_NAME_CAPTURE)
.ok_or_else(|| AmlError::MissingNamedCapture(FUNC_NAME_CAPTURE.into()))?;
let mod_name_idx = query
.capture_index_for_name(MOD_NAME_CAPTURE)
.ok_or_else(|| AmlError::MissingNamedCapture(MOD_NAME_CAPTURE.into()))?;
let mod_contents_idx = query
.capture_index_for_name(MOD_CONTENTS_CAPTURE)
.ok_or_else(|| AmlError::MissingNamedCapture(MOD_NAME_CAPTURE.into()))?;
let impl_type_idx = query
.capture_index_for_name(IMPL_NAME_CAPTURE)
.ok_or_else(|| AmlError::MissingNamedCapture(IMPL_NAME_CAPTURE.into()))?;
let impl_contents_idx = query
.capture_index_for_name(IMPL_CONTENTS_CAPTURE)
.ok_or_else(|| AmlError::MissingNamedCapture(IMPL_CONTENTS_CAPTURE.into()))?;
Ok(Self {
query,
func_name_idx,
mod_name_idx,
mod_contents_idx,
impl_type_idx,
impl_contents_idx,
})
}
pub fn list_function_names(
&self,
file_name: &str,
module: String,
source: &str,
) -> Result<Vec<FunctionInfo>> {
let mut parser = new_parser()?;
let parsed_source = parser.parse(source, None).ok_or(AmlError::Parsing)?;
self.list_function_rec(file_name, module, None, parsed_source.root_node(), source)
}
fn list_function_rec(
&self,
file_name: &str,
current_module: String,
current_type: Option<String>,
node: Node,
source: &str,
) -> Result<Vec<FunctionInfo>> {
let mut res = Vec::new();
let mut cursor = tree_sitter::QueryCursor::new();
// Detect all functions directly in module scope
let direct_names = self.list_direct_function_names(
&mut cursor,
node,
file_name,
source,
current_type,
¤t_module,
);
res.extend(direct_names);
// Detect all functions in submodule scope
for capture in cursor.matches(&self.query, node, source.as_bytes()) {
if let Some(mod_name_node) = capture.nodes_for_capture_index(self.mod_name_idx).next() {
// We only want to consider module nodes that are direct children of the currently iterating node,
// because the recursion will cleanly look for deeply nested module declarations.
if mod_name_node
.parent()
.unwrap_or_else(|| panic!("The rust tree-sitter grammar guarantees that a mod_item:name has a mod_item as parent. {} capture is supposed to capture a mod_item:name", MOD_NAME_CAPTURE))
.parent() != Some(node) {
continue;
}
let mod_name = {
match mod_name_node
.utf8_text(source.as_bytes())
.map(ToString::to_string)
{
Ok(val) => val,
Err(e) => {
warn!("Could not extract module name from a capture: {e}");
continue;
}
}
};
if let Some(contents_node) = capture
.nodes_for_capture_index(self.mod_contents_idx)
.next()
{
let new_module = if current_module.is_empty() {
mod_name
} else {
format!("{current_module}::{mod_name}")
};
trace!(
"Recursing into mod {}\n{}\n\n\n",
new_module,
contents_node
.utf8_text(source.as_bytes())
.map(ToString::to_string)
.unwrap()
);
let inner =
self.list_function_rec(file_name, new_module, None, contents_node, source)?;
res.extend(inner.into_iter())
}
}
if let Some(impl_type_node) = capture.nodes_for_capture_index(self.impl_type_idx).next()
{
// We only want to consider impl blocks that are direct children of the currently iterating node,
// because the recursion will cleanly look for deeply nested module declarations.
if impl_type_node
.parent()
.unwrap_or_else(|| panic!("The rust tree-sitter grammar guarantees that a impl_item:type_identifier has a impl_item as parent. {} capture is supposed to capture a mod_item:name", MOD_NAME_CAPTURE))
.parent() != Some(node) {
continue;
}
let type_name = {
match impl_type_node
.utf8_text(source.as_bytes())
.map(ToString::to_string)
{
Ok(val) => val,
Err(e) => {
warn!("Could not extract the type name of the impl block: {e}");
continue;
}
}
};
if let Some(contents_node) = capture
.nodes_for_capture_index(self.impl_contents_idx)
.next()
{
trace!(
"Recursing into impl block {}::{}\n{}\n\n\n",
current_module,
type_name,
contents_node
.utf8_text(source.as_bytes())
.map(ToString::to_string)
.unwrap()
);
let inner = self.list_function_rec(
file_name,
current_module.clone(),
Some(type_name),
contents_node,
source,
)?;
res.extend(inner.into_iter())
}
}
}
Ok(res)
}
fn list_direct_function_names(
&self,
cursor: &mut tree_sitter::QueryCursor,
node: Node,
file_name: &str,
source: &str,
current_type: Option<String>,
current_module: &str,
) -> Vec<FunctionInfo> {
cursor
.matches(&self.query, node, source.as_bytes())
.filter_map(|capture| -> Option<FunctionInfo> {
let fn_node: Node = capture.nodes_for_capture_index(self.func_name_idx).next()?;
// Ignore the matches that are within a mod_item, as the recursion will catch it later with the fully qualified module name.
if is_within_mod_item(fn_node, Some(node), source) {
return None;
}
// Ignore the matches that are within a impl_item, as the impl_block_names variable below catches those, applying the
// fully qualified module name.
if is_within_impl_item(fn_node, Some(node), source) {
return None;
}
let fn_name: std::result::Result<String, std::str::Utf8Error> = fn_node
.utf8_text(source.as_bytes())
.map(ToString::to_string);
let type_prefix: String = current_type
.as_ref()
.map(|t| format!("{t}::"))
.unwrap_or_default();
let start = fn_node.start_position();
let end = fn_node.end_position();
let instrumentation = None;
let definition = Some(Location::from((file_name, start, end)));
match fn_name {
Ok(f) => Some(FunctionInfo {
id: (current_module, format!("{type_prefix}{f}")).into(),
instrumentation,
definition,
}),
Err(e) => {
warn!("Could not get the method name: {e}");
None
}
}
})
.collect()
}
}