-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathphp.rs
More file actions
423 lines (379 loc) · 16.1 KB
/
php.rs
File metadata and controls
423 lines (379 loc) · 16.1 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
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
use lsp_types::Position;
use regex::Regex;
use std::collections::HashMap;
use tree_sitter::{Node, Point};
use super::tokens::{
ClassAttribute, DrupalHook, DrupalPlugin, DrupalPluginReference, DrupalPluginType, DrupalTranslationString, PhpClass, PhpClassName, PhpMethod, Token, TokenData
};
use super::{get_closest_parent_by_kind, get_node_at_position, get_tree, position_to_point};
pub struct PhpParser {
source: String,
}
impl PhpParser {
pub fn new(source: &str) -> Self {
Self {
source: source.to_string(),
}
}
pub fn get_tokens(&self) -> Vec<Token> {
let tree = get_tree(&self.source, &tree_sitter_php::LANGUAGE_PHP.into());
self.parse_nodes(vec![tree.unwrap().root_node()])
}
pub fn get_token_at_position(&self, position: Position) -> Option<Token> {
let tree = get_tree(&self.source, &tree_sitter_php::LANGUAGE_PHP.into())?;
let mut node = get_node_at_position(&tree, position)?;
let point = position_to_point(position);
// Return the first "parseable" token in the parent chain.
let mut parsed_node: Option<Token>;
loop {
parsed_node = self.parse_node(node, Some(point));
if parsed_node.is_some() {
break;
}
node = node.parent()?;
}
parsed_node
}
fn parse_nodes(&self, nodes: Vec<Node>) -> Vec<Token> {
let mut tokens: Vec<Token> = vec![];
let mut current_nodes: Box<Vec<Node>> = Box::new(nodes);
while current_nodes.len() > 0 {
let mut new_nodes: Box<Vec<Node>> = Box::default();
for node in current_nodes.into_iter() {
if node.is_error() {
continue;
}
match self.parse_node(node, None) {
Some(token) => tokens.push(token),
None => {
if node.child_count() > 0 {
let mut cursor = node.walk();
new_nodes
.append(&mut node.children(&mut cursor).collect::<Vec<Node>>());
}
}
};
}
current_nodes = new_nodes;
}
tokens
}
fn parse_node(&self, node: Node, point: Option<Point>) -> Option<Token> {
match node.kind() {
"class_declaration" => self.parse_class_declaration(node),
"method_declaration" => self.parse_method_declaration(node),
"scoped_call_expression" | "member_call_expression" | "function_call_expression" => {
self.parse_call_expression(node, point)
}
"function_definition" => self.parse_function_definition(node),
"comment" => self.parse_comment(node),
_ => None,
}
}
fn parse_function_definition(&self, node: Node) -> Option<Token> {
let name_node = node.child_by_field_name("name")?;
let name = self.get_node_text(&name_node);
if name.starts_with("hook") {
let parameters_node = node.child_by_field_name("parameters")?;
let parameters = self
.get_node_text(¶meters_node)
.trim_matches(['(', ')']);
return Some(Token::new(
TokenData::DrupalHookDefinition(DrupalHook {
name: name.to_string(),
parameters: Some(parameters.to_string()),
}),
node.range(),
));
}
None
}
fn parse_comment(&self, node: Node) -> Option<Token> {
let text = self.get_node_text(&node);
// A comment with the text "Implements hook_NAME" is a reference to a Drupal hook.
if text.contains("Implements hook_") {
let start_bytes = text.find("hook_")?;
let end_bytes = text.find("()")?;
let hook_name = &text[start_bytes..end_bytes];
return Some(Token::new(
TokenData::DrupalHookReference(hook_name.to_string()),
node.range(),
));
}
None
}
fn parse_call_expression(&self, node: Node, point: Option<Point>) -> Option<Token> {
let string_content = node.descendant_for_point_range(point?, point?)?;
let name_node = match node.kind() {
"function_call_expression" => node.child_by_field_name("function"),
_ => node.child_by_field_name("name"),
}?;
let name = self.get_node_text(&name_node);
if node.kind() == "member_call_expression" {
let object_node = node.child_by_field_name("object")?;
if self.get_node_text(&object_node).contains("Drupal::service") {
let arguments = object_node.child_by_field_name("arguments")?;
let service_name = self
.get_node_text(&arguments)
.trim_matches(|c| c == '\'' || c == '(' || c == ')');
return Some(Token::new(
TokenData::PhpMethodReference(PhpMethod {
name: name.to_string(),
class_name: None,
service_name: Some(service_name.to_string()),
}),
node.range(),
));
}
}
if string_content.kind() != "string_content" {
return None;
}
if name == "fromRoute" || name == "createFromRoute" || name == "setRedirect" {
return Some(Token::new(
TokenData::DrupalRouteReference(self.get_node_text(&string_content).to_string()),
node.range(),
));
} else if name == "service" {
return Some(Token::new(
TokenData::DrupalServiceReference(self.get_node_text(&string_content).to_string()),
node.range(),
));
} else if name == "hasPermission" {
return Some(Token::new(
TokenData::DrupalPermissionReference(
self.get_node_text(&string_content).to_string(),
),
node.range(),
));
}
// TODO: This is a quite primitive way to detect ContainerInterface::get.
// Can we somehow get the interface of a given variable?
else if name == "get" {
let object_node = node.child_by_field_name("object")?;
let object = self.get_node_text(&object_node);
if object == "$container" {
return Some(Token::new(
TokenData::DrupalServiceReference(
self.get_node_text(&string_content).to_string(),
),
node.range(),
));
} else if object.contains("queueFactory") {
return Some(Token::new(
TokenData::DrupalPluginReference(DrupalPluginReference {
plugin_type: DrupalPluginType::QueueWorker,
plugin_id: self.get_node_text(&string_content).to_string(),
}),
node.range(),
));
}
} else if name == "getStorage" {
let object_node = node.child_by_field_name("object")?;
let object = self.get_node_text(&object_node);
if object.contains("entityTypeManager") {
return Some(Token::new(
TokenData::DrupalPluginReference(DrupalPluginReference {
plugin_type: DrupalPluginType::EntityType,
plugin_id: self.get_node_text(&string_content).to_string(),
}),
node.range(),
));
}
} else if name == "create" {
let scope_node = node.child_by_field_name("scope")?;
if self
.get_node_text(&scope_node)
.contains("BaseFieldDefinition")
{
return Some(Token::new(
TokenData::DrupalPluginReference(DrupalPluginReference {
plugin_type: DrupalPluginType::FieldType,
plugin_id: self.get_node_text(&string_content).to_string(),
}),
node.range(),
));
} else if self.get_node_text(&scope_node).contains("DataDefinition") {
return Some(Token::new(
TokenData::DrupalPluginReference(DrupalPluginReference {
plugin_type: DrupalPluginType::DataType,
plugin_id: self.get_node_text(&string_content).to_string(),
}),
node.range(),
));
}
} else if name == "queue" {
return Some(Token::new(
TokenData::DrupalPluginReference(DrupalPluginReference {
plugin_type: DrupalPluginType::QueueWorker,
plugin_id: self.get_node_text(&string_content).to_string(),
}),
node.range(),
));
} else if name == "t" {
return Some(Token::new(
TokenData::DrupalTranslationString(DrupalTranslationString {
string: self.get_node_text(&string_content).to_string(),
placeholders: None,
}),
node.range(),
));
}
None
}
fn parse_class_declaration(&self, node: Node) -> Option<Token> {
let mut methods: HashMap<String, Box<Token>> = HashMap::new();
if let Some(body_node) = node.child_by_field_name("body") {
let mut cursor = body_node.walk();
body_node.children(&mut cursor).for_each(|child| {
if let Some(token) = self.parse_method_declaration(child) {
if let TokenData::PhpMethodDefinition(token_data) = &token.data {
methods.insert(token_data.name.clone(), Box::new(token));
}
}
});
}
let mut class_attribute = None;
if let Some(attributes_node) = node.child_by_field_name("attributes") {
let attribute_group = attributes_node.child(0)?;
class_attribute = self.parse_class_attribute(attribute_group.named_child(0)?);
} else if let Some(comment_node) = node.prev_named_sibling() {
if comment_node.kind() == "comment" {
let text = self.get_node_text(&comment_node);
let re = Regex::new(r#"\*\s*@(?<type>.+)\("#).unwrap();
let mut plugin_type: Option<DrupalPluginType> = None;
if let Some(captures) = re.captures(text) {
if let Some(str) = captures.name("type") {
plugin_type = DrupalPluginType::try_from(str.as_str()).ok();
}
}
let re = Regex::new(r#"id\s*=\s*"(?<id>[^"]+)""#).unwrap();
let mut plugin_id: Option<String> = None;
if let Some(captures) = re.captures(text) {
if let Some(str) = captures.name("id") {
plugin_id = Some(str.as_str().to_string());
}
}
if let (Some(plugin_type), Some(plugin_id)) = (plugin_type, plugin_id) {
class_attribute = Some(ClassAttribute::Plugin(DrupalPlugin {
plugin_type,
plugin_id,
usage_example: self.extract_usage_example_from_comment(&comment_node),
}));
};
}
}
Some(Token::new(
TokenData::PhpClassDefinition(PhpClass {
name: self.get_class_name_from_node(node)?,
attribute: class_attribute,
methods,
}),
node.range(),
))
}
fn parse_method_declaration(&self, node: Node) -> Option<Token> {
if node.kind() != "method_declaration" {
return None;
}
let class_node = get_closest_parent_by_kind(&node, "class_declaration")?;
let name_node = node.child_by_field_name("name")?;
Some(Token::new(
TokenData::PhpMethodDefinition(PhpMethod {
name: self.get_node_text(&name_node).to_string(),
class_name: self.get_class_name_from_node(class_node),
service_name: None,
}),
node.range(),
))
}
fn parse_class_attribute(&self, node: Node) -> Option<ClassAttribute> {
if node.kind() != "attribute" {
return None;
}
let mut plugin_id = String::default();
// TODO: Look into improving this if we want to extract more than plugin id.
let parameters_node = node.child_by_field_name("parameters")?;
for argument in parameters_node.named_children(&mut parameters_node.walk()) {
// In the case of f.e `#[FormElement('date')]` there is no `id` field.
if self.get_node_text(&argument).starts_with("'")
&& self.get_node_text(&argument).ends_with("'")
{
plugin_id = self
.get_node_text(&argument)
.trim_matches(|c| c == '"' || c == '\'')
.to_string();
break;
}
let argument_name = argument.child_by_field_name("name")?;
if self.get_node_text(&argument_name) == "id" {
plugin_id = self
.get_node_text(&argument.named_child(1)?)
.trim_matches(|c| c == '"' || c == '\'')
.to_string()
}
}
match DrupalPluginType::try_from(self.get_node_text(&node.child(0)?)) {
Ok(plugin_type) => Some(ClassAttribute::Plugin(DrupalPlugin {
plugin_id,
plugin_type,
usage_example: self.extract_usage_example_from_comment(
&node.parent()?.parent()?.parent()?.prev_named_sibling()?,
),
})),
Err(_) => None,
}
}
fn get_class_name_from_node(&self, node: Node) -> Option<PhpClassName> {
if node.kind() != "class_declaration" {
return None;
}
let mut prev = node.prev_sibling();
while prev?.kind() != "namespace_definition" {
prev = prev?.prev_sibling();
}
if prev?.kind() != "namespace_definition" {
return None;
}
let namespace_node = prev?.child_by_field_name("name");
let namespace = self.get_node_text(&namespace_node?);
let name_node = node.child_by_field_name("name")?;
let name = self.get_node_text(&name_node);
Some(PhpClassName::from(
format!("{}\\{}", namespace, name).as_str(),
))
}
fn get_node_text(&self, node: &Node) -> &str {
node.utf8_text(self.source.as_bytes()).unwrap_or("")
}
/// Helper function to extract usage example from the preceding comment.
fn extract_usage_example_from_comment(&self, comment_node: &Node) -> Option<String> {
if comment_node.kind() != "comment" {
return None;
}
let comment_text = self.get_node_text(comment_node);
let start_tag = "@code";
let end_tag = "@endcode";
if let (Some(start_index), Some(end_index)) =
(comment_text.find(start_tag), comment_text.find(end_tag))
{
if end_index > start_index {
let code_start = start_index + start_tag.len();
let example = comment_text[code_start..end_index].trim();
// Regex to replace "* " or "*" from the beginning of a line.
let re = Regex::new(r"^\s*\*\s?").unwrap();
let cleaned_example = example
.lines()
.map(|line| re.replace(line, "").to_string())
.collect::<Vec<String>>();
return Some(
cleaned_example[..cleaned_example.len() - 1]
.join("\n")
.trim()
.to_string(),
);
}
}
None
}
}