dart-decimate 0.0.10 → 0.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1005 @@
1
+ use tree_sitter::Node;
2
+
3
+ use super::{
4
+ balanced_enclosed_text, class_extends_state, direct_constructor_call_text, direct_named_child,
5
+ direct_static_member_call_text, is_identifier_character, simple_type_name,
6
+ strip_constructor_keyword_prefix, strip_whitespace, unwrap_parenthesized_text,
7
+ };
8
+
9
+ const BUILD_CONTEXT: &str = "BuildContext";
10
+ const GO_ROUTER: &str = "GoRouter";
11
+ const GO_ROUTER_FACTORY_METHODS: &[&str] = &["of", "maybeOf", "routingConfig"];
12
+
13
+ enum NameResolution {
14
+ Type(String),
15
+ Shadowed,
16
+ }
17
+
18
+ impl NameResolution {
19
+ fn matches(&self, accepted: &[&str]) -> bool {
20
+ let Self::Type(type_name) = self else {
21
+ return false;
22
+ };
23
+ accepted.contains(&type_name.as_str())
24
+ }
25
+ }
26
+
27
+ struct NavigationTargetName {
28
+ name: String,
29
+ member_only: bool,
30
+ }
31
+
32
+ struct GoRouterFactoryCall {
33
+ method: &'static str,
34
+ prefix: Option<String>,
35
+ }
36
+
37
+ pub(super) fn route_extension_navigation_has_context_argument(
38
+ root: Node<'_>,
39
+ site: Node<'_>,
40
+ arguments: Node<'_>,
41
+ source: &str,
42
+ ) -> bool {
43
+ first_positional_argument(arguments)
44
+ .and_then(|argument| argument.utf8_text(source.as_bytes()).ok())
45
+ .and_then(navigation_target_name)
46
+ .is_some_and(|target| {
47
+ target_resolves_to_navigation_type(root, site, &target, &[BUILD_CONTEXT], source)
48
+ })
49
+ }
50
+
51
+ pub(super) fn navigation_receiver_accepts_route_location(
52
+ root: Node<'_>,
53
+ site: Node<'_>,
54
+ receiver: &str,
55
+ source: &str,
56
+ ) -> bool {
57
+ let receiver = receiver.trim_end_matches(['?', '!']);
58
+ if go_router_receiver_expression(root, site, receiver, source) {
59
+ return true;
60
+ }
61
+ navigation_target_name(receiver).is_some_and(|target| {
62
+ target_resolves_to_navigation_type(root, site, &target, &[BUILD_CONTEXT, GO_ROUTER], source)
63
+ })
64
+ }
65
+
66
+ fn go_router_receiver_expression(
67
+ root: Node<'_>,
68
+ site: Node<'_>,
69
+ receiver: &str,
70
+ source: &str,
71
+ ) -> bool {
72
+ let compact = strip_whitespace(receiver.trim());
73
+ let unwrapped = unwrap_parenthesized_text(&compact).unwrap_or(&compact);
74
+ let receiver = unwrapped.trim_end_matches(['?', '!']);
75
+ if direct_constructor_call_text(receiver, GO_ROUTER) {
76
+ return !term_identifier_shadowed_at(root, site, GO_ROUTER, source);
77
+ }
78
+ let Some(factory) = go_router_factory_call(receiver) else {
79
+ return false;
80
+ };
81
+ if let Some(prefix) = factory.prefix.as_deref() {
82
+ return !term_identifier_shadowed_at(root, site, prefix, source)
83
+ && go_router_import(root, Some(prefix), source);
84
+ }
85
+ !term_identifier_shadowed_at(root, site, GO_ROUTER, source)
86
+ && go_router_factory_available(root, factory.method, source)
87
+ }
88
+
89
+ fn go_router_factory_call(receiver: &str) -> Option<GoRouterFactoryCall> {
90
+ for &method in GO_ROUTER_FACTORY_METHODS {
91
+ if direct_static_member_call_text(receiver, GO_ROUTER, method) {
92
+ return Some(GoRouterFactoryCall {
93
+ method,
94
+ prefix: None,
95
+ });
96
+ }
97
+ if let Some(prefix) = direct_prefixed_static_member_call_text(receiver, GO_ROUTER, method) {
98
+ return Some(GoRouterFactoryCall {
99
+ method,
100
+ prefix: Some(prefix),
101
+ });
102
+ }
103
+ }
104
+ None
105
+ }
106
+
107
+ fn direct_prefixed_static_member_call_text(
108
+ text: &str,
109
+ type_name: &str,
110
+ member_name: &str,
111
+ ) -> Option<String> {
112
+ let receiver = unwrap_parenthesized_text(text.trim())?;
113
+ let type_marker = format!(".{type_name}");
114
+ let type_start = receiver.find(&type_marker)?;
115
+ let prefix = &receiver[..type_start];
116
+ if !is_simple_identifier(prefix) {
117
+ return None;
118
+ }
119
+ let after_type = receiver.get(type_start + type_marker.len()..)?;
120
+ let after_dot = after_type.strip_prefix('.')?;
121
+ let args_start = after_dot.find('(')?;
122
+ let method = after_dot[..args_start].split('<').next().unwrap_or("");
123
+ (method == member_name
124
+ && is_simple_identifier(method)
125
+ && balanced_enclosed_text(&after_dot[args_start..], '(', ')'))
126
+ .then(|| prefix.to_owned())
127
+ }
128
+
129
+ fn go_router_factory_available(root: Node<'_>, method: &str, source: &str) -> bool {
130
+ if let Some(class) = local_go_router_class(root, source) {
131
+ return local_go_router_class_has_factory(class, method, source);
132
+ }
133
+ go_router_import(root, None, source)
134
+ }
135
+
136
+ fn local_go_router_class<'tree>(root: Node<'tree>, source: &str) -> Option<Node<'tree>> {
137
+ if root.kind() == "class_declaration"
138
+ && field_text(root, "name", source).as_deref() == Some(GO_ROUTER)
139
+ {
140
+ return Some(root);
141
+ }
142
+ let mut cursor = root.walk();
143
+ for child in root.named_children(&mut cursor) {
144
+ if let Some(found) = local_go_router_class(child, source) {
145
+ return Some(found);
146
+ }
147
+ }
148
+ None
149
+ }
150
+
151
+ fn local_go_router_class_has_factory(class: Node<'_>, method: &str, source: &str) -> bool {
152
+ let Some(body) = class.child_by_field_name("body") else {
153
+ return false;
154
+ };
155
+ let mut cursor = body.walk();
156
+ body.named_children(&mut cursor).any(|member| {
157
+ (matches!(member.kind(), "class_member" | "method_declaration")
158
+ && static_method_returns_type(member, method, GO_ROUTER, source))
159
+ || (method == "routingConfig" && class_has_named_constructor(member, method, source))
160
+ })
161
+ }
162
+
163
+ fn static_method_returns_type(node: Node<'_>, method: &str, type_name: &str, source: &str) -> bool {
164
+ let Some(text) = node.utf8_text(source.as_bytes()).ok() else {
165
+ return false;
166
+ };
167
+ text.split_whitespace().any(|part| part == "static")
168
+ && declared_type_before_name(text, method).as_deref() == Some(type_name)
169
+ }
170
+
171
+ fn class_has_named_constructor(node: Node<'_>, method: &str, source: &str) -> bool {
172
+ let Some(text) = node.utf8_text(source.as_bytes()).ok() else {
173
+ return false;
174
+ };
175
+ let compact = strip_whitespace(text);
176
+ [
177
+ format!("{GO_ROUTER}.{method}("),
178
+ format!("const{GO_ROUTER}.{method}("),
179
+ format!("factory{GO_ROUTER}.{method}("),
180
+ ]
181
+ .iter()
182
+ .any(|prefix| compact.starts_with(prefix))
183
+ }
184
+
185
+ fn go_router_import(root: Node<'_>, prefix: Option<&str>, source: &str) -> bool {
186
+ let mut found = false;
187
+ visit_named(root, &mut |node| {
188
+ if found || node.kind() != "library_import" {
189
+ return;
190
+ }
191
+ if import_alias(node, source).as_deref() != prefix {
192
+ return;
193
+ }
194
+ if import_uri(node, source).as_deref() == Some("package:go_router/go_router.dart") {
195
+ found = true;
196
+ }
197
+ });
198
+ found
199
+ }
200
+
201
+ fn import_alias(node: Node<'_>, source: &str) -> Option<String> {
202
+ find_first_named_descendant(node, "import_specification")
203
+ .and_then(|specification| field_text(specification, "alias", source))
204
+ }
205
+
206
+ fn import_uri(node: Node<'_>, source: &str) -> Option<String> {
207
+ find_first_named_descendant(node, "uri")
208
+ .and_then(|uri| uri.utf8_text(source.as_bytes()).ok())
209
+ .and_then(unquote_dart_string)
210
+ }
211
+
212
+ fn unquote_dart_string(text: &str) -> Option<String> {
213
+ let trimmed = text.trim().trim_start_matches('r');
214
+ let quote = trimmed.chars().next()?;
215
+ if quote != '\'' && quote != '"' {
216
+ return None;
217
+ }
218
+ trimmed
219
+ .strip_prefix(quote)
220
+ .and_then(|rest| rest.strip_suffix(quote))
221
+ .map(str::to_owned)
222
+ }
223
+
224
+ fn term_identifier_shadowed_at(root: Node<'_>, site: Node<'_>, name: &str, source: &str) -> bool {
225
+ let mut path_child = site;
226
+ let mut parent = site.parent();
227
+ while let Some(scope) = parent {
228
+ if callable_parameter_declares_name(scope, name, source)
229
+ || prior_term_binding_shadows_name(scope, path_child, name, source)
230
+ || scoped_header_binding_exists(scope, path_child, site.start_byte(), name, source)
231
+ {
232
+ return true;
233
+ }
234
+ if scope.kind() == "class_body" && class_member_declares_name(scope, name, source) {
235
+ return true;
236
+ }
237
+ if same_node(scope, root) {
238
+ break;
239
+ }
240
+ path_child = scope;
241
+ parent = scope.parent();
242
+ }
243
+ false
244
+ }
245
+
246
+ fn callable_parameter_declares_name(node: Node<'_>, name: &str, source: &str) -> bool {
247
+ if !is_callable_node(node.kind()) {
248
+ return false;
249
+ }
250
+ direct_parameter_lists(node).into_iter().any(|parameters| {
251
+ direct_formal_parameters(parameters)
252
+ .into_iter()
253
+ .any(|parameter| formal_parameter_name(parameter, source).as_deref() == Some(name))
254
+ })
255
+ }
256
+
257
+ fn prior_term_binding_shadows_name(
258
+ scope: Node<'_>,
259
+ path_child: Node<'_>,
260
+ name: &str,
261
+ source: &str,
262
+ ) -> bool {
263
+ let mut cursor = scope.walk();
264
+ let mut siblings = Vec::new();
265
+ for sibling in scope.named_children(&mut cursor) {
266
+ if same_node(sibling, path_child) || sibling.start_byte() >= path_child.start_byte() {
267
+ break;
268
+ }
269
+ siblings.push(sibling);
270
+ }
271
+ siblings
272
+ .into_iter()
273
+ .rev()
274
+ .any(|sibling| lexical_term_binding_shadows_name(sibling, name, source))
275
+ }
276
+
277
+ fn lexical_term_binding_shadows_name(node: Node<'_>, name: &str, source: &str) -> bool {
278
+ if local_function_name(node, source).as_deref() == Some(name) {
279
+ return true;
280
+ }
281
+ if is_callable_node(node.kind()) {
282
+ return false;
283
+ }
284
+ if lexical_declaration_node(node.kind()) && declaration_binds_name(node, name, source) {
285
+ return true;
286
+ }
287
+ if !matches!(node.kind(), "statement" | "expression_statement") {
288
+ return false;
289
+ }
290
+ let mut cursor = node.walk();
291
+ node.named_children(&mut cursor)
292
+ .any(|child| lexical_term_binding_shadows_name(child, name, source))
293
+ }
294
+
295
+ fn class_member_declares_name(class_body: Node<'_>, name: &str, source: &str) -> bool {
296
+ let mut cursor = class_body.walk();
297
+ class_body.named_children(&mut cursor).any(|member| {
298
+ method_name(member, source).as_deref() == Some(name)
299
+ || (!is_callable_node(member.kind()) && declaration_binds_name(member, name, source))
300
+ })
301
+ }
302
+
303
+ fn first_positional_argument(arguments: Node<'_>) -> Option<Node<'_>> {
304
+ let mut cursor = arguments.walk();
305
+ arguments
306
+ .named_children(&mut cursor)
307
+ .find(|argument| argument.kind() != "named_argument")
308
+ }
309
+
310
+ fn navigation_target_name(text: &str) -> Option<NavigationTargetName> {
311
+ let compact = strip_whitespace(text.trim());
312
+ let unwrapped = unwrap_parenthesized_text(&compact).unwrap_or(&compact);
313
+ let target = unwrapped.trim_end_matches(['?', '!']);
314
+ let (member_only, name) = target
315
+ .strip_prefix("this.")
316
+ .map_or((false, target), |member| (true, member));
317
+ is_simple_identifier(name).then(|| NavigationTargetName {
318
+ name: name.to_owned(),
319
+ member_only,
320
+ })
321
+ }
322
+
323
+ fn target_resolves_to_navigation_type(
324
+ root: Node<'_>,
325
+ site: Node<'_>,
326
+ target: &NavigationTargetName,
327
+ accepted: &[&str],
328
+ source: &str,
329
+ ) -> bool {
330
+ let resolution = if target.member_only {
331
+ class_member_resolution_at(root, site, &target.name, source)
332
+ } else {
333
+ visible_name_resolution_at(root, site, &target.name, source)
334
+ };
335
+ resolution.is_some_and(|resolution| resolution.matches(accepted))
336
+ }
337
+
338
+ fn visible_name_resolution_at(
339
+ root: Node<'_>,
340
+ site: Node<'_>,
341
+ name: &str,
342
+ source: &str,
343
+ ) -> Option<NameResolution> {
344
+ let mut path_child = site;
345
+ let mut parent = site.parent();
346
+ while let Some(scope) = parent {
347
+ if let Some(resolution) = callable_parameter_resolution(root, scope, name, source) {
348
+ return Some(resolution);
349
+ }
350
+ if let Some(resolution) = prior_binding_resolution(root, scope, path_child, name, source) {
351
+ return Some(resolution);
352
+ }
353
+ if scoped_header_binding_exists(scope, path_child, site.start_byte(), name, source) {
354
+ return Some(NameResolution::Shadowed);
355
+ }
356
+ if scope.kind() == "class_body" {
357
+ if let Some(resolution) = class_member_resolution(root, scope, name, source) {
358
+ return Some(resolution);
359
+ }
360
+ if name == "context" && class_extends_state(scope, source) {
361
+ return Some(NameResolution::Type(BUILD_CONTEXT.to_owned()));
362
+ }
363
+ }
364
+ if same_node(scope, root) {
365
+ break;
366
+ }
367
+ path_child = scope;
368
+ parent = scope.parent();
369
+ }
370
+ None
371
+ }
372
+
373
+ fn class_member_resolution_at(
374
+ root: Node<'_>,
375
+ site: Node<'_>,
376
+ name: &str,
377
+ source: &str,
378
+ ) -> Option<NameResolution> {
379
+ let mut current = site.parent();
380
+ while let Some(scope) = current {
381
+ if scope.kind() == "class_body" {
382
+ if let Some(resolution) = class_member_resolution(root, scope, name, source) {
383
+ return Some(resolution);
384
+ }
385
+ if name == "context" && class_extends_state(scope, source) {
386
+ return Some(NameResolution::Type(BUILD_CONTEXT.to_owned()));
387
+ }
388
+ return None;
389
+ }
390
+ current = scope.parent();
391
+ }
392
+ None
393
+ }
394
+
395
+ fn prior_binding_resolution(
396
+ root: Node<'_>,
397
+ scope: Node<'_>,
398
+ path_child: Node<'_>,
399
+ name: &str,
400
+ source: &str,
401
+ ) -> Option<NameResolution> {
402
+ let mut cursor = scope.walk();
403
+ let mut siblings = Vec::new();
404
+ for sibling in scope.named_children(&mut cursor) {
405
+ if same_node(sibling, path_child) || sibling.start_byte() >= path_child.start_byte() {
406
+ break;
407
+ }
408
+ siblings.push(sibling);
409
+ }
410
+ for sibling in siblings.into_iter().rev() {
411
+ if let Some(resolution) = lexical_binding_resolution(root, sibling, name, source) {
412
+ return Some(resolution);
413
+ }
414
+ }
415
+ None
416
+ }
417
+
418
+ fn lexical_binding_resolution(
419
+ root: Node<'_>,
420
+ node: Node<'_>,
421
+ name: &str,
422
+ source: &str,
423
+ ) -> Option<NameResolution> {
424
+ if node.kind() == "local_function_declaration"
425
+ && local_function_name(node, source).as_deref() == Some(name)
426
+ {
427
+ return Some(NameResolution::Shadowed);
428
+ }
429
+ if is_callable_node(node.kind()) {
430
+ return None;
431
+ }
432
+ if lexical_declaration_node(node.kind()) && declaration_binds_name(node, name, source) {
433
+ return Some(declaration_type_resolution(root, node, name, source));
434
+ }
435
+ if !matches!(node.kind(), "statement" | "expression_statement") {
436
+ return None;
437
+ }
438
+ let mut cursor = node.walk();
439
+ for child in node.named_children(&mut cursor) {
440
+ if let Some(resolution) = lexical_binding_resolution(root, child, name, source) {
441
+ return Some(resolution);
442
+ }
443
+ }
444
+ None
445
+ }
446
+
447
+ fn callable_parameter_resolution(
448
+ root: Node<'_>,
449
+ node: Node<'_>,
450
+ name: &str,
451
+ source: &str,
452
+ ) -> Option<NameResolution> {
453
+ if !is_callable_node(node.kind()) {
454
+ return None;
455
+ }
456
+ for parameters in direct_parameter_lists(node) {
457
+ for parameter in direct_formal_parameters(parameters) {
458
+ if formal_parameter_name(parameter, source).as_deref() == Some(name) {
459
+ return Some(declaration_type_resolution(root, parameter, name, source));
460
+ }
461
+ }
462
+ }
463
+ None
464
+ }
465
+
466
+ fn class_member_resolution(
467
+ root: Node<'_>,
468
+ class_body: Node<'_>,
469
+ name: &str,
470
+ source: &str,
471
+ ) -> Option<NameResolution> {
472
+ let mut cursor = class_body.walk();
473
+ for member in class_body.named_children(&mut cursor) {
474
+ if member.kind() == "method_declaration"
475
+ && method_name(member, source).as_deref() == Some(name)
476
+ {
477
+ return Some(if method_is_getter(member, source) {
478
+ declaration_type_resolution(root, member, name, source)
479
+ } else {
480
+ NameResolution::Shadowed
481
+ });
482
+ }
483
+ if is_callable_node(member.kind()) {
484
+ continue;
485
+ }
486
+ if declaration_binds_name(member, name, source) {
487
+ return Some(declaration_type_resolution(root, member, name, source));
488
+ }
489
+ }
490
+ None
491
+ }
492
+
493
+ fn declaration_type_resolution(
494
+ root: Node<'_>,
495
+ node: Node<'_>,
496
+ name: &str,
497
+ source: &str,
498
+ ) -> NameResolution {
499
+ if node.kind() == "formal_parameter" {
500
+ return formal_parameter_type(root, node, name, source)
501
+ .map_or(NameResolution::Shadowed, NameResolution::Type);
502
+ }
503
+ if let Some(resolution) = declared_type_for_name(root, node, name, source) {
504
+ return resolution;
505
+ }
506
+ initializer_type_for_name(root, node, name, source)
507
+ .map_or(NameResolution::Shadowed, NameResolution::Type)
508
+ }
509
+
510
+ fn declared_type_for_name(
511
+ root: Node<'_>,
512
+ node: Node<'_>,
513
+ name: &str,
514
+ source: &str,
515
+ ) -> Option<NameResolution> {
516
+ let text = node.utf8_text(source.as_bytes()).ok()?;
517
+ if declaration_binds_name(node, name, source)
518
+ && let Some(type_name) = raw_declared_type_before_name(text, name)
519
+ {
520
+ return Some(
521
+ declared_navigation_type(root, &type_name, source)
522
+ .map_or(NameResolution::Shadowed, NameResolution::Type),
523
+ );
524
+ }
525
+ let mut cursor = node.walk();
526
+ for child in node.named_children(&mut cursor) {
527
+ if is_callable_node(child.kind()) {
528
+ continue;
529
+ }
530
+ if let Some(resolution) = declared_type_for_name(root, child, name, source) {
531
+ return Some(resolution);
532
+ }
533
+ }
534
+ None
535
+ }
536
+
537
+ fn declared_type_before_name(text: &str, name: &str) -> Option<String> {
538
+ raw_declared_type_before_name(text, name).map(|type_name| simple_type_name(&type_name))
539
+ }
540
+
541
+ fn raw_declared_type_before_name(text: &str, name: &str) -> Option<String> {
542
+ let declaration = text.split('=').next().unwrap_or(text);
543
+ let name_start = find_identifier(declaration, name)?;
544
+ let before_name = declaration[..name_start].trim();
545
+ let type_name = before_name
546
+ .split_whitespace()
547
+ .map(|part| part.trim_matches(type_token_trim))
548
+ .rfind(|part| !part.is_empty() && !declaration_type_keyword(part))?;
549
+ Some(type_name.trim_end_matches('?').to_owned())
550
+ }
551
+
552
+ fn declared_navigation_type(root: Node<'_>, type_name: &str, source: &str) -> Option<String> {
553
+ let type_name = type_name.trim().trim_end_matches('?');
554
+ let base = type_name.split('<').next().unwrap_or(type_name).trim();
555
+ if let Some((prefix, simple)) = base.rsplit_once('.') {
556
+ if !is_simple_identifier(prefix) || !is_simple_identifier(simple) {
557
+ return None;
558
+ }
559
+ return match simple {
560
+ BUILD_CONTEXT => framework_build_context_import(root, Some(prefix), source),
561
+ GO_ROUTER => go_router_import(root, Some(prefix), source),
562
+ _ => false,
563
+ }
564
+ .then(|| simple.to_owned());
565
+ }
566
+ Some(simple_type_name(base))
567
+ }
568
+
569
+ fn framework_build_context_import(root: Node<'_>, prefix: Option<&str>, source: &str) -> bool {
570
+ let mut found = false;
571
+ visit_named(root, &mut |node| {
572
+ if found || node.kind() != "library_import" {
573
+ return;
574
+ }
575
+ if import_alias(node, source).as_deref() != prefix {
576
+ return;
577
+ }
578
+ if import_uri(node, source).is_some_and(|uri| uri.starts_with("package:flutter/")) {
579
+ found = true;
580
+ }
581
+ });
582
+ found
583
+ }
584
+
585
+ fn initializer_type_for_name(
586
+ root: Node<'_>,
587
+ node: Node<'_>,
588
+ name: &str,
589
+ source: &str,
590
+ ) -> Option<String> {
591
+ if field_text(node, "name", source).as_deref() == Some(name)
592
+ && let Some(type_name) = initializer_type(root, node, source)
593
+ {
594
+ return Some(type_name);
595
+ }
596
+ let mut cursor = node.walk();
597
+ for child in node.named_children(&mut cursor) {
598
+ if is_callable_node(child.kind()) {
599
+ continue;
600
+ }
601
+ if let Some(type_name) = initializer_type_for_name(root, child, name, source) {
602
+ return Some(type_name);
603
+ }
604
+ }
605
+ None
606
+ }
607
+
608
+ fn initializer_type(root: Node<'_>, node: Node<'_>, source: &str) -> Option<String> {
609
+ let text = node.utf8_text(source.as_bytes()).ok()?;
610
+ let (_, right) = text.split_once('=')?;
611
+ let expression = right.trim().trim_end_matches([',', ';']).trim();
612
+ let unwrapped = unwrap_parenthesized_text(expression).unwrap_or(expression);
613
+ let without_postfix = unwrapped.trim_end_matches(['?', '!']).trim();
614
+ let unwrapped = unwrap_parenthesized_text(without_postfix).unwrap_or(without_postfix);
615
+ let without_keyword = strip_constructor_keyword_prefix(unwrapped).unwrap_or(unwrapped);
616
+ let compact = strip_whitespace(without_keyword);
617
+ for target_type in [BUILD_CONTEXT, GO_ROUTER] {
618
+ if direct_constructor_call_text(&compact, target_type)
619
+ || (target_type == GO_ROUTER
620
+ && go_router_receiver_expression(root, node, &compact, source))
621
+ {
622
+ return Some(target_type.to_owned());
623
+ }
624
+ }
625
+ None
626
+ }
627
+
628
+ fn scoped_header_binding_exists(
629
+ scope: Node<'_>,
630
+ path_child: Node<'_>,
631
+ usage_start: usize,
632
+ name: &str,
633
+ source: &str,
634
+ ) -> bool {
635
+ if catch_header_binding_exists(scope, path_child, usage_start, name, source) {
636
+ return true;
637
+ }
638
+ if !matches!(
639
+ scope.kind(),
640
+ "for_element"
641
+ | "for_statement"
642
+ | "if_element"
643
+ | "if_statement"
644
+ | "switch_expression_case"
645
+ | "switch_statement_case"
646
+ ) {
647
+ return false;
648
+ }
649
+ let mut cursor = scope.walk();
650
+ for child in scope.named_children(&mut cursor) {
651
+ if same_node(child, path_child) || child.start_byte() >= path_child.start_byte() {
652
+ break;
653
+ }
654
+ if header_binding_child(scope.kind(), child)
655
+ && child.end_byte() <= usage_start
656
+ && declaration_binds_name(child, name, source)
657
+ {
658
+ return true;
659
+ }
660
+ }
661
+ false
662
+ }
663
+
664
+ fn catch_header_binding_exists(
665
+ scope: Node<'_>,
666
+ path_child: Node<'_>,
667
+ usage_start: usize,
668
+ name: &str,
669
+ source: &str,
670
+ ) -> bool {
671
+ if scope.kind() == "catch_clause" {
672
+ return scope.start_byte() < path_child.start_byte()
673
+ && catch_clause_binds_name(scope, name, source);
674
+ }
675
+ if scope.kind() == "try_statement" {
676
+ let mut previous: Option<Node<'_>> = None;
677
+ let mut cursor = scope.walk();
678
+ for child in scope.named_children(&mut cursor) {
679
+ if same_node(child, path_child) || child.start_byte() >= path_child.start_byte() {
680
+ return previous.is_some_and(|header| {
681
+ header.kind() == "catch_clause"
682
+ && matches!(path_child.kind(), "block" | "function_body")
683
+ && header.end_byte() <= usage_start
684
+ && source
685
+ .get(header.end_byte()..path_child.start_byte())
686
+ .is_some_and(|text| !text.contains("finally"))
687
+ && catch_clause_binds_name(header, name, source)
688
+ });
689
+ }
690
+ previous = Some(child);
691
+ }
692
+ }
693
+ false
694
+ }
695
+
696
+ fn catch_clause_binds_name(node: Node<'_>, name: &str, source: &str) -> bool {
697
+ field_text(node, "exception", source).as_deref() == Some(name)
698
+ || field_text(node, "stack_trace", source).as_deref() == Some(name)
699
+ }
700
+
701
+ fn header_binding_child(scope_kind: &str, child: Node<'_>) -> bool {
702
+ if matches!(scope_kind, "for_element" | "for_statement") {
703
+ return !is_body_statement_child(child.kind())
704
+ || child.kind() == "local_variable_declaration";
705
+ }
706
+ !is_body_statement_child(child.kind()) && node_can_contain_pattern_binding(child)
707
+ }
708
+
709
+ fn node_can_contain_pattern_binding(node: Node<'_>) -> bool {
710
+ let mut found = false;
711
+ visit_named(node, &mut |candidate| {
712
+ if !found
713
+ && matches!(
714
+ candidate.kind(),
715
+ "list_pattern"
716
+ | "local_variable_declaration"
717
+ | "map_pattern"
718
+ | "object_pattern"
719
+ | "pattern_variable_declaration"
720
+ | "record_pattern"
721
+ | "variable_pattern"
722
+ )
723
+ {
724
+ found = true;
725
+ }
726
+ });
727
+ found
728
+ }
729
+
730
+ fn is_body_statement_child(kind: &str) -> bool {
731
+ matches!(
732
+ kind,
733
+ "assert_statement"
734
+ | "block"
735
+ | "break_statement"
736
+ | "continue_statement"
737
+ | "declaration"
738
+ | "do_statement"
739
+ | "empty_statement"
740
+ | "expression_statement"
741
+ | "for_statement"
742
+ | "if_statement"
743
+ | "local_function_declaration"
744
+ | "local_variable_declaration"
745
+ | "return_statement"
746
+ | "switch_statement"
747
+ | "try_statement"
748
+ | "while_statement"
749
+ | "yield_statement"
750
+ )
751
+ }
752
+
753
+ fn declaration_binds_name(node: Node<'_>, name: &str, source: &str) -> bool {
754
+ if binding_name(node, source).as_deref() == Some(name) {
755
+ return true;
756
+ }
757
+ if is_callable_node(node.kind()) {
758
+ return false;
759
+ }
760
+ let mut cursor = node.walk();
761
+ node.named_children(&mut cursor)
762
+ .any(|child| declaration_binds_name(child, name, source))
763
+ }
764
+
765
+ fn binding_name(node: Node<'_>, source: &str) -> Option<String> {
766
+ if !matches!(
767
+ node.kind(),
768
+ "formal_parameter"
769
+ | "initialized_identifier"
770
+ | "initialized_variable_definition"
771
+ | "typed_identifier"
772
+ | "variable_pattern"
773
+ ) {
774
+ return None;
775
+ }
776
+ field_text(node, "name", source)
777
+ }
778
+
779
+ fn direct_parameter_lists(node: Node<'_>) -> Vec<Node<'_>> {
780
+ match node.kind() {
781
+ "function_expression" => parameter_field_lists(node),
782
+ "function_declaration" | "local_function_declaration" | "method_declaration" => {
783
+ helper_signature(node)
784
+ .and_then(parameter_list)
785
+ .or_else(|| parameter_list(node))
786
+ .into_iter()
787
+ .collect()
788
+ }
789
+ _ => Vec::new(),
790
+ }
791
+ }
792
+
793
+ fn direct_formal_parameters(parameters: Node<'_>) -> Vec<Node<'_>> {
794
+ let mut formal_parameters = Vec::new();
795
+ let mut cursor = parameters.walk();
796
+ for candidate in parameters.named_children(&mut cursor) {
797
+ if candidate.kind() == "optional_formal_parameters" {
798
+ let mut optional_cursor = candidate.walk();
799
+ formal_parameters.extend(candidate.named_children(&mut optional_cursor));
800
+ } else {
801
+ formal_parameters.push(candidate);
802
+ }
803
+ }
804
+ formal_parameters
805
+ }
806
+
807
+ fn parameter_field_lists(node: Node<'_>) -> Vec<Node<'_>> {
808
+ let mut cursor = node.walk();
809
+ node.children_by_field_name("parameters", &mut cursor)
810
+ .filter_map(formal_parameter_list)
811
+ .collect()
812
+ }
813
+
814
+ fn helper_signature(node: Node<'_>) -> Option<Node<'_>> {
815
+ let signature = node
816
+ .child_by_field_name("signature")
817
+ .or_else(|| direct_named_child(node, "function_signature"))
818
+ .or_else(|| direct_named_child(node, "method_signature"))?;
819
+ if signature.kind() == "method_signature" {
820
+ return direct_named_child(signature, "function_signature").or(Some(signature));
821
+ }
822
+ Some(signature)
823
+ }
824
+
825
+ fn parameter_list(node: Node<'_>) -> Option<Node<'_>> {
826
+ node.child_by_field_name("parameters")
827
+ .or_else(|| direct_named_child(node, "formal_parameter_list"))
828
+ }
829
+
830
+ fn formal_parameter_list(node: Node<'_>) -> Option<Node<'_>> {
831
+ if node.kind() == "formal_parameter_list" {
832
+ return Some(node);
833
+ }
834
+ let mut cursor = node.walk();
835
+ node.named_children(&mut cursor)
836
+ .find(|child| child.kind() == "formal_parameter_list")
837
+ }
838
+
839
+ fn formal_parameter_name(param: Node<'_>, source: &str) -> Option<String> {
840
+ field_text(param, "name", source).or_else(|| last_identifier_child(param, source))
841
+ }
842
+
843
+ fn formal_parameter_type(
844
+ root: Node<'_>,
845
+ param: Node<'_>,
846
+ name: &str,
847
+ source: &str,
848
+ ) -> Option<String> {
849
+ let text = param.utf8_text(source.as_bytes()).ok()?;
850
+ let name_index = find_identifier(text, name)?;
851
+ let before_name = text[..name_index].trim();
852
+ let type_name = before_name
853
+ .split_whitespace()
854
+ .map(|part| part.trim_matches(type_token_trim))
855
+ .rfind(|part| !part.is_empty() && !declaration_type_keyword(part))?;
856
+ declared_navigation_type(root, type_name, source)
857
+ }
858
+
859
+ fn last_identifier_child(node: Node<'_>, source: &str) -> Option<String> {
860
+ let mut cursor = node.walk();
861
+ node.named_children(&mut cursor)
862
+ .filter(|child| {
863
+ matches!(
864
+ child.kind(),
865
+ "identifier" | "identifier_dollar_escaped" | "type_identifier"
866
+ ) && child.utf8_text(source.as_bytes()).ok() != Some("key")
867
+ })
868
+ .filter_map(|child| child.utf8_text(source.as_bytes()).ok())
869
+ .last()
870
+ .map(str::to_owned)
871
+ }
872
+
873
+ fn field_text(node: Node<'_>, field: &str, source: &str) -> Option<String> {
874
+ node.child_by_field_name(field)
875
+ .and_then(|child| child.utf8_text(source.as_bytes()).ok())
876
+ .map(str::to_owned)
877
+ }
878
+
879
+ fn method_name(node: Node<'_>, source: &str) -> Option<String> {
880
+ direct_named_child(node, "function_signature")
881
+ .and_then(|signature| field_text(signature, "name", source))
882
+ .or_else(|| {
883
+ direct_named_child(node, "method_signature").and_then(|signature| {
884
+ direct_named_child(signature, "function_signature")
885
+ .and_then(|function| field_text(function, "name", source))
886
+ .or_else(|| field_text(signature, "name", source))
887
+ })
888
+ })
889
+ .or_else(|| field_text(node, "name", source))
890
+ }
891
+
892
+ fn method_is_getter(node: Node<'_>, source: &str) -> bool {
893
+ node.utf8_text(source.as_bytes())
894
+ .ok()
895
+ .is_some_and(|text| text.split_whitespace().any(|part| part == "get"))
896
+ }
897
+
898
+ fn local_function_name(node: Node<'_>, source: &str) -> Option<String> {
899
+ direct_named_child(node, "function_signature")
900
+ .and_then(|signature| signature.child_by_field_name("name"))
901
+ .or_else(|| node.child_by_field_name("name"))
902
+ .and_then(|name| name.utf8_text(source.as_bytes()).ok())
903
+ .map(str::to_owned)
904
+ }
905
+
906
+ fn find_identifier(text: &str, identifier: &str) -> Option<usize> {
907
+ let mut cursor = 0usize;
908
+ while let Some(relative) = text[cursor..].find(identifier) {
909
+ let start = cursor + relative;
910
+ let end = start + identifier.len();
911
+ if !identifier_continues_before(text, start)
912
+ && !text[end..]
913
+ .chars()
914
+ .next()
915
+ .is_some_and(is_identifier_character)
916
+ {
917
+ return Some(start);
918
+ }
919
+ cursor = end;
920
+ }
921
+ None
922
+ }
923
+
924
+ fn identifier_continues_before(text: &str, index: usize) -> bool {
925
+ text[..index]
926
+ .chars()
927
+ .next_back()
928
+ .is_some_and(is_identifier_character)
929
+ }
930
+
931
+ fn is_simple_identifier(text: &str) -> bool {
932
+ let mut chars = text.chars();
933
+ chars
934
+ .next()
935
+ .is_some_and(|first| first == '_' || first == '$' || first.is_ascii_alphabetic())
936
+ && chars.all(is_identifier_character)
937
+ }
938
+
939
+ fn find_first_named_descendant<'tree>(node: Node<'tree>, kind: &str) -> Option<Node<'tree>> {
940
+ if node.kind() == kind {
941
+ return Some(node);
942
+ }
943
+ let mut cursor = node.walk();
944
+ for child in node.named_children(&mut cursor) {
945
+ if let Some(found) = find_first_named_descendant(child, kind) {
946
+ return Some(found);
947
+ }
948
+ }
949
+ None
950
+ }
951
+
952
+ fn declaration_type_keyword(text: &str) -> bool {
953
+ matches!(
954
+ text,
955
+ "abstract"
956
+ | "const"
957
+ | "covariant"
958
+ | "external"
959
+ | "final"
960
+ | "get"
961
+ | "late"
962
+ | "required"
963
+ | "set"
964
+ | "static"
965
+ | "var"
966
+ )
967
+ }
968
+
969
+ fn type_token_trim(character: char) -> bool {
970
+ matches!(
971
+ character,
972
+ ',' | ';' | '(' | ')' | '{' | '}' | '[' | ']' | '?' | ':'
973
+ )
974
+ }
975
+
976
+ fn is_callable_node(kind: &str) -> bool {
977
+ matches!(
978
+ kind,
979
+ "function_declaration"
980
+ | "function_expression"
981
+ | "local_function_declaration"
982
+ | "method_declaration"
983
+ )
984
+ }
985
+
986
+ fn lexical_declaration_node(kind: &str) -> bool {
987
+ matches!(
988
+ kind,
989
+ "local_variable_declaration" | "pattern_variable_declaration"
990
+ )
991
+ }
992
+
993
+ fn visit_named(node: Node<'_>, visitor: &mut impl FnMut(Node<'_>)) {
994
+ visitor(node);
995
+ let mut cursor = node.walk();
996
+ for child in node.named_children(&mut cursor) {
997
+ visit_named(child, visitor);
998
+ }
999
+ }
1000
+
1001
+ fn same_node(left: Node<'_>, right: Node<'_>) -> bool {
1002
+ left.kind() == right.kind()
1003
+ && left.start_byte() == right.start_byte()
1004
+ && left.end_byte() == right.end_byte()
1005
+ }