-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathImportResolver.java
More file actions
1815 lines (1566 loc) · 74.9 KB
/
Copy pathImportResolver.java
File metadata and controls
1815 lines (1566 loc) · 74.9 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
package cod.semantic;
import cod.ast.ASTFactory;
import cod.ast.node.*;
import cod.error.InternalError;
import cod.error.ProgramError;
import cod.lexer.*;
import cod.parser.MainParser;
import cod.debug.DebugSystem;
import cod.interpreter.Index;
import cod.ir.IRManager;
import cod.ptac.Artifact;
import java.util.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
public class ImportResolver {
private static final String PERF_PREFIX = "importResolver.";
// The new layout uses src/main/cod/demo/src/main with internal as a sibling of demo.
private static final String DEMO_DIR_NAME = "demo";
private static final Pattern SAFE_UNIT_NAME_PATTERN =
Pattern.compile("[A-Za-z_][A-Za-z0-9_]*(\\.[A-Za-z_][A-Za-z0-9_]*)*");
private static final Map<String, String> STANDARD_UNIT_PATH_OVERRIDES = createStandardUnitPathOverrides();
private static final int IMPORT_NAME_CACHE_LIMIT = 4096;
private static final int TYPE_CACHE_LIMIT = 4096;
private static final int INDEX_CACHE_LIMIT = 1024;
private static final int LOADED_TYPES_CACHE_LIMIT = 4096;
private static final int FILE_CACHE_LIMIT = 2048;
private static final int FILE_METADATA_CACHE_LIMIT = 4096;
private final Object policyLookupLock = new Object();
private Map<String, Program> importedUnits = new HashMap<String, Program>();
private Map<String, Program> loadedPrograms = new HashMap<String, Program>();
private Map<String, Program> preloadedImports = new HashMap<String, Program>();
private Set<String> registeredImports = new HashSet<String>();
private List<String> methodImportSpecs = new ArrayList<String>();
private Set<String> wildcardEverythingUnits = new HashSet<String>();
private Set<String> wildcardClassUnits = new HashSet<String>();
private Map<String, String> explicitFieldImports = new HashMap<String, String>();
private List<String> importPaths = new ArrayList<String>();
private Map<String, String> packageBroadcasts = new HashMap<String, String>();
// Concurrent map keeps lock-free fast-path reads in findPolicy/get/register paths.
private Map<String, Policy> importedPolicies = new ConcurrentHashMap<String, Policy>();
private Map<String, String> policyToUnitMap = new HashMap<String, String>();
// Import name cache for O(1) lookups
private Map<String, String> importNameCache = createBoundedMap(IMPORT_NAME_CACHE_LIMIT);
// Type cache for O(1) type lookups
private Map<String, Type> typeCache = createBoundedMap(TYPE_CACHE_LIMIT);
// Index cache for O(1) class lookups
private Map<String, Index> indexCache = createBoundedMap(INDEX_CACHE_LIMIT);
// IR manager for .codb files
private IRManager irManager;
// Cache for loaded TypeNodes (bytecode or parsed)
private Map<String, Type> loadedTypes = createBoundedMap(LOADED_TYPES_CACHE_LIMIT);
private Map<String, Artifact> loadedArtifacts = createBoundedMap(LOADED_TYPES_CACHE_LIMIT);
// Filesystem result cache
private Map<String, CachedFileResult> fileCache = createBoundedMap(FILE_CACHE_LIMIT);
// File metadata cache (exists, isDirectory, lastModified)
private Map<String, FileMetadata> fileMetadataCache = createBoundedMap(FILE_METADATA_CACHE_LIMIT);
// Cache hit/miss counters for debugging
private int fileCacheHits = 0;
private int fileCacheMisses = 0;
private int metadataCacheHits = 0;
private int metadataCacheMisses = 0;
private int indexCacheHits = 0;
private int indexCacheMisses = 0;
private int bytecodeCacheHits = 0;
private int bytecodeCacheMisses = 0;
// Current file location for relative import resolution
private String srcMainRoot;
private String demoSiblingRoot;
private String currentFileDirectory;
private String projectRoot;
// Cache entry with timestamp
private static class CachedFileResult {
final Program program;
final long lastModified;
CachedFileResult(Program program, long lastModified) {
this.program = program;
this.lastModified = lastModified;
}
boolean isValid(File file) {
return file.exists() && file.lastModified() == lastModified;
}
}
// File metadata cache
private static class FileMetadata {
final boolean exists;
final boolean isDirectory;
final long lastModified;
FileMetadata(boolean exists, boolean isDirectory, long lastModified) {
this.exists = exists;
this.isDirectory = isDirectory;
this.lastModified = lastModified;
}
boolean isValid(File file) {
return file.exists() == exists &&
file.isDirectory() == isDirectory &&
file.lastModified() == lastModified;
}
}
private static <K, V> Map<K, V> createBoundedMap(final int maxSize) {
Map<K, V> lru = new LinkedHashMap<K, V>(maxSize + 1, 0.75f, true) {
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
// removeEldestEntry is evaluated after insertion, so '>' enforces maxSize.
return size() > maxSize;
}
};
return Collections.synchronizedMap(lru);
}
public ImportResolver() {
importPaths.add("src/main");
DebugSystem.debug("IMPORTS", "Initialized with import paths: " + importPaths);
}
/**
* Set the current file directory and automatically find the src/main/ root
*/
public void setCurrentFileDirectory(String filePath) {
if (filePath == null || filePath.isEmpty()) {
DebugSystem.debug("IMPORTS", "setCurrentFileDirectory called with null/empty path");
return;
}
DebugSystem.debug("IMPORTS", "=== setCurrentFileDirectory CALLED ===");
DebugSystem.debug("IMPORTS", "filePath: " + filePath);
File file = new File(filePath);
File parentDir = file.getParentFile();
if (parentDir == null || !parentDir.exists()) {
DebugSystem.debug("IMPORTS", "Parent directory does not exist for: " + filePath);
return;
}
this.currentFileDirectory = parentDir.getAbsolutePath();
DebugSystem.debug("IMPORTS", "Current file directory set to: " + currentFileDirectory);
// Navigate up to find the src/main/ directory structure
File searchDir = parentDir;
this.srcMainRoot = null;
while (searchDir != null) {
// Check if this directory IS src/main/
if (searchDir.getName().equals("main") &&
searchDir.getParentFile() != null &&
searchDir.getParentFile().getName().equals("src")) {
this.srcMainRoot = searchDir.getAbsolutePath();
DebugSystem.debug("IMPORTS", "Found src/main/ root (directory itself): " + srcMainRoot);
break;
}
// Check if src/main/ is a subdirectory
File srcMain = new File(searchDir, "src/main");
if (srcMain.exists() && srcMain.isDirectory()) {
this.srcMainRoot = srcMain.getAbsolutePath();
DebugSystem.debug("IMPORTS", "Found src/main/ at: " + srcMainRoot);
break;
}
// Move up one level
searchDir = searchDir.getParentFile();
}
// If we found src/main/, add it to import paths and set project root
if (srcMainRoot != null) {
// Add the src/main/ root to import paths if not present
if (!importPaths.contains(srcMainRoot)) {
importPaths.add(0, srcMainRoot);
DebugSystem.debug("IMPORTS", "Added srcMainRoot to import paths: " + srcMainRoot);
}
this.demoSiblingRoot = null;
File srcMainDir = new File(srcMainRoot);
File srcDir = srcMainDir.getParentFile();
File srcHolder = srcDir != null ? srcDir.getParentFile() : null;
if (srcHolder != null && DEMO_DIR_NAME.equals(srcHolder.getName())) {
File siblingRoot = srcHolder.getParentFile();
if (siblingRoot != null) {
this.demoSiblingRoot = siblingRoot.getAbsolutePath();
if (!importPaths.contains(this.demoSiblingRoot)) {
importPaths.add(1, this.demoSiblingRoot);
DebugSystem.debug("IMPORTS", "Added demo sibling root to import paths: " + this.demoSiblingRoot);
}
}
}
// Set the project root for Index class (for src/bin/project.codc index location)
Index.setProjectRoot(srcMainRoot);
DebugSystem.debug("IMPORTS", "Set Index project root from: " + srcMainRoot);
// Calculate and store project root for IR manager
this.projectRoot = Index.getProjectRoot();
if (this.projectRoot != null) {
this.irManager = new IRManager(this.projectRoot);
DebugSystem.debug("IMPORTS", "Initialized IRManager with root: " + this.projectRoot);
}
} else {
DebugSystem.debug("IMPORTS", "Could not find src/main/ structure, imports will be relative to: " + currentFileDirectory);
}
DebugSystem.debug("IMPORTS", "Final configuration - srcMainRoot: " + srcMainRoot +
", currentFileDirectory: " + currentFileDirectory +
", importPaths: " + importPaths);
}
public String getCurrentFileDirectory() {
return currentFileDirectory;
}
public String getSrcMainRoot() {
return srcMainRoot;
}
public String getProjectRoot() {
return projectRoot;
}
/**
* Get absolute path for a unit
*/
private String getUnitPath(String unitName) {
validateUnitName(unitName);
String fallbackPath = buildUnitPath(srcMainRoot, unitName);
if (fallbackPath == null) {
fallbackPath = buildUnitPath("src/main", unitName);
}
if (fallbackPath != null) {
File primaryDir = new File(fallbackPath);
if (primaryDir.exists() && primaryDir.isDirectory()) {
return fallbackPath;
}
}
for (String basePath : importPaths) {
if (basePath == null || basePath.isEmpty()) {
continue;
}
String candidate = buildUnitPath(basePath, unitName);
File dir = new File(candidate);
if (dir.exists() && dir.isDirectory()) {
return candidate;
}
String overrideDir = STANDARD_UNIT_PATH_OVERRIDES.get(unitName);
if (overrideDir != null) {
String overrideCandidate = new File(basePath, overrideDir).getPath();
File override = new File(overrideCandidate);
if (override.exists() && override.isDirectory()) {
return overrideCandidate;
}
}
}
return fallbackPath;
}
private static String buildUnitPath(String basePath, String unitName) {
if (basePath == null || basePath.isEmpty()) {
return null;
}
return new File(basePath, toUnitDirectoryPath(unitName)).getPath();
}
private static String toUnitDirectoryPath(String unitName) {
return unitName.replace('.', '/');
}
private static Map<String, String> createStandardUnitPathOverrides() {
Map<String, String> overrides = new HashMap<String, String>();
overrides.put("math", "std/math");
overrides.put("json", "std/json");
overrides.put("scimath", "std/scimath");
overrides.put("scimath.distribution", "std/scimath/distribution");
return Collections.unmodifiableMap(overrides);
}
private static String toModuleMainFileName(String unitName) {
if (unitName == null || unitName.isEmpty()) {
return null;
}
int lastDot = unitName.lastIndexOf('.');
String simpleName = lastDot >= 0 ? unitName.substring(lastDot + 1) : unitName;
if (simpleName.isEmpty()) {
return null;
}
return Character.toUpperCase(simpleName.charAt(0)) + simpleName.substring(1);
}
private void validateUnitName(String unitName) {
if (unitName == null || unitName.isEmpty()) {
throw new IllegalArgumentException("Unit name cannot be null/empty");
}
if (!SAFE_UNIT_NAME_PATTERN.matcher(unitName).matches()) {
throw new ProgramError("Invalid import unit name: " + unitName);
}
}
private boolean isMatchingProgramUnit(Program program, String expectedUnitName) {
if (program == null || program.unit == null || program.unit.name == null) {
return false;
}
return expectedUnitName.equals(program.unit.name);
}
/**
* Get or create index for a unit (cached)
*/
private Index getIndex(String unitName) {
String timer = startPerfTimer(DebugSystem.Level.DEBUG, PERF_PREFIX + "getIndex");
try {
if (unitName == null || unitName.isEmpty()) {
return null;
}
// Check memory cache
if (indexCache.containsKey(unitName)) {
Index cached = indexCache.get(unitName);
String unitPath = getUnitPath(unitName);
if (!cached.isStale(unitPath)) {
indexCacheHits++;
DebugSystem.debug("IMPORTS_CACHE", "Index cache hit for unit: " + unitName);
return cached;
} else {
indexCache.remove(unitName);
DebugSystem.debug("IMPORTS_CACHE", "Index cache stale for unit: " + unitName);
}
}
indexCacheMisses++;
// Try to load from disk
Index index = Index.load(unitName);
if (index != null) {
String unitPath = getUnitPath(unitName);
if (!index.isStale(unitPath)) {
indexCache.put(unitName, index);
DebugSystem.debug("IMPORTS_CACHE", "Loaded index from disk for unit: " + unitName +
" (" + index.size() + " classes)");
return index;
} else {
DebugSystem.debug("IMPORTS_CACHE", "Index file stale for unit: " + unitName);
}
}
// Generate new index - this may throw IllegalStateException on duplicates
try {
index = generateIndex(unitName);
if (index != null && !index.isEmpty()) {
index.save();
indexCache.put(unitName, index);
DebugSystem.debug("IMPORTS_CACHE", "Generated new index for unit: " + unitName +
" (" + index.size() + " classes)");
}
return index;
} catch (IllegalStateException e) {
// Convert to ProgramError for user-friendly message
throw new ProgramError(e.getMessage());
}
} finally {
stopPerfTimer(timer);
}
}
/**
* Generate index by scanning unit directory
*/
private Index generateIndex(String unitName) {
String unitPath = getUnitPath(unitName);
if (unitPath == null) {
return null;
}
Index index = new Index(unitName);
if (index.refresh(unitPath)) {
return index;
}
return null;
}
private FileMetadata getFileMetadata(File file) {
String path = file.getAbsolutePath();
if (fileMetadataCache.containsKey(path)) {
FileMetadata cached = fileMetadataCache.get(path);
if (cached.isValid(file)) {
metadataCacheHits++;
return cached;
} else {
fileMetadataCache.remove(path);
}
}
metadataCacheMisses++;
boolean exists = file.exists();
boolean isDirectory = exists && file.isDirectory();
long lastModified = exists ? file.lastModified() : 0;
FileMetadata metadata = new FileMetadata(exists, isDirectory, lastModified);
fileMetadataCache.put(path, metadata);
return metadata;
}
private Program loadImportFromFileCached(String filePath) throws Exception {
String timer = startPerfTimer(DebugSystem.Level.DEBUG, PERF_PREFIX + "loadImportFromFileCached");
try {
if (filePath == null || filePath.isEmpty()) {
throw new InternalError("loadImportFromFileCached called with null/empty path");
}
File file = new File(filePath);
FileMetadata metadata = getFileMetadata(file);
if (!metadata.exists) {
return null;
}
if (!metadata.isDirectory) {
if (fileCache.containsKey(filePath)) {
CachedFileResult cached = fileCache.get(filePath);
if (cached.isValid(file)) {
fileCacheHits++;
DebugSystem.debug("IMPORTS_CACHE", "File cache hit: " + filePath);
return cached.program;
} else {
fileCache.remove(filePath);
DebugSystem.debug("IMPORTS_CACHE", "File cache stale: " + filePath);
}
}
fileCacheMisses++;
DebugSystem.debug("IMPORTS_CACHE", "File cache miss: " + filePath);
Program program = loadImportFromFile(filePath);
if (program != null) {
fileCache.put(filePath, new CachedFileResult(program, metadata.lastModified));
}
return program;
}
return null;
} finally {
stopPerfTimer(timer);
}
}
public void registerBroadcast(String packageName, String mainClassName) {
if (packageName == null || packageName.isEmpty()) {
throw new InternalError("registerBroadcast called with null/empty packageName");
}
if (mainClassName == null || mainClassName.isEmpty()) {
throw new InternalError("registerBroadcast called with null/empty mainClassName");
}
if (packageBroadcasts.containsKey(packageName)) {
String existing = packageBroadcasts.get(packageName);
if (!existing.equals(mainClassName)) {
throw new ProgramError(
"Broadcast conflict in package '" + packageName + "':\n" +
" Already declared: (main: " + existing + ")\n" +
" New declaration: (main: " + mainClassName + ")\n" +
"Only one broadcast per package allowed."
);
}
} else {
packageBroadcasts.put(packageName, mainClassName);
DebugSystem.debug("BROADCAST", "Registered broadcast for package '" +
packageName + "': (main: " + mainClassName + ")");
}
}
public String getBroadcast(String packageName) {
return packageBroadcasts.get(packageName);
}
public void clearBroadcasts() {
packageBroadcasts.clear();
}
public Policy findPolicy(String qualifiedPolicyName) {
if (qualifiedPolicyName == null || qualifiedPolicyName.isEmpty()) {
throw new InternalError("findPolicy called with null/empty name");
}
DebugSystem.debug("POLICY", "findPolicy called for: " + qualifiedPolicyName);
Policy cached = importedPolicies.get(qualifiedPolicyName);
if (cached != null) {
DebugSystem.debug("POLICY", "Policy already loaded: " + qualifiedPolicyName);
return cached;
}
synchronized (policyLookupLock) {
cached = importedPolicies.get(qualifiedPolicyName);
if (cached != null) {
DebugSystem.debug("POLICY", "Policy already loaded (post-lock): " + qualifiedPolicyName);
return cached;
}
int lastDot = qualifiedPolicyName.lastIndexOf('.');
String policyName;
String importName;
if (lastDot == -1) {
policyName = qualifiedPolicyName;
importName = qualifiedPolicyName;
} else {
policyName = qualifiedPolicyName.substring(lastDot + 1);
importName = qualifiedPolicyName.substring(0, lastDot);
}
DebugSystem.debug("POLICY", "Import part: '" + importName + "', policy: '" + policyName + "'");
String actualImportName = findMatchingImportCached(importName);
if (!loadedPrograms.containsKey(actualImportName)) {
try {
DebugSystem.debug("POLICY", "Import not loaded, attempting to load: " + actualImportName);
Program program = resolveImportAsProgram(actualImportName);
if (program == null) {
throw new ProgramError("Failed to load import: " + actualImportName);
}
} catch (ProgramError e) {
throw e;
} catch (Exception e) {
throw new InternalError("Unexpected error loading import: " + actualImportName, e);
}
}
Program program = loadedPrograms.get(actualImportName);
if (program != null && program.unit != null && program.unit.policies != null) {
for (Policy policy : program.unit.policies) {
if (policy.name.equals(policyName)) {
DebugSystem.debug("POLICY", "Found policy: " + policy.name);
importedPolicies.put(qualifiedPolicyName, policy);
policyToUnitMap.put(policyName, program.unit.name);
return policy;
}
}
}
throw new ProgramError(
"Policy not found: '" + qualifiedPolicyName + "'\n" +
"Available policies in import '" + actualImportName + "': " +
getPolicyNames(program)
);
}
}
private String getPolicyNames(Program program) {
if (program == null || program.unit == null || program.unit.policies == null) {
return "none";
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < program.unit.policies.size(); i++) {
if (i > 0) sb.append(", ");
sb.append(program.unit.policies.get(i).name);
}
return sb.toString();
}
public void registerPolicy(String qualifiedName, Policy policy) {
if (qualifiedName == null || qualifiedName.isEmpty()) {
throw new InternalError("registerPolicy called with null/empty qualifiedName");
}
if (policy == null) {
throw new InternalError("registerPolicy called with null policy");
}
importedPolicies.put(qualifiedName, policy);
DebugSystem.debug("POLICY", "Registered policy: " + qualifiedName);
if (!importedPolicies.containsKey(policy.name)) {
importedPolicies.put(policy.name, policy);
}
}
public String getPolicyUnit(String policyName) {
return policyToUnitMap.get(policyName);
}
public Set<String> getRegisteredPolicies() {
return importedPolicies.keySet();
}
public void addImportPath(String path) {
if (path == null || path.isEmpty()) {
throw new InternalError("addImportPath called with null/empty path");
}
importPaths.add(path);
DebugSystem.debug("IMPORTS", "Added import path: " + path);
}
public void registerImport(String importName) {
if (importName == null || importName.isEmpty()) {
throw new InternalError("registerImport called with null/empty importName");
}
if (importName.contains("(")) {
if (!methodImportSpecs.contains(importName)) {
methodImportSpecs.add(importName);
}
DebugSystem.debug("IMPORTS", "Registered method import spec: " + importName);
return;
}
if (importName.endsWith(".**")) {
String unitName = importName.substring(0, importName.length() - 3);
wildcardEverythingUnits.add(unitName);
DebugSystem.debug("IMPORTS", "Registered everything wildcard import: " + importName);
return;
}
if (importName.endsWith(".*")) {
String unitName = importName.substring(0, importName.length() - 2);
wildcardClassUnits.add(unitName);
DebugSystem.debug("IMPORTS", "Registered class wildcard import: " + importName);
return;
}
if (!importName.contains(".")) {
wildcardEverythingUnits.add(importName);
if (!registeredImports.contains(importName)) {
registeredImports.add(importName);
cacheImportName(importName);
}
DebugSystem.debug("IMPORTS", "Registered unit import as everything wildcard: " + importName);
return;
}
int lastDot = importName.lastIndexOf('.');
if (lastDot > 0 && lastDot < importName.length() - 1) {
String alias = importName.substring(lastDot + 1);
explicitFieldImports.put(alias, importName);
}
if (!registeredImports.contains(importName)) {
registeredImports.add(importName);
cacheImportName(importName);
DebugSystem.debug("IMPORTS", "Registered import (lazy): " + importName);
}
}
private void cacheImportName(String importName) {
String[] parts = importName.split("\\.");
if (parts.length > 0) {
String lastPart = parts[parts.length - 1];
if (!importNameCache.containsKey(lastPart)) {
importNameCache.put(lastPart, importName);
}
String lastPartLower = lastPart.toLowerCase(Locale.ENGLISH);
if (!importNameCache.containsKey(lastPartLower)) {
importNameCache.put(lastPartLower, importName);
}
StringBuilder partial = new StringBuilder();
for (int i = 0; i < parts.length; i++) {
if (i > 0) partial.append(".");
partial.append(parts[i]);
String key = partial.toString();
if (!importNameCache.containsKey(key)) {
importNameCache.put(key, importName);
}
String lowerKey = key.toLowerCase(Locale.ENGLISH);
if (!importNameCache.containsKey(lowerKey)) {
importNameCache.put(lowerKey, importName);
}
}
}
}
private String findMatchingImportCached(String calledImport) {
if (importNameCache.containsKey(calledImport)) {
String cached = importNameCache.get(calledImport);
DebugSystem.debug("IMPORTS", "Cache hit for import: " + calledImport + " -> " + cached);
return cached;
}
String calledImportLower = calledImport.toLowerCase(Locale.ENGLISH);
if (importNameCache.containsKey(calledImportLower)) {
String cached = importNameCache.get(calledImportLower);
DebugSystem.debug("IMPORTS", "Case-insensitive cache hit for import: " + calledImport + " -> " + cached);
return cached;
}
for (String loadedImport : loadedPrograms.keySet()) {
if (loadedImport.endsWith("." + calledImport) || loadedImport.equals(calledImport)
|| loadedImport.endsWith("." + calledImportLower)
|| loadedImport.equalsIgnoreCase(calledImport)) {
importNameCache.put(calledImport, loadedImport);
importNameCache.put(calledImportLower, loadedImport);
return loadedImport;
}
}
for (String registeredImport : registeredImports) {
if (registeredImport.endsWith("." + calledImport) || registeredImport.equals(calledImport)
|| registeredImport.endsWith("." + calledImportLower)
|| registeredImport.equalsIgnoreCase(calledImport)) {
importNameCache.put(calledImport, registeredImport);
importNameCache.put(calledImportLower, registeredImport);
return registeredImport;
}
}
for (String wildcardUnit : wildcardEverythingUnits) {
if (wildcardUnit.equalsIgnoreCase(calledImport)) {
importNameCache.put(calledImport, wildcardUnit);
importNameCache.put(calledImportLower, wildcardUnit);
return wildcardUnit;
}
}
return calledImport;
}
/**
* Resolve import and return Type directly
*/
public Type resolveImport(String importName) throws Exception {
String timer = startPerfTimer(DebugSystem.Level.DEBUG, PERF_PREFIX + "resolveImport");
try {
if (importName == null || importName.isEmpty()) {
throw new InternalError("resolveImport called with null/empty importName");
}
DebugSystem.debug("IMPORTS", "=== RESOLVING IMPORT: " + importName + " ===");
// Check cache first
if (loadedTypes.containsKey(importName)) {
DebugSystem.debug("IMPORTS", "Type already loaded: " + importName);
return loadedTypes.get(importName);
}
int lastDot = importName.lastIndexOf('.');
if (lastDot <= 0 || lastDot >= importName.length() - 1) {
throw new ProgramError(
"Invalid import format: '" + importName + "'\n" +
"Expected format: unit.Class (e.g., sample.Imported, internal.range.RangeSpec)"
);
}
String unitName = importName.substring(0, lastDot);
String className = importName.substring(lastDot + 1);
DebugSystem.debug("IMPORTS", "Unit: " + unitName + ", Class: " + className);
// ========== TRY CODE-P-TAC ARTIFACT FIRST (FAST PATH) ==========
if (irManager != null) {
Artifact artifact = irManager.loadArtifact(unitName, className);
if (artifact != null) {
bytecodeCacheHits++;
DebugSystem.debug("IR", "Loaded " + className + " CodP-TAC artifact from .codc/.codb (cache hit)");
loadedArtifacts.put(importName, artifact);
if (artifact.typeSnapshot != null) {
Type snapshot = artifact.typeSnapshot;
boolean snapshotHasMembers =
(snapshot.methods != null && !snapshot.methods.isEmpty())
|| (snapshot.fields != null && !snapshot.fields.isEmpty())
|| (snapshot.constructors != null && !snapshot.constructors.isEmpty());
if (snapshotHasMembers) {
loadedTypes.put(importName, snapshot);
return snapshot;
}
DebugSystem.debug("IR",
"Artifact snapshot for " + className + " has no members; falling back to source/index resolution");
}
} else {
bytecodeCacheMisses++;
DebugSystem.debug("IR", ".codc/.codb artifact not found for " + className + " (cache miss)");
}
}
// ========== END CodP-TAC CHECK ==========
// Try to get index (fast path for source)
Index index = getIndex(unitName);
if (index != null) {
String fileName = index.getFile(className);
if (fileName != null) {
String filePath = getUnitPath(unitName) + "/" + fileName;
DebugSystem.debug("IMPORTS", "Found class '" + className + "' in '" + fileName + "' via index");
Program program = loadImportFromFileCached(filePath);
if (program != null) {
if (!isMatchingProgramUnit(program, unitName)) {
DebugSystem.debug("IMPORTS",
"Skipping indexed file due to unit mismatch for '" + importName +
"': expected '" + unitName + "', found '" +
(program.unit != null ? program.unit.name : "null") + "'");
} else {
// Extract the Type from the program
for (Type type : program.unit.types) {
if (type.name.equals(className)) {
// Save IR for next time
if (irManager != null) {
irManager.save(unitName, type);
DebugSystem.debug("IR", "Saved " + className + " to .codc/.codb");
}
loadedTypes.put(importName, type);
return type;
}
}
}
}
}
// Class not found in index
throw new ProgramError(
"Class '" + className + "' not found in unit '" + unitName + "'\n" +
"Available classes: " + index.getClassNames()
);
}
// Fallback to directory scanning (slow path)
DebugSystem.debug("IMPORTS", "No index found, scanning directory for unit: " + unitName);
return resolveImportByScan(importName, unitName, className);
} finally {
stopPerfTimer(timer);
}
}
/**
* Legacy method for Program resolution (for policies, etc.)
*/
public Program resolveImportAsProgram(String importName) throws Exception {
String timer = startPerfTimer(DebugSystem.Level.DEBUG, PERF_PREFIX + "resolveImportAsProgram");
try {
if (importName == null || importName.isEmpty()) {
throw new InternalError("resolveImportAsProgram called with null/empty importName");
}
// Check if already loaded
if (loadedPrograms.containsKey(importName)) {
return loadedPrograms.get(importName);
}
// Check preloaded imports
if (preloadedImports.containsKey(importName)) {
Program program = preloadedImports.get(importName);
if (program != null) {
loadedPrograms.put(importName, program);
importedUnits.put(importName, program);
cacheImportName(importName);
registerPoliciesAndBroadcast(program, importName);
return program;
}
}
// Resolve as Type first, then wrap
Type type = resolveImport(importName);
if (type != null) {
Program program = ASTFactory.createProgram();
program.unit = ASTFactory.createUnit("default", null);
program.unit.types.add(type);
loadedPrograms.put(importName, program);
return program;
}
return null;
} finally {
stopPerfTimer(timer);
}
}
/**
* Fallback: resolve import by scanning directory (slow path)
*/
private Type resolveImportByScan(String importName, String unitName, String className) throws Exception {
validateUnitName(unitName);
String dirPath = unitName.replace('.', '/');
DebugSystem.debug("IMPORTS", "Scanning for: " + dirPath);
List<String> pathsToTry = new ArrayList<String>();
if (srcMainRoot != null) {
pathsToTry.add(srcMainRoot + "/" + dirPath);
pathsToTry.add(srcMainRoot + "/" + dirPath + ".cod");
}
if (currentFileDirectory != null &&
(srcMainRoot == null || !currentFileDirectory.equals(srcMainRoot))) {
pathsToTry.add(currentFileDirectory + "/" + dirPath);
pathsToTry.add(currentFileDirectory + "/" + dirPath + ".cod");
}
for (String basePath : importPaths) {
if (basePath == null || basePath.isEmpty()) continue;
if (srcMainRoot != null && basePath.equals(srcMainRoot)) continue;
pathsToTry.add(basePath + "/" + dirPath);
pathsToTry.add(basePath + "/" + dirPath + ".cod");
}
String unitDirPath = getUnitPath(unitName);
if (unitDirPath != null) {
pathsToTry.add(unitDirPath + File.separator + className + ".cod");
String moduleMainFileName = toModuleMainFileName(unitName);
if (moduleMainFileName != null) {
pathsToTry.add(unitDirPath + File.separator + moduleMainFileName + ".cod");
}
}
pathsToTry.add(dirPath);
pathsToTry.add(dirPath + ".cod");
List<String> attemptedPaths = new ArrayList<String>();
for (String fullPath : pathsToTry) {
if (fullPath == null) continue;
File file = new File(fullPath);
String absolutePath = file.getAbsolutePath();
attemptedPaths.add(absolutePath);
DebugSystem.debug("IMPORTS", "Checking: " + absolutePath);
if (file.exists() && file.isFile()) {
DebugSystem.debug("IMPORTS", "FOUND import at: " + absolutePath);
try {
Program program = loadImportFromFileCached(absolutePath);
if (program != null) {
if (!isMatchingProgramUnit(program, unitName)) {
DebugSystem.debug("IMPORTS",
"Skipping unit mismatch at " + absolutePath +
": expected '" + unitName + "', found '" +
(program.unit != null ? program.unit.name : "null") + "'");
continue;
}
// Extract the Type
for (Type type : program.unit.types) {
if (type.name.equals(className)) {
// Generate index for future use
Index index = generateIndex(unitName);
if (index != null && !index.isEmpty()) {
index.save();
indexCache.put(unitName, index);
}
// Save IR
if (irManager != null) {
irManager.save(unitName, type);
DebugSystem.debug("IR", "Saved " + className + " to .codc/.codb");
}
loadedTypes.put(importName, type);
return type;
}
}
}
} catch (Exception e) {
DebugSystem.debug("IMPORTS", "Failed to load from " + absolutePath + ": " + e.getMessage());
}
}
}
StringBuilder errorMsg = new StringBuilder();
errorMsg.append("Import not found: ").append(importName).append("\n");
errorMsg.append("Searched in:\n");
Set<String> uniquePaths = new LinkedHashSet<String>(attemptedPaths);
for (String path : uniquePaths) {
errorMsg.append(" - ").append(path).append("\n");
}
errorMsg.append("\nExpected structure: ").append(dirPath).append("/ (with .cod files)\n");
errorMsg.append("Or file: ").append(dirPath).append(".cod\n");
if (srcMainRoot != null) {
errorMsg.append("\nDetected src/main/ root: ").append(srcMainRoot).append("\n");
}
if (currentFileDirectory != null) {
errorMsg.append("Current file directory: ").append(currentFileDirectory).append("\n");