-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsource_query.rs
More file actions
183 lines (174 loc) · 7.71 KB
/
Copy pathsource_query.rs
File metadata and controls
183 lines (174 loc) · 7.71 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
use std::ops::Range;
use tree_sitter::{
Language, Node, Parser, Point, Query, QueryCursor, Range as TSRange, StreamingIterator, Tree,
};
use crate::source_ref::FormatArgument;
use crate::CodeSource;
pub struct SourceQuery<'a> {
pub source: &'a str,
tree: Tree,
language: Language,
}
pub(crate) struct QueryResult {
pub kind: String,
pub range: TSRange,
pub name_range: Range<usize>,
pub pattern: Option<String>,
pub args: Vec<FormatArgument>,
pub raw: bool,
}
impl<'a> SourceQuery<'a> {
pub fn new(code: &'a CodeSource) -> SourceQuery<'a> {
// println!("{}", code.filename);
let mut parser = Parser::new();
let language = code.info.language.into();
parser
.set_language(&language)
.unwrap_or_else(|_| panic!("Error loading {:?} grammar", language));
let source = code.buffer.as_str();
let tree = parser.parse(source, None).expect("source is parsable");
SourceQuery {
source,
tree,
language,
}
}
pub(crate) fn query(&self, query: &str, node_kind: Option<&str>) -> Vec<QueryResult> {
let query = Query::new(&self.language, query).unwrap();
let filter_idx = node_kind.and_then(|kind| query.capture_index_for_name(kind));
let mut cursor = QueryCursor::new();
let mut results = Vec::new();
let matches = cursor.matches(&query, self.tree.root_node(), self.source.as_bytes());
matches.for_each(|m| {
let mut got_string_literal = false;
for capture in m.captures {
let mut child = capture.node;
match child.kind() {
"string_literal" | "string" => {
// only return results after the format string literal, other captures
// are not relevant.
got_string_literal = true;
}
_ => {
if !got_string_literal {
continue;
}
}
}
let mut arg_start: Option<(usize, Point)> = None;
if filter_idx.is_none() || filter_idx.is_some_and(|f| f == capture.index) {
let qr_index = results.len();
results.push(QueryResult {
kind: capture.node.kind().to_string(),
range: capture.node.range(),
name_range: Self::find_fn_range(child),
pattern: None,
args: vec![],
raw: false,
});
let mut pattern = String::new();
if child.kind() == "string" {
// The Python tree-sitter outputs string nodes that contain details about
// the string, like interpolation expressions.
let mut child_cursor = child.walk();
for string_child in child.children(&mut child_cursor) {
let range = string_child.start_byte()..string_child.end_byte();
match string_child.kind() {
"string_start" => {
// Check for a python raw string literal.
if self.source[range].contains("r") {
results[qr_index].raw = true;
}
}
"string_content" => pattern.push_str(self.source[range].as_ref()),
"interpolation" => {
// Swap in a Python placeholder for the interpolation
// expression.
pattern.push_str("%s");
let expr =
string_child.child_by_field_name("expression").unwrap();
results[qr_index].args.push(FormatArgument::Named(
self.source[expr.start_byte()..expr.end_byte()].to_string(),
))
}
_ => {}
}
}
results[qr_index].pattern = Some(pattern);
}
while let Some(next_child) = child.next_sibling() {
if matches!(next_child.kind(), "," | ")") {
if let Some(start) = arg_start {
if start.0 < next_child.start_byte() {
results.push(QueryResult {
kind: "args".to_string(),
range: TSRange {
start_byte: start.0,
start_point: start.1,
end_byte: next_child.start_byte(),
end_point: next_child.start_position(),
},
name_range: Self::find_fn_range(child),
pattern: None,
args: vec![],
raw: false,
});
}
}
arg_start = Some((next_child.end_byte(), next_child.end_position()));
}
child = next_child;
}
}
}
});
results
}
fn find_fn_range(node: Node) -> Range<usize> {
// println!("node.kind()={:?}", node.kind());
match node.kind() {
"function_item" => {
let range = node.child_by_field_name("name").unwrap().range();
range.start_byte..range.end_byte
}
"function_definition" => {
let range = if let Some(decl) = node.child_by_field_name("declarator") {
decl.range()
} else if let Some(name) = node.child_by_field_name("name") {
name.range()
} else {
unreachable!();
};
range.start_byte..range.end_byte
}
"method_declaration" => {
let range = node.child_by_field_name("name").unwrap().range();
range.start_byte..range.end_byte
}
"constructor_declaration" => {
let range = node.child_by_field_name("name").unwrap().range();
range.start_byte..range.end_byte
}
"class_declaration" => {
let range = node.child_by_field_name("name").unwrap().range();
range.start_byte..range.end_byte
}
"declaration_list" | "static_item" | "attribute_item" => {
let range = node.range();
range.start_byte..range.end_byte
}
_ => {
if let Some(parent) = node.parent() {
if parent.kind() == "translation_unit" {
let range = parent.range();
return range.start_byte..range.end_byte;
}
Self::find_fn_range(parent)
} else {
let range = node.range();
range.start_byte..range.end_byte
}
}
}
}
}