forked from PHPantom-dev/phpantom_lsp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclassmap_scanner.rs
More file actions
2851 lines (2588 loc) · 95 KB
/
Copy pathclassmap_scanner.rs
File metadata and controls
2851 lines (2588 loc) · 95 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
//! Fast byte-level PHP symbol scanners for early-stage file discovery.
//!
//! This module provides two single-pass state machines that extract
//! symbol names from PHP source without a full AST parse:
//!
//! - **PSR-4 scanner** ([`find_classes`]) — extracts fully-qualified
//! class, interface, trait, and enum names. Used by the PSR-4
//! directory walker to build a classmap when Composer's
//! `autoload_classmap.php` is missing or incomplete.
//!
//! - **Full-scan** ([`find_symbols`]) — extracts classes *plus*
//! standalone function names, `define()` constants, and top-level
//! `const` declarations. Used for non-Composer projects (no
//! `composer.json`) and for Composer autoload files
//! (`autoload_files.php` and their `require_once` chains) to
//! populate name-to-path indices without a full AST parse.
//!
//! These scanners serve three indexing scenarios:
//!
//! 1. **Optimized Composer** — the Composer classmap is parsed
//! directly (not by this module). Functions and constants from
//! `autoload_files.php` are discovered by the full-scan during
//! initialization, populating `autoload_function_index`,
//! `autoload_constant_index`, and `fqn_uri_index`. Lazy
//! `update_ast` on first access provides complete details.
//!
//! 2. **Composer self-scan** — the PSR-4 scanner builds a classmap
//! from `composer.json`'s autoload directories. Functions and
//! constants from `autoload_files.php` are discovered by the
//! full-scan, same as scenario 1.
//!
//! 3. **No Composer** — the full-scan walks all workspace files,
//! populating the classmap, `autoload_function_index`, and
//! `autoload_constant_index` in one pass. Lazy `update_ast`
//! on first access provides complete `FunctionInfo`/`DefineInfo`.
//!
//! The implementation is modelled after Composer's `PhpFileParser` /
//! `PhpFileCleaner` pipeline and Libretto's `FastScanner`. Both
//! scanners handle:
//!
//! - `class`, `interface`, `trait`, and `enum` declarations
//! - `namespace` declarations (including braced and semicolon forms)
//! - Single-quoted and double-quoted strings (with escape handling)
//! - Heredoc and nowdoc literals
//! - Line comments (`//`, `#`) and block comments (`/* ... */`)
//! - PHP attributes (`#[...]`) — not confused with `#` comments
//! - Property/nullsafe access like `$node->class` (not treated as a
//! class declaration)
//! - `SomeClass::class` constant access (not treated as a declaration)
//!
//! The full-scan additionally handles:
//!
//! - `function` declarations (top-level only, not methods or closures)
//! - `define('NAME', ...)` calls (constant name from first string arg)
//! - `const NAME = ...` at top level (not class constants)
//!
//! # Performance
//!
//! Both scanners use `memchr` for SIMD-accelerated keyword
//! pre-screening. Files that contain none of the relevant keywords
//! are rejected in a single fast pass without entering the state
//! machine.
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use memchr::{memchr, memmem};
// ─── Data structures ────────────────────────────────────────────────────────
/// All symbols discovered in a single PHP file by [`find_symbols`].
///
/// Contains fully-qualified names for classes, standalone functions,
/// and constants (`define()` and top-level `const`).
#[derive(Debug, Clone, Default)]
pub struct ScanResult {
/// Fully-qualified class, interface, trait, and enum names.
pub classes: Vec<String>,
/// Fully-qualified standalone function names.
pub functions: Vec<String>,
/// Constant names from `define('NAME', ...)` and top-level `const NAME`.
pub constants: Vec<String>,
}
/// Combined workspace scan results for classes, functions, and constants.
///
/// Returned by [`scan_workspace_fallback_full`] and consumed during
/// server initialization to populate the classmap and autoload indices.
#[derive(Debug, Clone, Default)]
pub struct WorkspaceScanResult {
/// FQN → file path for classes, interfaces, traits, and enums.
pub classmap: HashMap<String, PathBuf>,
/// FQN → file path for standalone functions.
pub function_index: HashMap<String, PathBuf>,
/// Constant name → file path for `define()` and top-level `const`.
pub constant_index: HashMap<String, PathBuf>,
}
// ─── Public API ─────────────────────────────────────────────────────────────
/// Scan a single PHP file and return the fully-qualified class names it
/// defines.
///
/// Returns an empty `Vec` when the file cannot be read, is empty, or
/// contains no class-like declarations.
pub fn scan_file(path: &Path) -> Vec<String> {
let Ok(content) = std::fs::read(path) else {
return Vec::new();
};
if content.is_empty() {
return Vec::new();
}
find_classes(&content)
}
/// Scan already-loaded file content and return the fully-qualified class
/// names it defines.
///
/// This avoids a redundant `fs::read` when the caller already has the
/// bytes in memory (e.g. from a parallel batch read).
pub fn scan_content(content: &[u8]) -> Vec<String> {
if content.is_empty() {
return Vec::new();
}
find_classes(content)
}
/// Scan a single PHP file and return all discovered symbols (classes,
/// functions, and constants).
///
/// Returns an empty [`ScanResult`] when the file cannot be read or is
/// empty.
pub fn scan_file_full(path: &Path) -> ScanResult {
let Ok(content) = std::fs::read(path) else {
return ScanResult::default();
};
if content.is_empty() {
return ScanResult::default();
}
find_symbols(&content)
}
/// Return the number of available CPU cores, capped at a sensible
/// default. Used to size parallel scanning batches.
fn thread_count() -> usize {
std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(4)
}
/// Build a classmap by scanning all `.php` files under the given
/// directories.
///
/// Each directory is walked recursively using the `ignore` crate for
/// gitignore-aware traversal. Hidden directories (`.git`, `.idea`,
/// etc.) are skipped automatically. Directories in `.gitignore` are
/// also skipped. Any directory whose absolute path is in
/// `vendor_dir_paths` is explicitly skipped regardless of `.gitignore`.
///
/// File scanning is parallelised across CPU cores: the directory walk
/// collects file paths first, then files are read and scanned in
/// parallel batches using [`std::thread::scope`].
///
/// Returns a `HashMap<String, PathBuf>` mapping fully-qualified class
/// names to the absolute file path where they are defined. When a
/// class name appears in multiple files, the first occurrence wins.
pub fn scan_directories(
dirs: &[PathBuf],
vendor_dir_paths: &[PathBuf],
) -> HashMap<String, PathBuf> {
let mut php_files: Vec<PathBuf> = Vec::new();
let skip_paths = HashSet::new();
for dir in dirs {
if !dir.is_dir() {
continue;
}
collect_php_files(dir, vendor_dir_paths, &skip_paths, &mut php_files);
}
scan_files_parallel_classes(&php_files)
}
/// Build a classmap by scanning all `.php` files under the given
/// directories, applying PSR-4 compliance filtering.
///
/// For each `(namespace_prefix, base_path)` pair the scanner walks
/// `base_path` recursively using the `ignore` crate for
/// gitignore-aware traversal, and only includes classes whose FQN
/// matches the PSR-4 mapping: the namespace prefix plus the relative
/// file path must equal the class name.
///
/// Entries from `classmap_dirs` are scanned without PSR-4 filtering
/// (equivalent to Composer's `autoload.classmap` entries).
///
/// File scanning is parallelised across CPU cores.
///
/// `vendor_dir_paths` contains absolute paths of all known vendor
/// directories. Any directory whose absolute path matches one of
/// these is skipped.
pub fn scan_psr4_directories(
psr4: &[(String, PathBuf)],
classmap_dirs: &[PathBuf],
vendor_dir_paths: &[PathBuf],
) -> HashMap<String, PathBuf> {
scan_psr4_directories_with_skip(psr4, classmap_dirs, vendor_dir_paths, &HashSet::new())
}
/// Like [`scan_psr4_directories`] but accepts a set of absolute file
/// paths to skip. Files whose canonical path appears in `skip_paths`
/// are excluded from scanning. This is used by the merged
/// classmap + self-scan pipeline to avoid re-scanning files that
/// the Composer classmap already covers.
pub fn scan_psr4_directories_with_skip(
psr4: &[(String, PathBuf)],
classmap_dirs: &[PathBuf],
vendor_dir_paths: &[PathBuf],
skip_paths: &HashSet<PathBuf>,
) -> HashMap<String, PathBuf> {
// ── PSR-4 directories: collect (path, expected_fqn) pairs ───────
let mut psr4_files: Vec<(PathBuf, String)> = Vec::new();
for (prefix, base_path) in psr4 {
if !base_path.is_dir() {
continue;
}
collect_psr4_php_files(
base_path,
prefix,
vendor_dir_paths,
skip_paths,
&mut psr4_files,
);
}
// ── Plain classmap directories ──────────────────────────────────
let mut plain_files: Vec<PathBuf> = Vec::new();
for dir in classmap_dirs {
if !dir.is_dir() {
continue;
}
collect_php_files(dir, vendor_dir_paths, skip_paths, &mut plain_files);
}
// ── Scan all files in parallel ──────────────────────────────────
let mut classmap = scan_files_parallel_psr4(&psr4_files);
let plain_classmap = scan_files_parallel_classes(&plain_files);
for (fqcn, path) in plain_classmap {
classmap.entry(fqcn).or_insert(path);
}
classmap
}
/// Build a classmap from `installed.json` vendor package metadata.
///
/// Reads `<vendor_path>/composer/installed.json` and scans each
/// package's autoload directories. Supports PSR-4 and classmap
/// entries.
pub fn scan_vendor_packages(workspace_root: &Path, vendor_dir: &str) -> WorkspaceScanResult {
scan_vendor_packages_with_skip(workspace_root, vendor_dir, &HashSet::new())
}
/// Like [`scan_vendor_packages`] but accepts a set of absolute file
/// paths to skip. Files whose path appears in `skip_paths` are
/// excluded from scanning.
pub fn scan_vendor_packages_with_skip(
workspace_root: &Path,
vendor_dir: &str,
skip_paths: &HashSet<PathBuf>,
) -> WorkspaceScanResult {
let vendor_path = workspace_root.join(vendor_dir);
let installed_path = vendor_path.join("composer").join("installed.json");
let Ok(content) = std::fs::read_to_string(&installed_path) else {
return WorkspaceScanResult::default();
};
let Ok(json) = serde_json::from_str::<serde_json::Value>(&content) else {
return WorkspaceScanResult::default();
};
// installed.json has two formats:
// Composer 1: top-level array of packages
// Composer 2: { "packages": [...] }
let packages = if let Some(arr) = json.as_array() {
arr.as_slice()
} else if let Some(pkgs) = json.get("packages").and_then(|p| p.as_array()) {
pkgs.as_slice()
} else {
return WorkspaceScanResult::default();
};
let vendor_dir_paths: Vec<PathBuf> = vec![vendor_path.clone()];
// The directory containing installed.json — install-path values
// are relative to this directory.
let composer_dir = vendor_path.join("composer");
// Phase 1: collect all file paths from all packages (sequential
// walk, but no file I/O beyond stat calls).
let mut psr4_files: Vec<(PathBuf, String)> = Vec::new();
let mut plain_files: Vec<PathBuf> = Vec::new();
for package in packages {
// Locate the package on disk. Composer 2's installed.json
// includes an `install-path` field that is relative to the
// `vendor/composer/` directory. This is the authoritative
// location and handles path repositories, custom installers,
// and any other layout that doesn't follow the default
// `vendor/<name>/` convention. Fall back to `vendor/<name>`
// only when `install-path` is absent (Composer 1 format).
let pkg_path =
if let Some(install_path) = package.get("install-path").and_then(|p| p.as_str()) {
composer_dir.join(install_path)
} else if let Some(pkg_name) = package.get("name").and_then(|n| n.as_str()) {
vendor_path.join(pkg_name)
} else {
continue;
};
let pkg_path = match pkg_path.canonicalize() {
Ok(p) => p,
Err(_) => {
// Directory doesn't exist (package not installed yet).
if !pkg_path.is_dir() {
continue;
}
pkg_path
}
};
if !pkg_path.is_dir() {
continue;
}
// Extract autoload section
let Some(autoload) = package.get("autoload") else {
continue;
};
// PSR-4 entries
if let Some(psr4) = autoload.get("psr-4").and_then(|p| p.as_object()) {
for (prefix, paths) in psr4 {
let prefix = normalise_prefix(prefix);
for dir_str in value_to_strings(paths) {
let dir = pkg_path.join(&dir_str);
if dir.is_dir() {
collect_psr4_php_files(
&dir,
&prefix,
&vendor_dir_paths,
skip_paths,
&mut psr4_files,
);
}
}
}
}
// Files entries (individual PHP files that are always loaded)
if let Some(files) = autoload.get("files").and_then(|f| f.as_array()) {
let mut has_custom_autoloader = false;
for entry in files {
if let Some(file_str) = entry.as_str() {
let file = pkg_path.join(file_str);
if file.is_file()
&& file.extension().is_some_and(|ext| ext == "php")
&& !skip_paths.contains(&file)
{
// Check if this file registers a custom autoloader.
if !has_custom_autoloader
&& let Ok(content) = std::fs::read(&file)
&& memmem::find(&content, b"spl_autoload_register").is_some()
{
has_custom_autoloader = true;
}
plain_files.push(file);
}
}
}
// When a files entry registers a custom autoloader via
// spl_autoload_register, it will load classes from the
// package at runtime. Since we can't execute that logic,
// do a full scan of the package directory to discover all
// classes it provides.
if has_custom_autoloader {
collect_php_files(&pkg_path, &vendor_dir_paths, skip_paths, &mut plain_files);
}
}
// Classmap entries
if let Some(cm) = autoload.get("classmap").and_then(|c| c.as_array()) {
for entry in cm {
if let Some(dir_str) = entry.as_str() {
let dir = pkg_path.join(dir_str);
if dir.is_dir() {
collect_php_files(&dir, &vendor_dir_paths, skip_paths, &mut plain_files);
} else if dir.is_file()
&& dir.extension().is_some_and(|ext| ext == "php")
&& !skip_paths.contains(&dir)
{
plain_files.push(dir);
}
}
}
}
}
// Phase 2: scan all collected files in parallel
let mut all_files: Vec<PathBuf> = psr4_files.into_iter().map(|(path, _)| path).collect();
all_files.extend(plain_files);
scan_files_parallel_full(&all_files)
}
/// Scan all `.php` files under the workspace root using the PSR-4
/// scanner (`find_classes`), excluding hidden directories, gitignored
/// directories, and vendor directories.
///
/// This is a classes-only fallback used when `composer.json` cannot be
/// parsed. Prefer [`scan_workspace_fallback_full`] for the no-Composer
/// scenario so that functions and constants are also discovered.
///
/// `vendor_dir_paths` contains absolute paths of all known vendor
/// directories. Pass a single-element slice with the vendor directory
/// for single-project workspaces.
pub fn scan_workspace_fallback(
workspace_root: &Path,
vendor_dir_paths: &[PathBuf],
) -> HashMap<String, PathBuf> {
scan_directories(&[workspace_root.to_path_buf()], vendor_dir_paths)
}
/// Scan a batch of files for class names in parallel and return a classmap.
///
/// Uses [`std::thread::scope`] with one thread per CPU core. Small
/// batches (≤ 4 files) are processed sequentially to avoid thread
/// overhead.
fn scan_files_parallel_classes(files: &[PathBuf]) -> HashMap<String, PathBuf> {
if files.is_empty() {
return HashMap::new();
}
// Small batches: sequential
if files.len() <= 4 {
let mut classmap = HashMap::new();
for path in files {
if let Ok(content) = std::fs::read(path) {
for fqcn in scan_content(&content) {
classmap.entry(fqcn).or_insert_with(|| path.clone());
}
}
}
return classmap;
}
let n_threads = thread_count().min(files.len());
let chunk_size = files.len().div_ceil(n_threads);
let results: Vec<Vec<(String, PathBuf)>> = std::thread::scope(|s| {
let handles: Vec<_> = files
.chunks(chunk_size)
.map(|chunk| {
s.spawn(move || {
let mut local: Vec<(String, PathBuf)> = Vec::new();
for path in chunk {
if let Ok(content) = std::fs::read(path) {
for fqcn in scan_content(&content) {
local.push((fqcn, path.clone()));
}
}
}
local
})
})
.collect();
handles
.into_iter()
.map(|h| {
h.join().unwrap_or_else(|_| {
tracing::error!("PHPantom: thread panic in scan_files_parallel_classes");
Vec::new()
})
})
.collect()
});
let total: usize = results.iter().map(|v| v.len()).sum();
let mut classmap = HashMap::with_capacity(total);
for batch in results {
for (fqcn, path) in batch {
classmap.entry(fqcn).or_insert(path);
}
}
classmap
}
/// Scan a batch of files for class names with PSR-4 filtering in
/// parallel.
///
/// Each entry is `(file_path, expected_fqn)`. Only classes whose FQN
/// matches the expected FQN are included.
fn scan_files_parallel_psr4(files: &[(PathBuf, String)]) -> HashMap<String, PathBuf> {
if files.is_empty() {
return HashMap::new();
}
// Small batches: sequential
if files.len() <= 4 {
let mut classmap = HashMap::new();
for (path, expected_fqn) in files {
if let Ok(content) = std::fs::read(path) {
for fqcn in scan_content(&content) {
if &fqcn == expected_fqn {
classmap.entry(fqcn).or_insert_with(|| path.clone());
}
}
}
}
return classmap;
}
let n_threads = thread_count().min(files.len());
let chunk_size = files.len().div_ceil(n_threads);
let results: Vec<Vec<(String, PathBuf)>> = std::thread::scope(|s| {
let handles: Vec<_> = files
.chunks(chunk_size)
.map(|chunk| {
s.spawn(move || {
let mut local: Vec<(String, PathBuf)> = Vec::new();
for (path, expected_fqn) in chunk {
if let Ok(content) = std::fs::read(path) {
for fqcn in scan_content(&content) {
if &fqcn == expected_fqn {
local.push((fqcn, path.clone()));
}
}
}
}
local
})
})
.collect();
handles
.into_iter()
.map(|h| {
h.join().unwrap_or_else(|_| {
tracing::error!("PHPantom: thread panic in scan_files_parallel_psr4");
Vec::new()
})
})
.collect()
});
let total: usize = results.iter().map(|v| v.len()).sum();
let mut classmap = HashMap::with_capacity(total);
for batch in results {
for (fqcn, path) in batch {
classmap.entry(fqcn).or_insert(path);
}
}
classmap
}
/// Scan a batch of files for all symbols (classes, functions, constants)
/// in parallel and return a [`WorkspaceScanResult`].
fn scan_files_parallel_full(files: &[PathBuf]) -> WorkspaceScanResult {
if files.is_empty() {
return WorkspaceScanResult::default();
}
// Small batches: sequential
if files.len() <= 4 {
let mut result = WorkspaceScanResult::default();
for path in files {
if let Ok(content) = std::fs::read(path) {
let scan = find_symbols(&content);
for fqcn in scan.classes {
let class_short_name = fqcn_short_name(&fqcn).to_owned();
result
.classmap
.entry(fqcn)
.and_modify(|existing| {
let existing_stem =
existing.file_stem().and_then(|s| s.to_str()).unwrap_or("");
let new_stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("");
if existing_stem != class_short_name && new_stem == class_short_name {
*existing = path.clone();
}
})
.or_insert_with(|| path.clone());
}
for fqn in scan.functions {
result
.function_index
.entry(fqn)
.or_insert_with(|| path.clone());
}
for name in scan.constants {
result
.constant_index
.entry(name)
.or_insert_with(|| path.clone());
}
}
}
return result;
}
let n_threads = thread_count().min(files.len());
let chunk_size = files.len().div_ceil(n_threads);
let results: Vec<Vec<(ScanResult, PathBuf)>> = std::thread::scope(|s| {
let handles: Vec<_> = files
.chunks(chunk_size)
.map(|chunk| {
s.spawn(move || {
let mut local: Vec<(ScanResult, PathBuf)> = Vec::new();
for path in chunk {
if let Ok(content) = std::fs::read(path) {
let scan = find_symbols(&content);
if !scan.classes.is_empty()
|| !scan.functions.is_empty()
|| !scan.constants.is_empty()
{
local.push((scan, path.clone()));
}
}
}
local
})
})
.collect();
handles
.into_iter()
.map(|h| {
h.join().unwrap_or_else(|_| {
tracing::error!("PHPantom: thread panic in scan_files_parallel_full");
Vec::new()
})
})
.collect()
});
let mut result = WorkspaceScanResult::default();
for batch in results {
for (scan, path) in batch {
for fqcn in scan.classes {
let class_short_name = fqcn_short_name(&fqcn).to_owned();
result
.classmap
.entry(fqcn)
.and_modify(|existing| {
// When two files declare the same FQN, prefer the one
// whose filename matches the class's short name (PSR-4
// convention). This handles packages with conditional
// loading (e.g. ArraySubsetAsserts.php vs
// ArraySubsetAssertsEmpty.php both defining the same
// trait name).
let existing_stem =
existing.file_stem().and_then(|s| s.to_str()).unwrap_or("");
let new_stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("");
if existing_stem != class_short_name && new_stem == class_short_name {
*existing = path.clone();
}
})
.or_insert_with(|| path.clone());
}
for fqn in scan.functions {
result
.function_index
.entry(fqn)
.or_insert_with(|| path.clone());
}
for name in scan.constants {
result
.constant_index
.entry(name)
.or_insert_with(|| path.clone());
}
}
}
result
}
/// Scan all `.php` files under the workspace root using the full-scan
/// (`find_symbols`) and return classes, functions, and constants in a
/// single pass.
///
/// This is the primary scanner for the "no `composer.json`" scenario.
/// It populates all three indices (classmap, function index, constant
/// index) so that non-Composer projects get cross-file resolution for
/// every symbol type. Lazy `update_ast` on first access provides the
/// complete `FunctionInfo` / `DefineInfo` needed by hover, completion,
/// and go-to-definition.
///
/// Uses the `ignore` crate for gitignore-aware walking. Hidden
/// directories (starting with `.`) are skipped automatically.
/// Directories whose absolute path is in `skip_dirs` are also skipped
/// (used by monorepo support to avoid double-scanning subproject
/// directories that were already processed by the Composer pipeline).
pub fn scan_workspace_fallback_full(
workspace_root: &Path,
skip_dirs: &HashSet<PathBuf>,
) -> WorkspaceScanResult {
use ignore::WalkBuilder;
let skip_dirs_owned = skip_dirs.clone();
// Phase 1: collect file paths (single-threaded walk)
let walker = WalkBuilder::new(workspace_root)
.git_ignore(true)
.git_global(true)
.git_exclude(true)
.hidden(true)
.parents(true)
.ignore(true)
.filter_entry(move |entry| {
if entry.file_type().is_some_and(|ft| ft.is_dir()) {
let path = entry.path();
// Skip directories in the skip set (monorepo subproject roots)
if skip_dirs_owned.contains(path) {
return false;
}
}
true
})
.build();
let mut php_files: Vec<PathBuf> = Vec::new();
for entry in walker.flatten() {
let path = entry.path();
if path.is_file() && path.extension().is_some_and(|ext| ext == "php") {
php_files.push(path.to_path_buf());
}
}
// Phase 2: scan files in parallel
scan_files_parallel_full(&php_files)
}
/// Scan Drupal-specific directories for PHP symbols, bypassing `.gitignore`.
///
/// Drupal projects typically exclude their web root directories
/// (`web/core`, `web/modules/contrib`, etc.) from version control via
/// `.gitignore` because those files are managed by Composer. The normal
/// gitignore-aware walkers would therefore silently skip the most important
/// parts of the codebase. This function walks with gitignore **disabled**
/// so that those directories are always indexed.
///
/// In addition to `.php` files, Drupal uses several other file extensions
/// for valid PHP source: `.module`, `.install`, `.theme`, `.profile`,
/// `.inc`, and `.engine`. All are included by this scanner.
///
/// Test directories (`tests/` and `Tests/`) are excluded by name to avoid
/// indexing duplicate class definitions from unit-test fixtures.
pub fn scan_drupal_directories(web_root: &Path) -> WorkspaceScanResult {
use ignore::WalkBuilder;
let drupal_dirs = [
"core",
"modules/contrib",
"modules/custom",
"themes/contrib",
"themes/custom",
"profiles",
"sites",
];
let mut php_files: Vec<PathBuf> = Vec::new();
for rel in &drupal_dirs {
let dir = web_root.join(rel);
if !dir.exists() {
continue;
}
let walker = WalkBuilder::new(&dir)
// Gitignore is intentionally disabled — Drupal's .gitignore
// excludes web/core and web/modules/contrib which are the
// most critical directories to index.
.git_ignore(false)
.git_global(false)
.git_exclude(false)
.hidden(true) // still skip .git, .idea, etc.
.parents(false)
.ignore(false)
.filter_entry(|entry| {
if entry.file_type().is_some_and(|ft| ft.is_dir()) {
let name = entry.file_name().to_str().unwrap_or("");
// Exclude test directories (both conventional casings)
if name == "tests" || name == "Tests" {
return false;
}
}
true
})
.build();
for entry in walker.flatten() {
let path = entry.path();
if path.is_file() && is_drupal_php_file(path) {
php_files.push(path.to_path_buf());
}
}
}
scan_files_parallel_full(&php_files)
}
/// Return `true` for file extensions that Drupal treats as PHP source.
fn is_drupal_php_file(path: &Path) -> bool {
matches!(
path.extension().and_then(|e| e.to_str()),
Some("php" | "module" | "install" | "theme" | "profile" | "inc" | "engine")
)
}
// ─── Core scanner ───────────────────────────────────────────────────────────
/// The **full-scan**: a single-pass byte-level scanner that extracts
/// fully-qualified class, function, and constant names from PHP source
/// bytes.
///
/// This is the extended version of [`find_classes`] (the PSR-4 scanner)
/// that also recognises `function` declarations, `define()` calls, and
/// top-level `const` statements. It is used for both non-Composer
/// projects (full workspace scan) and Composer autoload files
/// (`autoload_files.php` and their `require_once` chains).
pub fn find_symbols(content: &[u8]) -> ScanResult {
// Quick rejection — if the file has none of the relevant keywords
// we can bail immediately.
if !has_any_keyword(content) {
return ScanResult::default();
}
let mut result = ScanResult::default();
let mut namespace = String::new();
let len = content.len();
let mut i = 0;
// Brace depth tracking for top-level `const` detection.
// Depth 0 = top-level, depth 1 = inside a class/namespace block.
let mut brace_depth: u32 = 0;
// Whether we are inside a braced namespace block.
let mut in_braced_namespace = false;
// The brace depth at which the current namespace was opened.
// `const` declarations at this depth (or depth 0 outside braced
// namespaces) are top-level.
let mut namespace_brace_depth: u32 = 0;
// State flags
let mut in_line_comment = false;
let mut in_block_comment = false;
let mut in_single_string = false;
let mut in_double_string = false;
let mut in_heredoc = false;
let mut heredoc_id: &[u8] = &[];
while i < len {
// ── Skip: line comment (memchr to newline) ──────────────────
if in_line_comment {
if let Some(pos) = memchr(b'\n', &content[i..]) {
i += pos + 1;
} else {
break; // rest of file is a comment
}
in_line_comment = false;
continue;
}
// ── Skip: block comment (memmem to "*/") ────────────────────
if in_block_comment {
if let Some(pos) = memmem::find(&content[i..], b"*/") {
i += pos + 2;
in_block_comment = false;
} else {
break; // unclosed block comment
}
continue;
}
// ── Skip: single-quoted string (memchr to '\'' or '\\') ────
if in_single_string {
match memchr2_single_string(&content[i..]) {
Some((offset, b'\\')) => {
i += offset + 2; // skip escaped char
}
Some((offset, _)) => {
// Found closing quote
i += offset + 1;
in_single_string = false;
}
None => break, // unclosed string
}
continue;
}
// ── Skip: double-quoted string (memchr to '"' or '\\') ─────
if in_double_string {
match memchr2_double_string(&content[i..]) {
Some((offset, b'\\')) => {
i += offset + 2; // skip escaped char
}
Some((offset, _)) => {
// Found closing quote
i += offset + 1;
in_double_string = false;
}
None => break, // unclosed string
}
continue;
}
// ── Skip: heredoc / nowdoc (memchr to newline) ──────────────
if in_heredoc {
let line_start = i;
while i < len && (content[i] == b' ' || content[i] == b'\t') {
i += 1;
}
if i + heredoc_id.len() <= len && &content[i..i + heredoc_id.len()] == heredoc_id {
let after = i + heredoc_id.len();
if after >= len
|| content[after] == b';'
|| content[after] == b'\n'
|| content[after] == b'\r'
|| content[after] == b','
|| content[after] == b')'
{
in_heredoc = false;
i = after;
continue;
}
}
i = line_start;
if let Some(pos) = memchr(b'\n', &content[i..]) {
i += pos + 1;
} else {
break; // rest of file is inside heredoc
}
continue;
}
// ── Main code parsing ───────────────────────────────────────
let b = content[i];
// Braces for depth tracking
if b == b'{' {
brace_depth += 1;
i += 1;
continue;
}
if b == b'}' {
brace_depth = brace_depth.saturating_sub(1);
// Exiting a braced namespace block resets the namespace.
if in_braced_namespace && brace_depth == namespace_brace_depth {
in_braced_namespace = false;
namespace.clear();
}
i += 1;
continue;
}
// Comments
if b == b'/' && i + 1 < len {
if content[i + 1] == b'/' {
in_line_comment = true;
i += 2;
continue;
}
if content[i + 1] == b'*' {
in_block_comment = true;
i += 2;
continue;
}
}
if b == b'#' {
if i + 1 < len && content[i + 1] == b'[' {
i += 1;
continue;
}
in_line_comment = true;
i += 1;
continue;
}
// Strings
if b == b'\'' {
in_single_string = true;
i += 1;
continue;
}
if b == b'"' {
in_double_string = true;
i += 1;
continue;
}
// Heredoc / nowdoc