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
use super::*;
impl<'a> BodyAnalyzer<'a> {
#[allow(clippy::too_many_arguments)]
pub(crate) fn analyze_fn_decl(
&self,
decl: &php_ast::owned::FunctionDecl,
file: &Arc<str>,
source: &str,
source_map: &php_rs_parser::source_map::SourceMap,
all_issues: &mut Vec<Issue>,
all_symbols: &mut Vec<ResolvedSymbol>,
) {
crate::attributes::check_function_attributes(
decl,
self.db,
file,
source,
source_map,
all_issues,
self.mode == AnalysisMode::Full,
Some(&mut *all_symbols),
);
let fn_name = decl.name.as_deref().unwrap_or("").to_string();
for param in decl.params.iter() {
if let Some(hint) = ¶m.type_hint {
self.check_and_record_type_hint_classes(
hint,
file,
source,
source_map,
all_issues,
Some(&mut *all_symbols),
);
}
// Defaults are fully analyzed below (the expression analyzer
// emits UndefinedClass itself and records references).
}
if let Some(hint) = &decl.return_type {
self.check_and_record_type_hint_classes(
hint,
file,
source,
source_map,
all_issues,
Some(&mut *all_symbols),
);
}
use crate::flow_state::FlowState;
use crate::stmt::StatementsAnalyzer;
use mir_issues::IssueBuffer;
let resolved = lookup_function_node_for_decl(self.db, file.as_ref(), &fn_name);
let fqn = resolved.as_ref().map(|(f, _)| f.clone());
#[allow(clippy::type_complexity)]
let (params, return_ty, template_params, declared_throws): (
Arc<[mir_codebase::DeclaredParam]>,
_,
Vec<_>,
Arc<[Arc<str>]>,
) = match &resolved {
Some((_, storage)) => {
if storage.params.len() == decl.params.len()
&& storage
.params
.iter()
.zip(decl.params.iter())
.all(|(cp, ap)| ap.name.as_deref().unwrap_or("") == cp.name.as_ref())
{
(
Arc::clone(&storage.params),
storage.return_type.as_deref().cloned(),
storage.template_params.clone(),
Arc::from(storage.throws.as_slice()),
)
} else {
(
Arc::from(ast_derived_fn_params(&decl.params)),
None,
vec![],
Arc::from([]),
)
}
}
None => (
Arc::from(ast_derived_fn_params(&decl.params)),
None,
vec![],
Arc::from([]),
),
};
if self.mode == AnalysisMode::Full {
self.emit_missing_fn_types(
decl,
resolved.as_ref().map(|(_, s)| s),
file,
source,
source_map,
all_issues,
);
}
self.check_and_record_throws_classes(
&declared_throws,
fn_header_name_span(source, decl),
file,
source,
source_map,
all_issues,
);
// A docblock @return that conflicts with the native hint must not
// make the function's own valid `return` statements look invalid —
// the native hint is runtime truth. This only affects body-statement
// checking below; the MismatchingDocblockReturnType check further
// down in this function still compares against the raw, unfiltered
// docblock value (via `stored`, independent of `return_ty`).
let return_ty = super::return_ty_for_body_check(
self.db,
file.as_ref(),
return_ty,
decl.return_type.as_ref(),
None,
);
let declared_return = return_ty.clone();
let mut ctx = FlowState::for_method_with_templates(
¶ms,
return_ty,
declared_throws,
None,
None,
None,
crate::body_analysis::is_strict_types_file(source),
false,
true,
Some(&template_params),
);
ctx.is_in_pure_fn = resolved.as_ref().map(|(_, s)| s.is_pure).unwrap_or(false);
// A free function has no `$this`, so `@mutation-free` has nothing to
// exempt — its only meaningful half is exactly `@external-mutation-
// free`'s "don't mutate a parameter" constraint. Reuse the existing
// (method-shaped) flag rather than introduce a function-specific one:
// its own gate (`recv_stripped != "this" && recv is a param`) already
// does the right thing here, since a free function's receiver is
// never literally `"this"`. `@pure` already covers this case via its
// own, separate `is_in_pure_fn` check above.
ctx.is_in_external_mutation_free_method = resolved
.as_ref()
.is_some_and(|(_, s)| s.is_mutation_free || s.is_external_mutation_free);
ctx.current_function_fqn = fqn.clone();
seed_param_locations(&mut ctx, &decl.params, source, source_map);
record_param_symbols(all_symbols, file, source, &decl.params, &ctx);
let mut buf = IssueBuffer::new();
let mut sa = StatementsAnalyzer::new(
self.db,
file.clone(),
source,
source_map,
&mut buf,
all_symbols,
self.php_version,
self.mode,
);
sa.collect_symbols = self.collect_symbols;
// Parameter defaults are constant expressions outside the body flow;
// analyze them (mirroring the class-method path) so `Cfg::MODE`-style
// defaults record references.
if self.mode == AnalysisMode::Full {
let mut default_ctx = FlowState::new();
default_ctx.strict_types = ctx.strict_types;
for p in decl.params.iter() {
if let Some(default) = &p.default {
let mut ea = sa.expr_analyzer(&default_ctx);
let _ = ea.analyze(default, &mut default_ctx);
}
}
}
ctx.is_generator = body_has_yield(&decl.body.stmts);
sa.analyze_stmts(&decl.body.stmts, &mut ctx);
let inferred = merge_return_types(&sa.return_types, ctx.diverges);
let inferred = if sa.yielded_types.is_empty() {
inferred
} else {
build_generator_return_type(&sa.yielded_types, inferred)
};
let body_diverges = ctx.diverges;
drop(sa);
emit_unused_params(¶ms, &ctx, "", file, all_issues);
emit_unused_variables(&ctx, file, all_issues);
all_issues.extend(buf.into_all_issues());
if self.mode == AnalysisMode::Full && !ctx.is_generator {
crate::diagnostics::check_missing_return(
declared_return.as_ref(),
body_diverges,
&decl.body.span,
file,
source,
source_map,
all_issues,
);
}
if let Some(fqn) = fqn {
self.record_function_inference(&fqn, &inferred);
}
}
/// Missing type declarations (Psalm parity): a top-level function with
/// neither a native hint nor a docblock type. `stored` carries the
/// docblock-resolved types, so absent there + absent in the AST = missing.
fn emit_missing_fn_types(
&self,
decl: &php_ast::owned::FunctionDecl,
stored: Option<&Arc<mir_codebase::definitions::FunctionDef>>,
file: &Arc<str>,
source: &str,
source_map: &php_rs_parser::source_map::SourceMap,
issues: &mut Vec<Issue>,
) {
let fn_name = decl.name.as_deref().unwrap_or("");
let stored_params_match = stored.is_some_and(|s| s.params.len() == decl.params.len());
if decl.return_type.is_none()
&& stored.is_none_or(|s| s.return_type.is_none())
&& !fn_name.is_empty()
{
let span = fn_header_name_span(source, decl);
let (line, col_start) =
crate::diagnostics::offset_to_line_col(source, span.start, source_map);
let (line_end, col_end) =
crate::diagnostics::offset_to_line_col(source, span.end, source_map);
issues.push(mir_issues::Issue::new(
mir_issues::IssueKind::MissingReturnType {
fn_name: fn_name.to_string(),
},
mir_issues::Location {
file: file.clone(),
line,
line_end,
col_start,
col_end: crate::diagnostics::clamp_col_end(line, line_end, col_start, col_end),
},
));
}
for (i, ast_param) in decl.params.iter().enumerate() {
let stored_ty_present = stored_params_match
&& stored.is_some_and(|s| s.params.get(i).is_some_and(|p| p.ty.is_some()));
if ast_param.type_hint.is_none() && !stored_ty_present {
let param_name = ast_param
.name
.as_deref()
.unwrap_or("")
.trim_start_matches('$')
.to_string();
let span = param_name_span(source, ast_param);
let (line, col_start) =
crate::diagnostics::offset_to_line_col(source, span.start, source_map);
let (line_end, col_end) =
crate::diagnostics::offset_to_line_col(source, span.end, source_map);
issues.push(mir_issues::Issue::new(
mir_issues::IssueKind::MissingParamType {
fn_name: fn_name.to_string(),
param: param_name,
},
mir_issues::Location {
file: file.clone(),
line,
line_end,
col_start,
col_end: crate::diagnostics::clamp_col_end(
line, line_end, col_start, col_end,
),
},
));
}
}
// Docblock signature mismatches (Psalm parity): a docblock type that
// contradicts the native hint. The stored type is the docblock-resolved
// one (collector prefers docblock and marks `from_docblock`); the hint
// is converted and namespace-resolved here for the comparison.
let Some(stored) = stored else { return };
let template_names: Vec<&str> = stored
.template_params
.iter()
.map(|tp| tp.name.as_ref())
.collect();
if let (Some(hint), Some(doc_ty)) = (&decl.return_type, stored.return_type.as_deref()) {
if doc_ty.from_docblock
&& !docblock_type_unresolvable(doc_ty, &template_names)
&& !fn_name.is_empty()
{
let hint_ty = crate::expr::helpers::resolve_named_objects_in_union(
crate::parser::type_from_hint_owned(hint, None),
self.db,
file.as_ref(),
);
if !hint_ty.is_mixed()
&& !doc_ty.is_mixed()
&& docblock_conflicts_with_hint(self.db, doc_ty, &hint_ty)
{
let span = fn_header_name_span(source, decl);
let (line, col_start) =
crate::diagnostics::offset_to_line_col(source, span.start, source_map);
let (line_end, col_end) =
crate::diagnostics::offset_to_line_col(source, span.end, source_map);
issues.push(mir_issues::Issue::new(
mir_issues::IssueKind::MismatchingDocblockReturnType {
declared: doc_ty.to_string(),
inferred: hint_ty.to_string(),
},
mir_issues::Location {
file: file.clone(),
line,
line_end,
col_start,
col_end: crate::diagnostics::clamp_col_end(
line, line_end, col_start, col_end,
),
},
));
}
}
}
// UndefinedDocblockClass: docblock @return type references a non-existent class.
if let Some(doc_ty) = stored.return_type.as_deref().filter(|t| t.from_docblock) {
let span = fn_header_name_span(source, decl);
let (line, col_start) =
crate::diagnostics::offset_to_line_col(source, span.start, source_map);
let (line_end, col_end) =
crate::diagnostics::offset_to_line_col(source, span.end, source_map);
// Recurse into type-argument lists, array/list element+key types, and
// intersections — not just the top-level atomic — so `Foo[]`,
// `array<int, Foo>`, `list<Foo>`, and `Foo&Bar` all get their
// member classes existence-checked and reference-recorded too.
let mut fqcns = Vec::new();
super::classes::collect_named_object_fqcns_with_arity(doc_ty, &mut fqcns);
for (fqcn, arity) in &fqcns {
if template_names.iter().any(|t| *t == fqcn.as_ref()) {
continue;
}
if !crate::db::class_exists(self.db, fqcn.as_ref()) {
issues.push(mir_issues::Issue::new(
mir_issues::IssueKind::UndefinedDocblockClass {
name: fqcn.to_string(),
},
mir_issues::Location {
file: file.clone(),
line,
line_end,
col_start,
col_end: crate::diagnostics::clamp_col_end(
line, line_end, col_start, col_end,
),
},
));
} else {
if self.mode == AnalysisMode::Full {
self.db.record_reference_location(crate::db::RefLoc {
symbol_key: Arc::from(format!("cls:{fqcn}")),
file: file.clone(),
line,
col_start,
col_end: crate::diagnostics::clamp_col_end(
line, line_end, col_start, col_end,
),
});
}
if let Some(message) =
super::classes::check_generic_arity(self.db, fqcn, *arity)
{
issues.push(mir_issues::Issue::new(
mir_issues::IssueKind::InvalidDocblock { message },
mir_issues::Location {
file: file.clone(),
line,
line_end,
col_start,
col_end: crate::diagnostics::clamp_col_end(
line, line_end, col_start, col_end,
),
},
));
}
}
}
}
// Param docblock types are not flagged `from_docblock` in storage, so
// re-parse the doc comment to know which params have a docblock type.
let doc = decl
.doc_comment
.as_ref()
.map(|c| crate::parser::DocblockParser::parse(&c.text))
.unwrap_or_default();
{
for ast_param in decl.params.iter() {
let raw_name = ast_param.name.as_deref().unwrap_or_default();
let (Some(hint), Some(doc_raw)) =
(&ast_param.type_hint, doc.get_param_type(raw_name))
else {
continue;
};
let doc_ty = crate::expr::helpers::resolve_named_objects_in_union(
doc_raw.clone(),
self.db,
file.as_ref(),
);
if docblock_type_unresolvable(&doc_ty, &template_names) {
continue;
}
let hint_ty = crate::expr::helpers::resolve_named_objects_in_union(
crate::parser::type_from_hint_owned(hint, None),
self.db,
file.as_ref(),
);
if hint_ty.is_mixed()
|| doc_ty.is_mixed()
|| !docblock_conflicts_with_hint(self.db, &doc_ty, &hint_ty)
{
continue;
}
let param_name = ast_param
.name
.as_deref()
.unwrap_or("")
.trim_start_matches('$')
.to_string();
let span = param_name_span(source, ast_param);
let (line, col_start) =
crate::diagnostics::offset_to_line_col(source, span.start, source_map);
let (line_end, col_end) =
crate::diagnostics::offset_to_line_col(source, span.end, source_map);
issues.push(mir_issues::Issue::new(
mir_issues::IssueKind::MismatchingDocblockParamType {
param: param_name,
declared: doc_ty.to_string(),
inferred: hint_ty.to_string(),
},
mir_issues::Location {
file: file.clone(),
line,
line_end,
col_start,
col_end: crate::diagnostics::clamp_col_end(
line, line_end, col_start, col_end,
),
},
));
}
}
// UndefinedDocblockClass: @param docblock references a non-existent class.
// Runs separately from the MismatchingDocblockParamType loop because that
// loop requires both a native hint and a docblock type, while this check
// only needs a docblock type.
{
let fn_span = fn_header_name_span(source, decl);
let (fn_line, fn_col_start) =
crate::diagnostics::offset_to_line_col(source, fn_span.start, source_map);
let (fn_line_end, fn_col_end) =
crate::diagnostics::offset_to_line_col(source, fn_span.end, source_map);
// Type alias names defined on this function (@psalm-type / @psalm-import-type).
// These are not class names and must not be flagged as UndefinedDocblockClass.
let type_alias_names: rustc_hash::FxHashSet<&str> = doc
.type_aliases
.iter()
.map(|a| a.name.as_str())
.chain(doc.import_types.iter().map(|i| i.local.as_str()))
.collect();
for ast_param in decl.params.iter() {
let raw_name = ast_param.name.as_deref().unwrap_or_default();
let Some(doc_raw) = doc.get_param_type(raw_name) else {
continue;
};
let doc_ty = crate::expr::helpers::resolve_named_objects_in_union(
doc_raw.clone(),
self.db,
file.as_ref(),
);
// Recurse into type-argument lists, array/list element+key types,
// and intersections — not just the top-level atomic — so
// `Foo[]`, `array<int, Foo>`, `list<Foo>`, and `Foo&Bar` all get
// their member classes existence-checked and reference-recorded.
let mut fqcns = Vec::new();
super::classes::collect_named_object_fqcns_with_arity(&doc_ty, &mut fqcns);
for (fqcn, arity) in &fqcns {
// Skip pseudo-types (non-falsy-string), callables (pure-callable(…)),
// class-constants (Ns\C::A), float-literals (0.3), and namespace-resolved
// template params (App\T where T is a declared template).
let looks_like_class = !fqcn.contains('-')
&& !fqcn.contains('(')
&& !fqcn.contains("::")
&& !fqcn.contains('.')
&& !fqcn.starts_with(|c: char| c.is_ascii_digit());
let last_segment = fqcn.rsplit('\\').next().unwrap_or(fqcn.as_ref());
let is_template = template_names
.iter()
.any(|t| *t == fqcn.as_ref() || *t == last_segment);
let is_alias = type_alias_names.contains(last_segment)
|| type_alias_names.contains(fqcn.as_ref());
if !looks_like_class || is_template || is_alias {
continue;
}
if !crate::db::class_exists(self.db, fqcn.as_ref()) {
issues.push(mir_issues::Issue::new(
mir_issues::IssueKind::UndefinedDocblockClass {
name: fqcn.to_string(),
},
mir_issues::Location {
file: file.clone(),
line: fn_line,
line_end: fn_line_end,
col_start: fn_col_start,
col_end: crate::diagnostics::clamp_col_end(
fn_line,
fn_line_end,
fn_col_start,
fn_col_end,
),
},
));
continue;
}
if self.mode == AnalysisMode::Full {
self.db.record_reference_location(crate::db::RefLoc {
symbol_key: Arc::from(format!("cls:{fqcn}")),
file: file.clone(),
line: fn_line,
col_start: fn_col_start,
col_end: crate::diagnostics::clamp_col_end(
fn_line,
fn_line_end,
fn_col_start,
fn_col_end,
),
});
}
if let Some(message) =
super::classes::check_generic_arity(self.db, fqcn, *arity)
{
issues.push(mir_issues::Issue::new(
mir_issues::IssueKind::InvalidDocblock { message },
mir_issues::Location {
file: file.clone(),
line: fn_line,
line_end: fn_line_end,
col_start: fn_col_start,
col_end: crate::diagnostics::clamp_col_end(
fn_line,
fn_line_end,
fn_col_start,
fn_col_end,
),
},
));
}
}
}
}
}
/// Pure entry point: run the same analysis as [`Self::analyze_fn_decl`] for
/// one function decl, but return the result instead of mutating
/// caller-owned buffers. Used by the `infer_function` salsa tracked query.
///
/// `ResolvedSymbol`s observed during the walk are intentionally dropped —
/// symbols are re-walked on demand to keep the cache small.
///
/// Ref-loc isolation: the walk is bracketed by a push/pop of a staging
/// frame, so only refs produced by *this* call are returned — refs
/// already staged on the handle (or recorded by a nested tracked query)
/// are unaffected.
pub(crate) fn analyze_fn_decl_pure(
&self,
decl: &php_ast::owned::FunctionDecl,
file: &Arc<str>,
source: &str,
source_map: &php_rs_parser::source_map::SourceMap,
) -> crate::db::FunctionInferenceResult {
use crate::flow_state::FlowState;
use crate::stmt::StatementsAnalyzer;
use mir_issues::IssueBuffer;
// Isolate this walk's refs in a fresh staging frame; popped at exit.
self.db.push_ref_loc_frame();
let mut issues: Vec<Issue> = Vec::new();
let mut discarded_symbols: Vec<ResolvedSymbol> = Vec::new();
let fn_name = decl.name.as_deref().unwrap_or("").to_string();
for param in decl.params.iter() {
if let Some(hint) = ¶m.type_hint {
self.check_and_record_type_hint_classes(
hint,
file,
source,
source_map,
&mut issues,
Some(&mut discarded_symbols),
);
}
if let Some(default_expr) = ¶m.default {
check_expr_for_undefined_classes(
default_expr,
self.db,
file,
source,
source_map,
&mut issues,
self.php_version,
);
}
}
if let Some(hint) = &decl.return_type {
self.check_and_record_type_hint_classes(
hint,
file,
source,
source_map,
&mut issues,
Some(&mut discarded_symbols),
);
}
let resolved = lookup_function_node_for_decl(self.db, file.as_ref(), &fn_name);
if self.mode == AnalysisMode::Full {
self.emit_missing_fn_types(
decl,
resolved.as_ref().map(|(_, s)| s),
file,
source,
source_map,
&mut issues,
);
}
#[allow(clippy::type_complexity)]
let (params, return_ty, template_params, declared_throws): (
Arc<[mir_codebase::DeclaredParam]>,
_,
Vec<_>,
Arc<[Arc<str>]>,
) = match &resolved {
Some((_, storage))
if storage.params.len() == decl.params.len()
&& storage
.params
.iter()
.zip(decl.params.iter())
.all(|(cp, ap)| ap.name.as_deref().unwrap_or("") == cp.name.as_ref()) =>
{
(
Arc::clone(&storage.params),
storage.return_type.as_deref().cloned(),
storage.template_params.clone(),
Arc::from(storage.throws.as_slice()),
)
}
_ => (
Arc::from(ast_derived_fn_params(&decl.params)),
None,
vec![],
Arc::from([]),
),
};
self.check_and_record_throws_classes(
&declared_throws,
fn_header_name_span(source, decl),
file,
source,
source_map,
&mut issues,
);
let mut ctx = FlowState::for_method_with_templates(
¶ms,
return_ty,
declared_throws,
None,
None,
None,
crate::body_analysis::is_strict_types_file(source),
false,
true,
Some(&template_params),
);
seed_param_locations(&mut ctx, &decl.params, source, source_map);
let mut buf = IssueBuffer::new();
let mut sa = StatementsAnalyzer::new(
self.db,
file.clone(),
source,
source_map,
&mut buf,
&mut discarded_symbols,
self.php_version,
self.mode,
);
sa.collect_symbols = self.collect_symbols;
// The symbol buffer above is dropped at return — skip building it.
sa.collect_symbols = false;
ctx.is_generator = body_has_yield(&decl.body.stmts);
sa.analyze_stmts(&decl.body.stmts, &mut ctx);
let inferred = merge_return_types(&sa.return_types, ctx.diverges);
let inferred = if sa.yielded_types.is_empty() {
inferred
} else {
build_generator_return_type(&sa.yielded_types, inferred)
};
drop(sa);
emit_unused_params(¶ms, &ctx, "", file, &mut issues);
emit_unused_variables(&ctx, file, &mut issues);
issues.extend(buf.into_all_issues());
let ref_locs = self.db.pop_ref_loc_frame();
crate::db::FunctionInferenceResult {
issues,
ref_locs,
return_type: Some(inferred),
}
}
#[allow(clippy::too_many_arguments)]
pub(super) fn analyze_fn_decl_typed(
&self,
decl: &php_ast::owned::FunctionDecl,
file: &Arc<str>,
source: &str,
source_map: &php_rs_parser::source_map::SourceMap,
all_issues: &mut Vec<Issue>,
type_envs: &mut FxHashMap<crate::type_env::ScopeId, crate::type_env::TypeEnv>,
all_symbols: &mut Vec<ResolvedSymbol>,
) {
use crate::flow_state::FlowState;
use crate::stmt::StatementsAnalyzer;
use mir_issues::IssueBuffer;
crate::attributes::check_function_attributes(
decl,
self.db,
file,
source,
source_map,
all_issues,
self.mode == AnalysisMode::Full,
Some(&mut *all_symbols),
);
let fn_name = decl.name.as_deref().unwrap_or("").to_string();
for param in decl.params.iter() {
if let Some(hint) = ¶m.type_hint {
self.check_and_record_type_hint_classes(
hint,
file,
source,
source_map,
all_issues,
Some(&mut *all_symbols),
);
}
if let Some(default_expr) = ¶m.default {
check_expr_for_undefined_classes(
default_expr,
self.db,
file,
source,
source_map,
all_issues,
self.php_version,
);
}
}
if let Some(hint) = &decl.return_type {
self.check_and_record_type_hint_classes(
hint,
file,
source,
source_map,
all_issues,
Some(&mut *all_symbols),
);
}
let resolved = lookup_function_node_for_decl(self.db, file.as_ref(), &fn_name);
if self.mode == AnalysisMode::Full {
self.emit_missing_fn_types(
decl,
resolved.as_ref().map(|(_, s)| s),
file,
source,
source_map,
all_issues,
);
}
let fqn = resolved.as_ref().map(|(f, _)| f.clone());
let (params, return_ty, declared_throws): (
Arc<[mir_codebase::DeclaredParam]>,
_,
Arc<[Arc<str>]>,
) = match &resolved {
Some((_, storage)) => {
if storage.params.len() == decl.params.len()
&& storage
.params
.iter()
.zip(decl.params.iter())
.all(|(cp, ap)| ap.name.as_deref().unwrap_or("") == cp.name.as_ref())
{
(
Arc::clone(&storage.params),
storage.return_type.as_deref().cloned(),
Arc::from(storage.throws.as_slice()),
)
} else {
(
Arc::from(ast_derived_fn_params(&decl.params)),
None,
Arc::from([]),
)
}
}
None => (
Arc::from(ast_derived_fn_params(&decl.params)),
None,
Arc::from([]),
),
};
self.check_and_record_throws_classes(
&declared_throws,
fn_header_name_span(source, decl),
file,
source,
source_map,
all_issues,
);
let mut ctx = FlowState::for_function(
¶ms,
return_ty,
declared_throws,
None,
None,
None,
crate::body_analysis::is_strict_types_file(source),
true,
);
ctx.is_in_pure_fn = resolved.as_ref().map(|(_, s)| s.is_pure).unwrap_or(false);
// A free function has no `$this`, so `@mutation-free` has nothing to
// exempt — its only meaningful half is exactly `@external-mutation-
// free`'s "don't mutate a parameter" constraint. Reuse the existing
// (method-shaped) flag rather than introduce a function-specific one:
// its own gate (`recv_stripped != "this" && recv is a param`) already
// does the right thing here, since a free function's receiver is
// never literally `"this"`. `@pure` already covers this case via its
// own, separate `is_in_pure_fn` check above.
ctx.is_in_external_mutation_free_method = resolved
.as_ref()
.is_some_and(|(_, s)| s.is_mutation_free || s.is_external_mutation_free);
ctx.current_function_fqn = fqn.clone();
seed_param_locations(&mut ctx, &decl.params, source, source_map);
record_param_symbols(all_symbols, file, source, &decl.params, &ctx);
let mut buf = IssueBuffer::new();
let mut sa = StatementsAnalyzer::new(
self.db,
file.clone(),
source,
source_map,
&mut buf,
all_symbols,
self.php_version,
self.mode,
);
sa.collect_symbols = self.collect_symbols;
ctx.is_generator = body_has_yield(&decl.body.stmts);
sa.analyze_stmts(&decl.body.stmts, &mut ctx);
let inferred = merge_return_types(&sa.return_types, ctx.diverges);
let inferred = if sa.yielded_types.is_empty() {
inferred
} else {
build_generator_return_type(&sa.yielded_types, inferred)
};
drop(sa);
let scope_name = fqn.clone().unwrap_or_else(|| Arc::from(fn_name));
type_envs.insert(
crate::type_env::ScopeId::Function {
file: file.clone(),
name: scope_name,
},
crate::type_env::TypeEnv::new(ctx.vars.clone()),
);
emit_unused_params(¶ms, &ctx, "", file, all_issues);
emit_unused_variables(&ctx, file, all_issues);
all_issues.extend(buf.into_all_issues());
if let Some(fqn) = fqn {
self.record_function_inference(&fqn, &inferred);
}
}
}