forked from PHPantom-dev/phpantom_lsp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcall_resolution.rs
More file actions
2805 lines (2620 loc) · 127 KB
/
Copy pathcall_resolution.rs
File metadata and controls
2805 lines (2620 loc) · 127 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
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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Call expression and callable target resolution.
//!
//! ## Callable target cache
//!
//! During diagnostic passes, `resolve_instance_method_callable` is
//! called for every call site in the file. Many different chain
//! expressions resolve to the same (class, method) pair — e.g.
//! `$q->where(...)`, `$query->where(...)`, and
//! `Product::query()->where(...)` all end up looking for `where` on
//! `Builder<Product>`. The per-file callable-target cache
//! (`CALLABLE_TARGET_CACHE`) stores `Option<ResolvedCallableTarget>`
//! keyed by `(class_fqn, method_name_lower)` so these redundant
//! resolutions are free after the first hit.
///
/// This module contains the logic for resolving call expressions (method
/// calls, static calls, function calls, constructor calls) to their
/// return types, as well as resolving callable targets for signature help
/// and named-argument completion.
///
/// Split from [`super::resolver`] for navigability. The entry points are:
///
/// - [`Backend::resolve_callable_target`]: resolves a call expression
/// string to a [`ResolvedCallableTarget`] with label, parameters, and
/// return type (used by signature help and named-argument completion).
/// - [`Backend::resolve_call_return_types_expr_with_hint`]: resolves the return
/// type of a structured [`SubjectExpr`] callee + argument text to
/// zero or more `ClassInfo` values (used by the completion chain).
/// - [`Backend::resolve_method_return_types_with_args`]: resolves a
/// method's return type on a specific class, handling conditional
/// return types and template substitutions.
/// - [`Backend::build_method_template_subs`]: builds a template
/// substitution map for method-level `@template` parameters from
/// pre-split call-site argument texts.
use std::cell::{Cell, RefCell};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use crate::Backend;
use crate::atom::atom;
use crate::completion::variable::rhs_resolution::{TemplateBindingMode, classify_template_binding};
use crate::completion::variable::{ARRAY_ELEMENT_FUNCS, ARRAY_PRESERVING_FUNCS};
use crate::docblock;
use crate::php_type::PhpType;
use crate::subject_expr::SubjectExpr;
use crate::types::ClassLikeKind;
use crate::types::*;
use crate::util::{
find_class_at_offset, is_self_or_static, position_to_offset, resolve_class_keyword,
};
use super::conditional_resolution::{
TemplateContext, VarClassStringResolver, resolve_conditional_with_text_args,
resolve_conditional_with_text_args_and_defaults, resolve_conditional_without_args,
resolve_conditional_without_args_and_defaults, split_call_subject, split_text_args,
};
use super::resolver::{Loaders, ResolutionCtx};
use crate::util::find_class_by_name;
use tower_lsp::lsp_types::Position;
/// Bundled parameters for [`Backend::resolve_method_return_types_with_args`].
///
/// Groups the resolution-context fields that are threaded through method
/// return-type resolution so the function stays within clippy's argument
/// limit.
pub(super) struct MethodReturnCtx<'a> {
/// All classes known in the current file.
pub all_classes: &'a [Arc<ClassInfo>],
/// Cross-file class resolution callback.
pub class_loader: &'a dyn Fn(&str) -> Option<Arc<ClassInfo>>,
/// Template substitution map (method-level `@template` bindings).
pub template_subs: &'a HashMap<String, PhpType>,
/// Resolves a variable name to class-string values (for conditional
/// return type evaluation).
pub var_resolver: VarClassStringResolver<'a>,
/// Shared resolved-class cache (when available).
pub cache: Option<&'a crate::virtual_members::ResolvedClassCache>,
/// The class at the call site (where `self::class` / `static::class`
/// appears), as opposed to the class that owns the method being called.
/// Used to resolve `self`/`static`/`parent` in conditional return types.
pub calling_class_name: Option<&'a str>,
/// Whether the call is a static method call (`Class::method()`).
///
/// When `true`, the magic-method fallback checks `__callStatic`
/// instead of `__call`.
pub is_static: bool,
}
/// Build a [`VarClassStringResolver`] closure from a [`ResolutionCtx`].
///
/// The returned closure resolves a variable name (e.g. `"$requestType"`)
/// to the class names it holds as class-string values by delegating to
/// [`resolve_class_string_targets`](crate::completion::variable::class_string_resolution::resolve_class_string_targets).
pub(super) fn build_var_resolver<'a>(
ctx: &'a ResolutionCtx<'a>,
) -> impl Fn(&str) -> Vec<String> + 'a {
move |var_name: &str| -> Vec<String> {
if let Some(cc) = ctx.current_class {
crate::completion::variable::class_string_resolution::resolve_class_string_targets(
var_name,
cc,
ctx.all_classes,
ctx.content,
ctx.cursor_offset,
ctx.class_loader,
)
.iter()
.map(|c| c.name.to_string())
.collect()
} else {
vec![]
}
}
}
// ─── Thread-local caches and body return inference ──────────────────────────
/// Closure type for body return type inference.
///
/// Takes `(class_fqn, &MethodInfo)` and returns `Some(PhpType)` when the
/// method body can be scanned for return statements.
type BodyReturnInferrerFn = Box<dyn Fn(&str, &MethodInfo) -> Option<PhpType>>;
thread_local! {
/// When `Some`, `resolve_instance_method_callable` caches results
/// by `"FQN::method_lower"`. Activated by
/// [`with_callable_target_cache`], cleared on guard drop.
static CALLABLE_TARGET_CACHE: RefCell<Option<HashMap<String, Option<ResolvedCallableTarget>>>> =
const { RefCell::new(None) };
/// When `Some`, methods without a declared return type can have
/// their return type inferred by scanning the method body.
///
/// The closure takes `(class_fqn, &MethodInfo)` and returns
/// `Some(PhpType)` when inference succeeds. Set up by
/// [`with_body_return_inferrer`] at request entry points that
/// have access to `Backend`.
static BODY_RETURN_INFERRER: RefCell<Option<BodyReturnInferrerFn>> =
const { RefCell::new(None) };
/// Re-entry guard for body return inference. Tracks
/// `"FQN::method"` keys currently being inferred to prevent
/// infinite recursion when a method body references another
/// method that also lacks a return type.
static BODY_INFER_VISITED: RefCell<HashSet<String>> =
RefCell::new(HashSet::new());
/// Current nesting depth of body return inference. Caps the
/// chain length so that A→B→C→D… doesn't trigger unbounded
/// sequential body scans. Each scan runs `resolve_variable_types`
/// (forward walker + full resolution), so even non-recursive
/// chains are expensive.
static BODY_INFER_DEPTH: Cell<u8> = const { Cell::new(0) };
}
/// RAII guard that clears the callable target cache on drop.
pub(crate) struct CallableTargetCacheGuard {
owns: bool,
}
impl Drop for CallableTargetCacheGuard {
fn drop(&mut self) {
if self.owns {
CALLABLE_TARGET_CACHE.with(|cell| {
*cell.borrow_mut() = None;
});
}
}
}
/// Activate the thread-local callable target cache.
///
/// While the returned guard is alive, `resolve_instance_method_callable`
/// caches callable target resolutions by `"FQN::method_lower"` so
/// that the same method on the same class is resolved at most once per
/// diagnostic pass, regardless of how many different chain expressions
/// lead to it.
pub(crate) fn with_callable_target_cache() -> CallableTargetCacheGuard {
let already_active = CALLABLE_TARGET_CACHE.with(|cell| cell.borrow().is_some());
if already_active {
return CallableTargetCacheGuard { owns: false };
}
CALLABLE_TARGET_CACHE.with(|cell| {
*cell.borrow_mut() = Some(HashMap::new());
});
CallableTargetCacheGuard { owns: true }
}
// ── Body return type inference ──────────────────────────────────────────────
/// RAII guard that clears [`BODY_RETURN_INFERRER`] on drop.
pub(crate) struct BodyReturnInferrerGuard {
owns: bool,
}
impl Drop for BodyReturnInferrerGuard {
fn drop(&mut self) {
if self.owns {
BODY_RETURN_INFERRER.with(|cell| {
*cell.borrow_mut() = None;
});
}
}
}
/// Activate body return type inference for the current thread.
///
/// The provided closure is called when `resolve_method_return_types_with_args`
/// encounters a real (non-virtual, non-stub) method that has no declared
/// return type and no `@return` docblock. It receives the owning class's
/// FQN and the `MethodInfo`, and should return `Some(PhpType)` when the
/// method body can be scanned for return statements.
///
/// Returns an RAII guard that clears the inferrer on drop.
pub(crate) fn with_body_return_inferrer(inferrer: BodyReturnInferrerFn) -> BodyReturnInferrerGuard {
let already_active = BODY_RETURN_INFERRER.with(|cell| cell.borrow().is_some());
if already_active {
return BodyReturnInferrerGuard { owns: false };
}
BODY_RETURN_INFERRER.with(|cell| {
*cell.borrow_mut() = Some(inferrer);
});
BodyReturnInferrerGuard { owns: true }
}
/// Try to infer a method's return type from its body using the
/// thread-local [`BODY_RETURN_INFERRER`].
///
/// Returns `None` when no inferrer is active, when the method is
/// already being inferred (re-entry), or when inference itself
/// produces no result.
/// Maximum nesting depth for body return inference chains.
///
/// A→B→C is 3 levels deep. Real PHP code rarely has long chains of
/// untyped methods calling each other, and each level runs a full
/// forward-walk body scan, so keeping this low avoids expensive
/// sequential scans on pathological code.
const MAX_BODY_INFER_DEPTH: u8 = 3;
pub(crate) fn try_infer_body_return_type(class_fqn: &str, method: &MethodInfo) -> Option<PhpType> {
// Depth cap: avoid long chains of sequential body scans.
let depth = BODY_INFER_DEPTH.with(|cell| cell.get());
if depth >= MAX_BODY_INFER_DEPTH {
return None;
}
// Build a re-entry key.
let key = format!("{}::{}", class_fqn, method.name);
// Check + insert into the visited set (re-entry guard).
let already_visiting = BODY_INFER_VISITED.with(|cell| {
let mut set = cell.borrow_mut();
!set.insert(key.clone())
});
if already_visiting {
return None;
}
BODY_INFER_DEPTH.with(|cell| cell.set(depth + 1));
let result = BODY_RETURN_INFERRER.with(|cell| {
let borrow = cell.borrow();
let inferrer = borrow.as_ref()?;
let inferred = inferrer(class_fqn, method);
// Filter out `mixed` and `void` — these are not useful as
// inferred return types for completion/hover.
inferred.filter(|t| !t.is_mixed() && !t.is_void())
});
// Restore depth and remove from visited set so the same method
// can be inferred again from a different call chain.
BODY_INFER_DEPTH.with(|cell| cell.set(depth));
BODY_INFER_VISITED.with(|cell| {
cell.borrow_mut().remove(&key);
});
result
}
impl Backend {
/// Build and activate the thread-local body return type inferrer.
///
/// Returns an RAII guard that deactivates the inferrer on drop.
/// Call this at the start of completion, hover, and diagnostic
/// request handlers so that methods without declared return types
/// can have their return type inferred from the method body.
///
/// Internally clones the `Backend` (all fields are `Arc`-wrapped,
/// so this is cheap) and delegates to
/// [`Backend::infer_return_type_for_function`] which has the full
/// resolution infrastructure (use maps, namespace resolution,
/// function loader, class loader with stubs/class index/PSR-4).
pub(crate) fn activate_body_return_inferrer(&self) -> BodyReturnInferrerGuard {
let backend = self.clone_for_diagnostic_worker();
let inferrer = move |class_fqn: &str, method: &MethodInfo| -> Option<PhpType> {
// Find the file URI for this class.
let file_uri = backend.fqn_uri_index.read().get(class_fqn).cloned()?;
// Read the file content.
let content = backend.get_file_content(&file_uri)?;
// Convert method name_offset to a 0-based line number.
let offset = method.name_offset as usize;
if offset >= content.len() {
return None;
}
let func_line = content[..offset].matches('\n').count();
// Walk backwards from the method name to find the function
// keyword line (the declaration may start on an earlier line).
// infer_return_type_for_function expects the line of the
// `function` keyword.
let lines: Vec<&str> = content.lines().collect();
let mut decl_line = func_line;
for i in (0..=func_line).rev() {
let trimmed = lines.get(i).map(|l| l.trim()).unwrap_or("");
if trimmed.contains("function ")
|| trimmed.contains("function(")
|| trimmed.starts_with("function")
{
decl_line = i;
break;
}
if trimmed.ends_with('}') || trimmed.ends_with(';') {
break;
}
}
let result = backend.infer_return_type_for_function(&file_uri, &content, decl_line)?;
// Prefer the effective type (richer, e.g. `list<string>`)
// over the native type (e.g. `array`).
Some(result.effective.unwrap_or(result.native))
};
with_body_return_inferrer(Box::new(inferrer))
}
/// Resolve an instance method base expression + method name to a
/// [`ResolvedCallableTarget`].
///
/// Resolves `base` to owner classes, merges each via
/// `resolve_class_fully_with_generics`, and returns the first match
/// for `method_name`.
fn resolve_instance_method_callable(
base: &SubjectExpr,
method_name: &str,
rctx: &ResolutionCtx<'_>,
args_text: Option<&str>,
) -> Option<ResolvedCallableTarget> {
let subject_text = base.to_subject_text();
let resolved_types: Vec<ResolvedType> = if base.is_self_like() {
rctx.current_class
.map(|c| ResolvedType::from_class(c.clone()))
.into_iter()
.collect()
} else {
super::resolver::resolve_target_classes(&subject_text, crate::AccessKind::Arrow, rctx)
};
for rt in &resolved_types {
let owner = match &rt.class_info {
Some(ci) => Arc::clone(ci),
None => continue,
};
// Extract generic type arguments from the resolved type
// string (e.g. `Collection<User>` → `[User]`) so we can
// substitute class-level template parameters in the
// method's parameter and return types.
let generic_args: Vec<PhpType> = match &rt.type_string {
PhpType::Generic(_, args) => args.clone(),
_ => {
// When the resolved type has no generic annotation
// but the class declares template parameters (e.g.
// `$errors = new Collection()` without `<string>`),
// fill in default type args from declared upper
// bounds or `mixed`. This follows PHPStan's
// `resolveToBounds()` semantics and prevents raw
// template names like `TValue` from leaking into
// method parameter and return types.
if !owner.template_params.is_empty() {
crate::inheritance::default_type_args(&owner)
} else {
vec![]
}
}
};
// ── Callable target cache check ─────────────────────────
// When args_text is None (argument_count diagnostics),
// the callable target depends only on the resolved class
// and method name, not on the specific chain expression.
// Cache by "FQN::method_lower" so that `$q->where(...)`,
// `$query->where(...)`, and `Product::query()->where(...)`
// all share the result.
//
// When args_text is Some (type_error diagnostics with
// method-level template substitution), the result depends
// on the call-site arguments and cannot be cached this way.
let method_lower = method_name.to_ascii_lowercase();
let generic_arg_strings: Vec<String> =
generic_args.iter().map(|a| a.to_string()).collect();
let callable_cache_key = if args_text.is_none() {
let fqn = owner.fqn();
let key_str = if generic_arg_strings.is_empty() {
format!("{}::{}", fqn, method_lower)
} else {
format!(
"{}<{}>::{}",
fqn,
generic_arg_strings.join(","),
method_lower
)
};
Some(key_str)
} else {
None
};
if let Some(ref key) = callable_cache_key {
let cached = CALLABLE_TARGET_CACHE.with(|cell| {
let borrow = cell.borrow();
borrow.as_ref().and_then(|map| map.get(key).cloned())
});
match cached {
Some(Some(target)) => return Some(target),
Some(None) => continue,
None => {}
}
}
// Always use a fully-resolved class so that inherited
// docblock types (return types, parameter types,
// descriptions) are visible in signature help. The
// candidate from `resolve_target_classes` may not have
// gone through `resolve_class_fully` (e.g. bare `new X`
// instantiation without generics).
//
// Use the fused resolve+substitute helper so that the
// result of `apply_generic_args` is cached under
// `(FQN, generic_args)`. For Eloquent Builder<Model>
// chains where the same generic class appears at dozens
// of call sites, this avoids re-cloning and
// re-substituting hundreds of virtual members each time.
let effective = crate::virtual_members::resolve_class_fully_with_generics(
&owner,
rctx.class_loader,
rctx.resolved_class_cache,
&generic_arg_strings,
&generic_args,
);
if let Some(m) = effective.get_method_ci(&method_lower) {
let mut result_method = m.clone();
// Apply method-level template substitutions when
// call-site argument text is available.
if let Some(at) = args_text {
let split_args = crate::completion::types::conditional::split_text_args(at);
let method_subs = Self::build_method_template_subs(
&effective,
method_name,
&split_args,
rctx,
);
if !method_subs.is_empty() {
crate::inheritance::apply_substitution_to_method(
&mut result_method,
&method_subs,
);
}
}
let target = ResolvedCallableTarget {
parameters: result_method.parameters.clone(),
return_type: result_method.return_type.clone(),
..Default::default()
};
// Store positive result in the callable target cache.
if let Some(ref key) = callable_cache_key {
CALLABLE_TARGET_CACHE.with(|cell| {
let mut borrow = cell.borrow_mut();
if let Some(ref mut map) = *borrow {
map.insert(key.clone(), Some(target.clone()));
}
});
}
return Some(target);
}
// Fall back to __call / __callStatic — the candidate
// directly may contain model-specific members (e.g.
// Eloquent scope methods injected onto Builder<Model>)
// that the FQN-keyed cache does not have.
if let Some(m) = owner.get_method_ci(method_name) {
let target = ResolvedCallableTarget {
parameters: m.parameters.clone(),
return_type: m.return_type.clone(),
..Default::default()
};
// Store __call fallback in the callable target cache.
if let Some(ref key) = callable_cache_key {
CALLABLE_TARGET_CACHE.with(|cell| {
let mut borrow = cell.borrow_mut();
if let Some(ref mut map) = *borrow {
map.insert(key.clone(), Some(target.clone()));
}
});
}
return Some(target);
}
// Store negative result (method not found) in the cache.
if let Some(ref key) = callable_cache_key {
CALLABLE_TARGET_CACHE.with(|cell| {
let mut borrow = cell.borrow_mut();
if let Some(ref mut map) = *borrow {
map.insert(key.clone(), None);
}
});
}
}
None
}
/// Resolve a static class reference + method name to a
/// [`ResolvedCallableTarget`].
///
/// Resolves the class via [`super::resolver::resolve_static_owner_class`], merges
/// via `resolve_class_fully`, and looks up `method_name`.
fn resolve_static_method_callable(
class: &str,
method_name: &str,
rctx: &ResolutionCtx<'_>,
args_text: Option<&str>,
) -> Option<ResolvedCallableTarget> {
let owner = super::resolver::resolve_static_owner_class(class, rctx)?;
// When the class has template params, try to substitute them with
// concrete types. For `parent::` calls, use the child's @extends
// generics to get the concrete type arguments. Otherwise fall back
// to upper bounds / `mixed`.
let merged = if !owner.template_params.is_empty() {
let type_args = if class.eq_ignore_ascii_case("parent") {
// Look up the child's extends_generics for the parent class
rctx.current_class.and_then(|child| {
let parent_short = crate::util::short_name(&owner.name);
child
.extends_generics
.iter()
.find(|(name, _)| crate::util::short_name(name) == parent_short)
.map(|(_, args)| args.clone())
})
} else {
None
};
let args = type_args.unwrap_or_else(|| crate::inheritance::default_type_args(&owner));
crate::virtual_members::resolve_class_fully_with_type_args(
&owner,
rctx.class_loader,
rctx.resolved_class_cache,
&args,
)
} else {
crate::virtual_members::resolve_class_fully_maybe_cached(
&owner,
rctx.class_loader,
rctx.resolved_class_cache,
)
};
let m = merged.get_method_ci(method_name)?;
let mut result_method = m.clone();
// Apply method-level template substitutions when call-site
// argument text is available.
if let Some(at) = args_text {
let split_args = crate::completion::types::conditional::split_text_args(at);
let method_subs =
Self::build_method_template_subs(&merged, method_name, &split_args, rctx);
if !method_subs.is_empty() {
crate::inheritance::apply_substitution_to_method(&mut result_method, &method_subs);
}
}
Some(ResolvedCallableTarget {
parameters: result_method.parameters.clone(),
return_type: result_method.return_type.clone(),
..Default::default()
})
}
/// Build a [`ResolvedCallableTarget`] from a resolved [`FunctionInfo`].
fn function_to_callable(func: &FunctionInfo) -> ResolvedCallableTarget {
ResolvedCallableTarget {
parameters: func.parameters.clone(),
return_type: func.return_type.clone(),
..Default::default()
}
}
/// Like [`Self::function_to_callable`] but resolves function-level
/// `@template` parameters from call-site argument text before
/// building the callable target. Without this, functions like
/// `throw_unless($cond)` would report `expects TValue` instead of
/// the concrete type.
fn function_to_callable_with_subs(
func: &FunctionInfo,
args_text: Option<&str>,
rctx: &ResolutionCtx<'_>,
) -> ResolvedCallableTarget {
if let Some(at) = args_text
&& !func.template_params.is_empty()
{
let split_args: Vec<String> =
crate::completion::types::conditional::split_text_args(at)
.into_iter()
.map(|s| s.to_string())
.collect();
let subs = crate::completion::variable::rhs_resolution::build_function_template_subs(
func,
&split_args,
rctx,
);
if !subs.is_empty() {
let parameters: Vec<_> = func
.parameters
.iter()
.map(|p| {
let mut param = p.clone();
if let Some(ref mut hint) = param.type_hint {
*hint = hint.substitute(&subs);
}
param
})
.collect();
return ResolvedCallableTarget {
parameters,
return_type: func.return_type.clone(),
..Default::default()
};
}
}
Self::function_to_callable(func)
}
/// Resolve class name keywords (`self`, `static`, `parent`) to actual
/// class names in the context of the current class.
fn resolve_class_name_keyword(class_name: &str, current_class: Option<&ClassInfo>) -> String {
resolve_class_keyword(class_name, current_class).unwrap_or_else(|| class_name.to_string())
}
/// Build a [`ResolvedCallableTarget`] for a constructor call.
///
/// Loads and merges the class, then extracts `__construct` parameters.
/// When `args_text` is provided, class-level `@template` parameters are
/// resolved from the call-site argument types and substituted into the
/// constructor's parameter types.
///
/// For example, given `/** @template T */ class Box { /** @param T $value */ … }`,
/// calling `new Box(new Gift())` resolves `T` → `Gift` and substitutes it
/// into the constructor parameters so that type-error diagnostics see
/// `Gift` instead of the raw `T`.
fn resolve_constructor_callable(
class_name: &str,
class_loader: &dyn Fn(&str) -> Option<Arc<ClassInfo>>,
cache: &crate::virtual_members::ResolvedClassCache,
args_text: Option<&str>,
rctx: &ResolutionCtx<'_>,
) -> Option<ResolvedCallableTarget> {
let ci = class_loader(class_name)?;
let merged = crate::virtual_members::resolve_class_fully_cached(&ci, class_loader, cache);
let ctor = match merged.get_method("__construct") {
Some(c) => c.clone(),
// A class with no constructor (and none inherited) accepts any
// arguments without error: PHP silently ignores them. Mark the
// target so the argument-count diagnostic skips it, while
// signature help still shows the empty `()` signature.
None => {
return Some(ResolvedCallableTarget {
parameters: vec![],
return_type: None,
accepts_any_args: true,
});
}
};
// Apply class-level template substitutions from the call-site
// argument types when the constructor has template bindings.
if let Some(at) = args_text
&& !ctor.template_bindings.is_empty()
{
let split_args = crate::completion::types::conditional::split_text_args(at);
let subs = Self::build_method_template_subs(&merged, "__construct", &split_args, rctx);
if !subs.is_empty() {
let mut result_ctor = ctor;
crate::inheritance::apply_substitution_to_method(&mut result_ctor, &subs);
return Some(ResolvedCallableTarget {
parameters: result_ctor.parameters.clone(),
return_type: result_ctor.return_type.clone(),
..Default::default()
});
}
}
Some(ResolvedCallableTarget {
parameters: ctor.parameters.clone(),
return_type: ctor.return_type.clone(),
..Default::default()
})
}
// ── Main callable target resolution ─────────────────────────────────
/// Resolve a call expression string to the callable's owner class and
/// method (or standalone function), returning a
/// [`ResolvedCallableTarget`] with the label, parameters, and return
/// type.
///
/// This is the single shared implementation used by both signature
/// help (`resolve_callable`) and named-argument completion
/// (`resolve_named_arg_params`). Each caller projects the fields it
/// needs from the result.
///
/// The `expr` parameter uses the same format as the symbol map's
/// `CallSite::call_expression`:
/// - `"functionName"` for standalone function calls
/// - `"$subject->method"` for instance/null-safe method calls
/// - `"ClassName::method"` for static method calls
/// - `"new ClassName"` for constructor calls
pub(crate) fn resolve_callable_target(
&self,
expr: &str,
content: &str,
position: Position,
file_ctx: &FileContext,
) -> Option<ResolvedCallableTarget> {
self.resolve_callable_target_with_args(expr, content, position, file_ctx, None)
}
/// Like [`resolve_callable_target`](Self::resolve_callable_target)
/// but accepts optional raw argument text for method-level template
/// substitution.
///
/// When `call_args_text` is `Some("$user, 42")`, method-level
/// `@template` parameters are resolved from the call-site argument
/// types and substituted into the parameter types before returning.
pub(crate) fn resolve_callable_target_with_args(
&self,
expr: &str,
content: &str,
position: Position,
file_ctx: &FileContext,
call_args_text: Option<&str>,
) -> Option<ResolvedCallableTarget> {
let class_loader = self.class_loader(file_ctx);
let function_loader_cl = self.function_loader(file_ctx);
let cursor_offset = position_to_offset(content, position);
let current_class = find_class_at_offset(&file_ctx.classes, cursor_offset);
let rctx = ResolutionCtx {
current_class,
all_classes: &file_ctx.classes,
content,
cursor_offset,
class_loader: &class_loader,
resolved_class_cache: Some(&self.resolved_class_cache),
function_loader: Some(&function_loader_cl),
scope_var_resolver: None,
is_in_static_method: false,
};
let parsed = SubjectExpr::parse(expr);
// Unwrap `CallExpr` wrapper so downstream arms match the inner
// callee directly. Capture `args_text` from the parsed
// expression; prefer the caller-supplied `call_args_text` when
// available (it comes from the source content and is more
// accurate for method-level template substitution).
let (effective, args_text_from_parse) = match &parsed {
SubjectExpr::CallExpr { callee, args_text } => {
(callee.as_ref(), Some(args_text.as_str()))
}
other => (other, None),
};
let effective_args_text = call_args_text.or(args_text_from_parse);
match effective {
// ── Constructor: `new ClassName` or `new ClassName()` ────
SubjectExpr::NewExpr { class_name } => {
let resolved_class_name =
Self::resolve_class_name_keyword(class_name, rctx.current_class);
Self::resolve_constructor_callable(
&resolved_class_name,
&class_loader,
&self.resolved_class_cache,
effective_args_text,
&rctx,
)
}
// ── Instance method call: `$subject->method(…)` ─────────
SubjectExpr::MethodCall { base, method } => {
Self::resolve_instance_method_callable(base, method, &rctx, effective_args_text)
}
// ── Static method call: `Class::method(…)` ──────────────
SubjectExpr::StaticMethodCall { class, method } => {
Self::resolve_static_method_callable(class, method, &rctx, effective_args_text)
}
// ── Standalone function call: `functionName(…)` ─────────
SubjectExpr::FunctionCall(name) => {
let func =
self.resolve_function_name(name, &file_ctx.use_map, &file_ctx.namespace)?;
Some(Self::function_to_callable_with_subs(
&func,
effective_args_text,
&rctx,
))
}
// ── Variable used as a callable target: `$fn(…)` ────────
// Check for a first-class callable assignment and recurse.
SubjectExpr::Variable(var_name) => {
let callable_target =
Self::extract_callable_target_from_variable(var_name, content, cursor_offset)?;
self.resolve_callable_target_with_args(
&callable_target,
content,
position,
file_ctx,
call_args_text,
)
}
// ── Bare class name used as a function name ─────────────
// Named-arg and signature-help contexts pass bare function
// names like `"foo"` which `SubjectExpr::parse` produces
// as `ClassName` (since it can't distinguish class names
// from function names without context).
SubjectExpr::ClassName(name) => {
let func =
self.resolve_function_name(name, &file_ctx.use_map, &file_ctx.namespace)?;
Some(Self::function_to_callable_with_subs(
&func,
effective_args_text,
&rctx,
))
}
// ── PropertyChain used as a callable target ──────────────
// Named-arg and signature-help contexts pass expressions
// like `"$this->method"` (without trailing `()`), which
// `SubjectExpr::parse` produces as `PropertyChain`. Treat
// the trailing property as a method name.
SubjectExpr::PropertyChain { base, property } => {
Self::resolve_instance_method_callable(base, property, &rctx, effective_args_text)
}
// ── StaticAccess used as a callable target ──────────────
// Same situation: `"ClassName::method"` without `()` parses
// as `StaticAccess` rather than `StaticMethodCall`.
SubjectExpr::StaticAccess { class, member } => {
Self::resolve_static_method_callable(class, member, &rctx, effective_args_text)
}
// ── Anything else doesn't resolve to a callable ─────────
_ => None,
}
}
/// Resolve the return type of a call expression given a structured
/// [`SubjectExpr`] callee and argument text, returning zero or more
/// `ClassInfo` values.
///
/// This is the primary entry point for call return type resolution.
/// The callee should be one of the "callee" variants produced by
/// `parse_callee`: [`SubjectExpr::MethodCall`],
/// [`SubjectExpr::StaticMethodCall`], [`SubjectExpr::FunctionCall`],
/// [`SubjectExpr::Variable`], or [`SubjectExpr::NewExpr`].
/// Any other variant falls through to `resolve_target_classes_expr`.
///
/// Resolves the return type of a structured [`SubjectExpr`] callee +
/// argument text. Optionally captures the raw return type hint
/// (with template substitutions applied) into `return_type_hint_out`
/// when provided. This preserves generic
/// type parameters (e.g. `HasMany<Translation, Tag>`) that would
/// otherwise be lost when converting to `Vec<Arc<ClassInfo>>`.
pub(crate) fn resolve_call_return_types_expr_with_hint(
callee: &SubjectExpr,
text_args: &str,
ctx: &ResolutionCtx<'_>,
mut return_type_hint_out: Option<&mut Option<PhpType>>,
) -> Vec<Arc<ClassInfo>> {
match callee {
// ── Instance method call: base->method(…) ───────────────
SubjectExpr::MethodCall { base, method } => {
let method_name = method.as_str();
// Resolve the base expression preserving generic type
// arguments (e.g. `Collection<Product>`) so class-level
// template parameters can be substituted in the method's
// return type.
let lhs_resolved: Vec<ResolvedType> =
super::resolver::resolve_target_classes_expr(base, AccessKind::Arrow, ctx);
// Capture the raw return type hint while we iterate
// the owner classes below. We grab it from the first
// owner that has a matching method — before the return
// type gets flattened into ClassInfo.
let mut hint_captured = false;
let mut results = Vec::new();
for rt in &lhs_resolved {
let owner = match &rt.class_info {
Some(ci) => Arc::clone(ci),
None => continue,
};
// Extract class-level generic type arguments from the
// resolved type string (e.g. `Collection<Product>` →
// `[Product]`) so we can substitute class-level
// template parameters (e.g. `TItem → Product`).
// Skip self-like args ($this, self, static) because
// they refer to the caller's class context which is
// not available here.
let class_level_subs: HashMap<String, PhpType> = match &rt.type_string {
PhpType::Generic(_, args)
if !args.is_empty()
&& !owner.template_params.is_empty()
&& !args.iter().any(|a| a.is_self_like()) =>
{
owner
.template_params
.iter()
.zip(args.iter())
.map(|(name, ty)| (name.to_string(), ty.clone()))
.collect()
}
_ => HashMap::new(),
};
let split_args = split_text_args(text_args);
let arg_refs = split_args.to_vec();
let method_subs =
Self::build_method_template_subs(&owner, method_name, &arg_refs, ctx);
// Merge class-level generic substitutions with
// method-level template substitutions. Class-level
// subs map e.g. `TItem → Product`; method-level subs
// map method @template params from call-site args.
// Method-level subs take precedence (inserted last).
let mut template_subs = class_level_subs;
template_subs.extend(method_subs);
// Capture the return type hint from the first owner
// that has the method. Apply template substitutions
// so that generic return types like `T` are resolved
// to their concrete types (e.g. `Product`). Without
// this, callers that use the hint for downstream
// template binding would see unsubstituted params.
if !hint_captured && let Some(ref mut hint_out) = return_type_hint_out {
let merged = crate::virtual_members::resolve_class_fully_maybe_cached(
&owner,
ctx.class_loader,
ctx.resolved_class_cache,
);
if let Some(m) = merged.get_method_ci(method_name) {
if let Some(ref ret) = m.return_type {
let substituted = if !template_subs.is_empty() {
ret.substitute(&template_subs)
} else {
ret.clone()
};
// Resolve self/static/parent keywords to
// concrete class names so that downstream
// consumers see real FQNs, not keywords.
let resolved_hint = if substituted.is_parent_ref() {
owner
.parent_class
.as_ref()
.map(|p| PhpType::Named(p.to_string()))
.unwrap_or(substituted)
} else if substituted.is_self_like() {
PhpType::Named(owner.fqn().to_string())
} else {
substituted
};
**hint_out = Some(resolved_hint);
}
hint_captured = true;