Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 4bc371272d24e8171926bcc5afddef4636151360 (plain) (blame)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
/*******************************************************************************
 * Copyright (c) 2000, 2016 IBM Corporation and others.
 *
 * This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License 2.0
 * which accompanies this distribution, and is available at
 * https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *     Stephan Herrmann - contribution for bug 337868 - [compiler][model] incomplete support for package-info.java when using SearchableEnvironment
 *******************************************************************************/
package org.eclipse.jdt.internal.core;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.jdt.core.*;
import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.core.search.*;
import org.eclipse.jdt.internal.codeassist.ISearchRequestor;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
import org.eclipse.jdt.internal.compiler.env.AccessRestriction;
import org.eclipse.jdt.internal.compiler.env.IBinaryType;
import org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
import org.eclipse.jdt.internal.compiler.env.IModule;
import org.eclipse.jdt.internal.compiler.env.IModule.IModuleReference;
import org.eclipse.jdt.internal.compiler.env.IModule.IPackageExport;
import org.eclipse.jdt.internal.compiler.env.IModuleAwareNameEnvironment;
import org.eclipse.jdt.internal.compiler.env.ISourceType;
import org.eclipse.jdt.internal.compiler.env.IUpdatableModule;
import org.eclipse.jdt.internal.compiler.env.NameEnvironmentAnswer;
import org.eclipse.jdt.internal.compiler.env.IUpdatableModule.UpdateKind;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.eclipse.jdt.internal.compiler.lookup.ModuleBinding;
import org.eclipse.jdt.internal.compiler.lookup.TypeConstants;
import org.eclipse.jdt.internal.core.NameLookup.Answer;
import org.eclipse.jdt.internal.core.search.BasicSearchEngine;
import org.eclipse.jdt.internal.core.search.IRestrictedAccessConstructorRequestor;
import org.eclipse.jdt.internal.core.search.IRestrictedAccessTypeRequestor;
import org.eclipse.jdt.internal.core.search.indexing.IndexManager;
import org.eclipse.jdt.internal.core.search.processing.IJob;
import org.eclipse.jdt.internal.core.util.Util;

/**
 *	This class provides a <code>SearchableBuilderEnvironment</code> for code assist which
 *	uses the Java model as a search tool.
 */
public class SearchableEnvironment
	implements IModuleAwareNameEnvironment, IJavaSearchConstants {

	public NameLookup nameLookup;
	protected ICompilationUnit unitToSkip;
	protected org.eclipse.jdt.core.ICompilationUnit[] workingCopies;
	protected WorkingCopyOwner owner;

	protected JavaProject project;
	protected IJavaSearchScope searchScope;

	protected boolean checkAccessRestrictions;
	// moduleName -> IPackageFragmentRoot[](lazily populated)
	private Map<String,IPackageFragmentRoot[]> knownModuleLocations; // null indicates: not using JPMS
	private boolean excludeTestCode;

	private ModuleUpdater moduleUpdater;
	private Map<IPackageFragmentRoot,IModuleDescription> rootToModule;

	@Deprecated
	public SearchableEnvironment(JavaProject project, org.eclipse.jdt.core.ICompilationUnit[] workingCopies) throws JavaModelException {
		this(project, workingCopies, false);
	}
	/**
	 * Creates a SearchableEnvironment on the given project
	 */
	public SearchableEnvironment(JavaProject project, org.eclipse.jdt.core.ICompilationUnit[] workingCopies, boolean excludeTestCode) throws JavaModelException {
		this.project = project;
		this.excludeTestCode = excludeTestCode;
		this.checkAccessRestrictions =
			!JavaCore.IGNORE.equals(project.getOption(JavaCore.COMPILER_PB_FORBIDDEN_REFERENCE, true))
			|| !JavaCore.IGNORE.equals(project.getOption(JavaCore.COMPILER_PB_DISCOURAGED_REFERENCE, true));
		this.workingCopies = workingCopies;
		this.nameLookup = project.newNameLookup(workingCopies, excludeTestCode);
		if (CompilerOptions.versionToJdkLevel(project.getOption(JavaCore.COMPILER_COMPLIANCE, true)) >= ClassFileConstants.JDK9) {
			this.knownModuleLocations = new HashMap<>();
		}
		if (CompilerOptions.versionToJdkLevel(project.getOption(JavaCore.COMPILER_COMPLIANCE, true)) >= ClassFileConstants.JDK9) {
			this.moduleUpdater = new ModuleUpdater(project);
			if (!excludeTestCode) {
				IClasspathEntry[] expandedClasspath = project.getExpandedClasspath();
				if(Arrays.stream(expandedClasspath).anyMatch(e -> e.isTest())) {
					this.moduleUpdater.addReadUnnamedForNonEmptyClasspath(project, expandedClasspath);
				}
			}
			for (IClasspathEntry entry : project.getRawClasspath())
				if(!excludeTestCode || !entry.isTest())
					this.moduleUpdater.computeModuleUpdates(entry);
		}
	}
	/**
	 * Creates a SearchableEnvironment on the given project
	 */
	public SearchableEnvironment(JavaProject project, WorkingCopyOwner owner, boolean excludeTestCode) throws JavaModelException {
		this(project, owner == null ? null : JavaModelManager.getJavaModelManager().getWorkingCopies(owner, true/*add primary WCs*/), excludeTestCode);
		this.owner = owner;
	}

	private static int convertSearchFilterToModelFilter(int searchFilter) {
		switch (searchFilter) {
			case IJavaSearchConstants.CLASS:
				return NameLookup.ACCEPT_CLASSES;
			case IJavaSearchConstants.INTERFACE:
				return NameLookup.ACCEPT_INTERFACES;
			case IJavaSearchConstants.ENUM:
				return NameLookup.ACCEPT_ENUMS;
			case IJavaSearchConstants.ANNOTATION_TYPE:
				return NameLookup.ACCEPT_ANNOTATIONS;
			case IJavaSearchConstants.CLASS_AND_ENUM:
				return NameLookup.ACCEPT_CLASSES | NameLookup.ACCEPT_ENUMS;
			case IJavaSearchConstants.CLASS_AND_INTERFACE:
				return NameLookup.ACCEPT_CLASSES | NameLookup.ACCEPT_INTERFACES;
			default:
				return NameLookup.ACCEPT_ALL;
		}
	}
	/**
	 * Returns the given type in the the given package if it exists,
	 * otherwise <code>null</code>.
	 */
	protected NameEnvironmentAnswer find(String typeName, String packageName, IPackageFragmentRoot[] moduleContext) {
		if (packageName == null)
			packageName = IPackageFragment.DEFAULT_PACKAGE_NAME;
		if (this.owner != null) {
			String source = this.owner.findSource(typeName, packageName);
			if (source != null) {
				IJavaElement moduleElement = (moduleContext != null && moduleContext.length > 0) ? moduleContext[0] : null;
				ICompilationUnit cu = new BasicCompilationUnit(
						source.toCharArray(),
						CharOperation.splitOn('.', packageName.toCharArray()),
						typeName + Util.defaultJavaExtension(),
						moduleElement);
				return new NameEnvironmentAnswer(cu, null);
			}
		}
		NameLookup.Answer answer =
			this.nameLookup.findType(
				typeName,
				packageName,
				false/*exact match*/,
				NameLookup.ACCEPT_ALL,
				this.checkAccessRestrictions,
				moduleContext);
		if (answer != null) {
			// construct name env answer
			if (answer.type instanceof BinaryType) { // BinaryType
				try {
					char[] moduleName = answer.module != null ? answer.module.getElementName().toCharArray() : null;
					return new NameEnvironmentAnswer((IBinaryType) ((BinaryType) answer.type).getElementInfo(), answer.restriction, moduleName);
				} catch (JavaModelException npe) {
					// fall back to using owner
				}
			} else { //SourceType
				try {
					// retrieve the requested type
					SourceTypeElementInfo sourceType = (SourceTypeElementInfo)((SourceType) answer.type).getElementInfo();
					ISourceType topLevelType = sourceType;
					while (topLevelType.getEnclosingType() != null) {
						topLevelType = topLevelType.getEnclosingType();
					}
					// find all siblings (other types declared in same unit, since may be used for name resolution)
					IType[] types = sourceType.getHandle().getCompilationUnit().getTypes();
					ISourceType[] sourceTypes = new ISourceType[types.length];

					// in the resulting collection, ensure the requested type is the first one
					sourceTypes[0] = sourceType;
					int length = types.length;
					for (int i = 0, index = 1; i < length; i++) {
						ISourceType otherType =
							(ISourceType) ((JavaElement) types[i]).getElementInfo();
						if (!otherType.equals(topLevelType) && index < length) // check that the index is in bounds (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=62861)
							sourceTypes[index++] = otherType;
					}
					char[] moduleName = answer.module != null ? answer.module.getElementName().toCharArray() : null;
					return new NameEnvironmentAnswer(sourceTypes, answer.restriction, getExternalAnnotationPath(answer.entry), moduleName);
				} catch (JavaModelException jme) {
					if (jme.isDoesNotExist() && String.valueOf(TypeConstants.PACKAGE_INFO_NAME).equals(typeName)) {
						// in case of package-info.java the type doesn't exist in the model,
						// but the CU may still help in order to fetch package level annotations.
						return new NameEnvironmentAnswer((ICompilationUnit)answer.type.getParent(), answer.restriction);
					}
					// no usable answer
				}
			}
		}
		return null;
	}

	private String getExternalAnnotationPath(IClasspathEntry entry) {
		if (entry == null)
			return null;
		IPath path = ClasspathEntry.getExternalAnnotationPath(entry, this.project.getProject(), true);
		if (path == null)
			return null;
		return path.toOSString();
	}

	/**
	 * Find the modules that start with the given prefix.
	 * A valid prefix is a qualified name separated by periods
	 * (ex. java.util).
	 * The packages found are passed to:
	 *    ISearchRequestor.acceptModule(char[][] moduleName)
	 */
	public void findModules(char[] prefix, ISearchRequestor requestor, IJavaProject javaProject) {
		this.nameLookup.seekModule(prefix, true, new SearchableEnvironmentRequestor(requestor));
	}

	/**
	 * Find the packages that start with the given prefix.
	 * A valid prefix is a qualified name separated by periods
	 * (ex. java.util).
	 * The packages found are passed to:
	 *    ISearchRequestor.acceptPackage(char[][] packageName)
	 */
	public void findPackages(char[] prefix, ISearchRequestor requestor) {
		this.nameLookup.seekPackageFragments(
			new String(prefix),
			true,
			new SearchableEnvironmentRequestor(requestor));
	}

	/**
	 * Find the packages that start with the given prefix and belong to the given module.
	 * A valid prefix is a qualified name separated by periods
	 * (ex. java.util).
	 * The packages found are passed to:
	 *    ISearchRequestor.acceptPackage(char[][] packageName)
	 */
	public void findPackages(char[] prefix, ISearchRequestor requestor, IPackageFragmentRoot[] moduleContext, boolean followRequires) {
		this.nameLookup.seekPackageFragments(
			new String(prefix),
			true,
			new SearchableEnvironmentRequestor(requestor), moduleContext);
	if (followRequires && this.knownModuleLocations != null) {
		try {
			boolean isMatchAllPrefix = CharOperation.equals(CharOperation.ALL_PREFIX, prefix);
			Set<IModuleDescription> modDescs = new HashSet<>();
			for (IPackageFragmentRoot root : moduleContext) {
				IModuleDescription desc = root.getJavaProject().getModuleDescription();
				if (desc instanceof AbstractModule)
					modDescs.add(desc);
			}
			for (IModuleDescription md : modDescs) {
				IModuleReference[] reqModules = ((AbstractModule) md).getRequiredModules();
				char[] modName = md.getElementName().toCharArray();
				for (IModuleReference moduleReference : reqModules) {
					findPackagesFromRequires(prefix, isMatchAllPrefix, requestor, moduleReference, modName);
				}
			}
		} catch (JavaModelException e) {
			// silent
		}
	}
}

private void findPackagesFromRequires(char[] prefix, boolean isMatchAllPrefix, ISearchRequestor requestor, IModuleReference moduleReference, char[] clientModuleName) {
	IPackageFragmentRoot[] fragmentRoots = findModuleContext(moduleReference.name());
	if (fragmentRoots == null) return;
	for (IPackageFragmentRoot root : fragmentRoots) {
		IJavaProject requiredProject = root.getJavaProject();
		try {
			IModuleDescription module = requiredProject.getModuleDescription();
			if (module instanceof AbstractModule) {
				AbstractModule requiredModule = (AbstractModule) module;
				for (IPackageExport packageExport : requiredModule.getExportedPackages()) {
					if (!packageExport.isQualified() || CharOperation.containsEqual(packageExport.targets(), clientModuleName)) {
						char[] exportName = packageExport.name();
						if (isMatchAllPrefix || CharOperation.prefixEquals(prefix, exportName))
							requestor.acceptPackage(exportName);
					}
				}
				for (IModuleReference moduleRef2 : requiredModule.getRequiredModules()) {
					if (moduleRef2.isTransitive())
						findPackagesFromRequires(prefix, isMatchAllPrefix, requestor, moduleRef2, clientModuleName);
				}
			}
		} catch (JavaModelException e) {
			// silent
		}
	}
}
	/**
	 * Find the top-level types that are defined
	 * in the current environment and whose simple name matches the given name.
	 *
	 * The types found are passed to one of the following methods (if additional
	 * information is known about the types):
	 *    ISearchRequestor.acceptType(char[][] packageName, char[] typeName)
	 *    ISearchRequestor.acceptClass(char[][] packageName, char[] typeName, int modifiers)
	 *    ISearchRequestor.acceptInterface(char[][] packageName, char[] typeName, int modifiers)
	 *
	 * This method can not be used to find member types... member
	 * types are found relative to their enclosing type.
	 */
	public void findExactTypes(char[] name, final boolean findMembers, int searchFor, final ISearchRequestor storage) {

		try {
			final String excludePath;
			if (this.unitToSkip != null) {
				if (!(this.unitToSkip instanceof IJavaElement)) {
					// revert to model investigation
					findExactTypes(
						new String(name),
						storage,
						convertSearchFilterToModelFilter(searchFor));
					return;
				}
				excludePath = ((IJavaElement) this.unitToSkip).getPath().toString();
			} else {
				excludePath = null;
			}

			IProgressMonitor progressMonitor = new IProgressMonitor() {
				boolean isCanceled = false;
				@Override
				public void beginTask(String n, int totalWork) {
					// implements interface method
				}
				@Override
				public void done() {
					// implements interface method
				}
				@Override
				public void internalWorked(double work) {
					// implements interface method
				}
				@Override
				public boolean isCanceled() {
					return this.isCanceled;
				}
				@Override
				public void setCanceled(boolean value) {
					this.isCanceled = value;
				}
				@Override
				public void setTaskName(String n) {
					// implements interface method
				}
				@Override
				public void subTask(String n) {
					// implements interface method
				}
				@Override
				public void worked(int work) {
					// implements interface method
				}
			};
			IRestrictedAccessTypeRequestor typeRequestor = new IRestrictedAccessTypeRequestor() {
				@Override
				public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path, AccessRestriction access) {
					if (excludePath != null && excludePath.equals(path))
						return;
					if (!findMembers && enclosingTypeNames != null && enclosingTypeNames.length > 0)
						return; // accept only top level types
					storage.acceptType(packageName, simpleTypeName, enclosingTypeNames, modifiers, access);
				}
			};
			try {
				new BasicSearchEngine(this.workingCopies).searchAllTypeNames(
					null,
					SearchPattern.R_EXACT_MATCH,
					name,
					SearchPattern.R_EXACT_MATCH,
					searchFor,
					getSearchScope(),
					typeRequestor,
					CANCEL_IF_NOT_READY_TO_SEARCH,
					progressMonitor);
			} catch (OperationCanceledException e) {
				findExactTypes(
					new String(name),
					storage,
					convertSearchFilterToModelFilter(searchFor));
			}
		} catch (JavaModelException e) {
			findExactTypes(
				new String(name),
				storage,
				convertSearchFilterToModelFilter(searchFor));
		}
	}

	/**
	 * Returns all types whose simple name matches with the given <code>name</code>.
	 */
	private void findExactTypes(String name, ISearchRequestor storage, int type) {
		SearchableEnvironmentRequestor requestor =
			new SearchableEnvironmentRequestor(storage, this.unitToSkip, this.project, this.nameLookup);
		this.nameLookup.seekTypes(name, null, false, type, requestor);
	}

	/**
	 * Find a type in the given module or any module read by it.
	 * Does not check accessibility / unique visibility, but returns the first observable type found.
	 * @param compoundTypeName name of the sought type
	 * @param module start into the module graph
	 * @return the answer :)
	 */
	public NameEnvironmentAnswer findTypeInModules(char[][] compoundTypeName, ModuleBinding module) {
		char[] nameForLookup = module.nameForLookup();
		NameEnvironmentAnswer answer = findType(compoundTypeName, nameForLookup);
		if (answer != null)
			return answer;
		if (LookupStrategy.get(nameForLookup) == LookupStrategy.Named) {
			for (ModuleBinding required : module.getAllRequiredModules()) {
				answer = findType(compoundTypeName, required.nameForLookup());
				if (answer != null)
					return answer;
			}
		}
		return null;
	}

	/**
	 * @see org.eclipse.jdt.internal.compiler.env.IModuleAwareNameEnvironment#findType(char[][],char[])
	 */
	@Override
	public NameEnvironmentAnswer findType(char[][] compoundTypeName, char[] moduleName) {
		if (compoundTypeName == null) return null;

		boolean isNamedStrategy = LookupStrategy.get(moduleName) == LookupStrategy.Named;
		IPackageFragmentRoot[] moduleLocations = isNamedStrategy ? findModuleContext(moduleName) : null;

		int length = compoundTypeName.length;
		if (length <= 1) {
			if (length == 0) return null;
			return find(new String(compoundTypeName[0]), null, moduleLocations);
		}

		int lengthM1 = length - 1;
		char[][] packageName = new char[lengthM1][];
		System.arraycopy(compoundTypeName, 0, packageName, 0, lengthM1);

		return find(
			new String(compoundTypeName[lengthM1]),
			CharOperation.toString(packageName),
			moduleLocations);
	}

	/**
	 * @see org.eclipse.jdt.internal.compiler.env.IModuleAwareNameEnvironment#findType(char[],char[][],char[])
	 */
	@Override
	public NameEnvironmentAnswer findType(char[] name, char[][] packageName, char[] moduleName) {
		if (name == null) return null;

		boolean isNamedStrategy = LookupStrategy.get(moduleName) == LookupStrategy.Named;
		IPackageFragmentRoot[] moduleLocations = isNamedStrategy ? findModuleContext(moduleName) : null;
		return find(
			new String(name),
			packageName == null || packageName.length == 0 ? null : CharOperation.toString(packageName),
			moduleLocations);
	}

	/**
	 * Find the top-level types that are defined
	 * in the current environment and whose name starts with the
	 * given prefix. The prefix is a qualified name separated by periods
	 * or a simple name (ex. java.util.V or V).
	 *
	 * The types found are passed to one of the following methods (if additional
	 * information is known about the types):
	 *    ISearchRequestor.acceptType(char[][] packageName, char[] typeName)
	 *    ISearchRequestor.acceptClass(char[][] packageName, char[] typeName, int modifiers)
	 *    ISearchRequestor.acceptInterface(char[][] packageName, char[] typeName, int modifiers)
	 *
	 * This method can not be used to find member types... member
	 * types are found relative to their enclosing type.
	 */
	public void findTypes(char[] prefix, final boolean findMembers, boolean camelCaseMatch, int searchFor, final ISearchRequestor storage) {
		findTypes(prefix, findMembers, camelCaseMatch, searchFor, storage, null);
	}
	/**
	 * Must be used only by CompletionEngine.
	 * The progress monitor is used to be able to cancel completion operations
	 * 
	 * Find the top-level types that are defined
	 * in the current environment and whose name starts with the
	 * given prefix. The prefix is a qualified name separated by periods
	 * or a simple name (ex. java.util.V or V).
	 *
	 * The types found are passed to one of the following methods (if additional
	 * information is known about the types):
	 *    ISearchRequestor.acceptType(char[][] packageName, char[] typeName)
	 *    ISearchRequestor.acceptClass(char[][] packageName, char[] typeName, int modifiers)
	 *    ISearchRequestor.acceptInterface(char[][] packageName, char[] typeName, int modifiers)
	 *
	 * This method can not be used to find member types... member
	 * types are found relative to their enclosing type.
	 */
	public void findTypes(char[] prefix, final boolean findMembers, boolean camelCaseMatch, int searchFor, final ISearchRequestor storage, IProgressMonitor monitor) {
		
		/*
			if (true){
				findTypes(new String(prefix), storage, NameLookup.ACCEPT_CLASSES | NameLookup.ACCEPT_INTERFACES);
				return;
			}
		*/
		try {
			final String excludePath;
			if (this.unitToSkip != null) {
				if (!(this.unitToSkip instanceof IJavaElement)) {
					// revert to model investigation
					findTypes(
						new String(prefix),
						storage,
						convertSearchFilterToModelFilter(searchFor));
					return;
				}
				excludePath = ((IJavaElement) this.unitToSkip).getPath().toString();
			} else {
				excludePath = null;
			}
			int lastDotIndex = CharOperation.lastIndexOf('.', prefix);
			char[] qualification, simpleName;
			if (lastDotIndex < 0) {
				qualification = null;
				if (camelCaseMatch) {
					simpleName = prefix;
				} else {
					simpleName = CharOperation.toLowerCase(prefix);
				}
			} else {
				qualification = CharOperation.subarray(prefix, 0, lastDotIndex);
				if (camelCaseMatch) {
					simpleName = CharOperation.subarray(prefix, lastDotIndex + 1, prefix.length);
				} else {
					simpleName =
						CharOperation.toLowerCase(
							CharOperation.subarray(prefix, lastDotIndex + 1, prefix.length));
				}
			}

			IProgressMonitor progressMonitor = new IProgressMonitor() {
				boolean isCanceled = false;
				@Override
				public void beginTask(String name, int totalWork) {
					// implements interface method
				}
				@Override
				public void done() {
					// implements interface method
				}
				@Override
				public void internalWorked(double work) {
					// implements interface method
				}
				@Override
				public boolean isCanceled() {
					return this.isCanceled;
				}
				@Override
				public void setCanceled(boolean value) {
					this.isCanceled = value;
				}
				@Override
				public void setTaskName(String name) {
					// implements interface method
				}
				@Override
				public void subTask(String name) {
					// implements interface method
				}
				@Override
				public void worked(int work) {
					// implements interface method
				}
			};
			IRestrictedAccessTypeRequestor typeRequestor = new IRestrictedAccessTypeRequestor() {
				@Override
				public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path, AccessRestriction access) {
					if (excludePath != null && excludePath.equals(path))
						return;
					if (!findMembers && enclosingTypeNames != null && enclosingTypeNames.length > 0)
						return; // accept only top level types
					storage.acceptType(packageName, simpleTypeName, enclosingTypeNames, modifiers, access);
				}
			};
			
			int matchRule = SearchPattern.R_PREFIX_MATCH;
			if (camelCaseMatch) matchRule |= SearchPattern.R_CAMELCASE_MATCH;
			if (monitor != null) {
				IndexManager indexManager = JavaModelManager.getIndexManager();
				if (indexManager.awaitingJobsCount() == 0) {
					// indexes were already there, so perform an immediate search to avoid any index rebuilt
					new BasicSearchEngine(this.workingCopies).searchAllTypeNames(
						qualification,
						SearchPattern.R_EXACT_MATCH,
						simpleName,
						matchRule, // not case sensitive
						searchFor,
						getSearchScope(),
						typeRequestor,
						FORCE_IMMEDIATE_SEARCH,
						progressMonitor);
				} else {
					// indexes were not ready, give the indexing a chance to finish small jobs by sleeping 100ms...
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						// Do nothing
					}
					if (monitor.isCanceled()) {
						throw new OperationCanceledException();
					}
					if (indexManager.awaitingJobsCount() == 0) {
						// indexes are now ready, so perform an immediate search to avoid any index rebuilt
						new BasicSearchEngine(this.workingCopies).searchAllTypeNames(
							qualification,
							SearchPattern.R_EXACT_MATCH,
							simpleName,
							matchRule, // not case sensitive
							searchFor,
							getSearchScope(),
							typeRequestor,
							FORCE_IMMEDIATE_SEARCH,
							progressMonitor);
					} else {
						// Indexes are still not ready, so look for types in the model instead of a search request
						findTypes(
							new String(prefix),
							storage,
							convertSearchFilterToModelFilter(searchFor));
					}
				}
			} else {
				try {
					new BasicSearchEngine(this.workingCopies).searchAllTypeNames(
						qualification,
						SearchPattern.R_EXACT_MATCH,
						simpleName,
						matchRule, // not case sensitive
						searchFor,
						getSearchScope(),
						typeRequestor,
						CANCEL_IF_NOT_READY_TO_SEARCH,
						progressMonitor);
				} catch (OperationCanceledException e) {
					findTypes(
						new String(prefix),
						storage,
						convertSearchFilterToModelFilter(searchFor));
				}
			}
		} catch (JavaModelException e) {
			findTypes(
				new String(prefix),
				storage,
				convertSearchFilterToModelFilter(searchFor));
		}
	}
	
	/**
	 * Must be used only by CompletionEngine.
	 * The progress monitor is used to be able to cancel completion operations
	 * 
	 * Find constructor declarations that are defined
	 * in the current environment and whose name starts with the
	 * given prefix. The prefix is a qualified name separated by periods
	 * or a simple name (ex. java.util.V or V).
	 *
	 * The constructors found are passed to one of the following methods:
	 *    ISearchRequestor.acceptConstructor(...)
	 */
	public void findConstructorDeclarations(char[] prefix, boolean camelCaseMatch, final ISearchRequestor storage, IProgressMonitor monitor) {
		try {
			final String excludePath;
			if (this.unitToSkip != null && this.unitToSkip instanceof IJavaElement) {
				excludePath = ((IJavaElement) this.unitToSkip).getPath().toString();
			} else {
				excludePath = null;
			}
			
			int lastDotIndex = CharOperation.lastIndexOf('.', prefix);
			char[] qualification, simpleName;
			if (lastDotIndex < 0) {
				qualification = null;
				if (camelCaseMatch) {
					simpleName = prefix;
				} else {
					simpleName = CharOperation.toLowerCase(prefix);
				}
			} else {
				qualification = CharOperation.subarray(prefix, 0, lastDotIndex);
				if (camelCaseMatch) {
					simpleName = CharOperation.subarray(prefix, lastDotIndex + 1, prefix.length);
				} else {
					simpleName =
						CharOperation.toLowerCase(
							CharOperation.subarray(prefix, lastDotIndex + 1, prefix.length));
				}
			}

			IProgressMonitor progressMonitor = new IProgressMonitor() {
				boolean isCanceled = false;
				@Override
				public void beginTask(String name, int totalWork) {
					// implements interface method
				}
				@Override
				public void done() {
					// implements interface method
				}
				@Override
				public void internalWorked(double work) {
					// implements interface method
				}
				@Override
				public boolean isCanceled() {
					return this.isCanceled;
				}
				@Override
				public void setCanceled(boolean value) {
					this.isCanceled = value;
				}
				@Override
				public void setTaskName(String name) {
					// implements interface method
				}
				@Override
				public void subTask(String name) {
					// implements interface method
				}
				@Override
				public void worked(int work) {
					// implements interface method
				}
			};
			
			IRestrictedAccessConstructorRequestor constructorRequestor = new IRestrictedAccessConstructorRequestor() {
				@Override
				public void acceptConstructor(
						int modifiers,
						char[] simpleTypeName,
						int parameterCount,
						char[] signature,
						char[][] parameterTypes,
						char[][] parameterNames,
						int typeModifiers,
						char[] packageName,
						int extraFlags,
						String path,
						AccessRestriction access) {
					if (excludePath != null && excludePath.equals(path))
						return;
					
					storage.acceptConstructor(
							modifiers,
							simpleTypeName,
							parameterCount,
							signature,
							parameterTypes,
							parameterNames, 
							typeModifiers,
							packageName,
							extraFlags,
							path,
							access);
				}
			};
			
			int matchRule = SearchPattern.R_PREFIX_MATCH;
			if (camelCaseMatch) matchRule |= SearchPattern.R_CAMELCASE_MATCH;
			if (monitor != null) {
				IndexManager indexManager = JavaModelManager.getIndexManager();
				// Wait for the end of indexing or a cancel
				indexManager.performConcurrentJob(new IJob() {
					@Override
					public boolean belongsTo(String jobFamily) {
						return true;
					}

					@Override
					public void cancel() {
						// job is cancelled through progress
					}

					@Override
					public void ensureReadyToRun() {
						// always ready
					}

					@Override
					public boolean execute(IProgressMonitor progress) {
						return progress == null || !progress.isCanceled();
					}

					@Override
					public String getJobFamily() {
						return ""; //$NON-NLS-1$
					}
				
				}, IJob.WaitUntilReady, monitor);
				new BasicSearchEngine(this.workingCopies).searchAllConstructorDeclarations(
						qualification,
						simpleName,
						matchRule,
						getSearchScope(),
						constructorRequestor,
						FORCE_IMMEDIATE_SEARCH,
						progressMonitor);
			} else {
				try {
					new BasicSearchEngine(this.workingCopies).searchAllConstructorDeclarations(
							qualification,
							simpleName,
							matchRule,
							getSearchScope(),
							constructorRequestor,
							CANCEL_IF_NOT_READY_TO_SEARCH,
							progressMonitor);
				} catch (OperationCanceledException e) {
					// Do nothing
				}
			}
		} catch (JavaModelException e) {
			// Do nothing
		}
	}

	/**
	 * Returns all types whose name starts with the given (qualified) <code>prefix</code>.
	 *
	 * If the <code>prefix</code> is unqualified, all types whose simple name matches
	 * the <code>prefix</code> are returned.
	 */
	private void findTypes(String prefix, ISearchRequestor storage, int type) {
		//TODO (david) should add camel case support
		SearchableEnvironmentRequestor requestor =
			new SearchableEnvironmentRequestor(storage, this.unitToSkip, this.project, this.nameLookup);
		int index = prefix.lastIndexOf('.');
		if (index == -1) {
			this.nameLookup.seekTypes(prefix, null, true, type, requestor);
		} else {
			String packageName = prefix.substring(0, index);
			JavaElementRequestor elementRequestor = new JavaElementRequestor();
			this.nameLookup.seekPackageFragments(packageName, false, elementRequestor);
			IPackageFragment[] fragments = elementRequestor.getPackageFragments();
			if (fragments != null) {
				String className = prefix.substring(index + 1);
				for (int i = 0, length = fragments.length; i < length; i++)
					if (fragments[i] != null)
						this.nameLookup.seekTypes(className, fragments[i], true, type, requestor);
			}
		}
	}

	private IJavaSearchScope getSearchScope() {
		if (this.searchScope == null) {
			// Create search scope with visible entry on the project's classpath
			if(this.checkAccessRestrictions) {
				this.searchScope = BasicSearchEngine.createJavaSearchScope(this.excludeTestCode, new IJavaElement[] {this.project});
			} else {
				this.searchScope = BasicSearchEngine.createJavaSearchScope(this.excludeTestCode, this.nameLookup.packageFragmentRoots);
			}
		}
		return this.searchScope;
	}

	/**
	 * @see org.eclipse.jdt.internal.compiler.env.IModuleAwareNameEnvironment#getModulesDeclaringPackage(char[][], char[], char[])
	 */
	@Override
	public char[][] getModulesDeclaringPackage(char[][] parentPackageName, char[] name, char[] moduleName) {
		String[] pkgName;
		if (parentPackageName == null)
			pkgName = new String[] {new String(name)};
		else {
			int length = parentPackageName.length;
			pkgName = new String[length+1];
			for (int i = 0; i < length; i++)
				pkgName[i] = new String(parentPackageName[i]);
			pkgName[length] = new String(name);
		}
		LookupStrategy strategy = LookupStrategy.get(moduleName);
		switch (strategy) {
			case Named:
				if (this.knownModuleLocations != null) {
					IPackageFragmentRoot[] moduleContext = findModuleContext(moduleName);
					if (moduleContext != null) {
						// (this.owner != null && this.owner.isPackage(pkgName)) // TODO(SHMOD) see old isPackage
						if (this.nameLookup.isPackage(pkgName, moduleContext)) {
							return new char[][] { moduleName };
						}
					}
				}
				return null;
			case Unnamed:
			case Any:
				// if in pre-9 mode we may still search the unnamed module 
				if (this.knownModuleLocations == null) {
					if ((this.owner != null && this.owner.isPackage(pkgName))
							|| this.nameLookup.isPackage(pkgName))
						return new char[][] { ModuleBinding.UNNAMED };
					return null;
				}
				//$FALL-THROUGH$
			case AnyNamed:
				char[][] names = CharOperation.NO_CHAR_CHAR;
				IPackageFragmentRoot[] packageRoots = this.nameLookup.packageFragmentRoots;
				boolean containsUnnamed = false;
				for (IPackageFragmentRoot packageRoot : packageRoots) {
					IPackageFragmentRoot[] singleton = { packageRoot };
					if (strategy.matches(singleton, locs -> locs[0] instanceof JrtPackageFragmentRoot || getModuleDescription(locs) != null)) {
						if (this.nameLookup.isPackage(pkgName, singleton)) {
							IModuleDescription moduleDescription = getModuleDescription(singleton);
							char[] aName;
							if (moduleDescription != null) {
								aName = moduleDescription.getElementName().toCharArray();
							} else {
								if (containsUnnamed)
									continue;
								containsUnnamed = true;
								aName = ModuleBinding.UNNAMED;
							}
							names = CharOperation.arrayConcat(names, aName);
						}
					}
				}
				return names == CharOperation.NO_CHAR_CHAR ? null : names;
			default:
				throw new IllegalArgumentException("Unexpected LookupStrategy "+strategy); //$NON-NLS-1$
		}
	}
	@Override
	public boolean hasCompilationUnit(char[][] pkgName, char[] moduleName, boolean checkCUs) {
		LookupStrategy strategy = LookupStrategy.get(moduleName);
		switch (strategy) {
			case Named:
				if (this.knownModuleLocations != null) {
					IPackageFragmentRoot[] moduleContext = findModuleContext(moduleName);
					if (moduleContext != null) {
						// (this.owner != null && this.owner.isPackage(pkgName)) // TODO(SHMOD) see old isPackage
						if (this.nameLookup.hasCompilationUnit(pkgName, moduleContext))
							return true;
					}
				}
				return false;
			case Unnamed:
			case Any:
				// if in pre-9 mode we may still search the unnamed module 
				if (this.knownModuleLocations == null) {
					if (this.nameLookup.hasCompilationUnit(pkgName, null))
						return true;
				}
				//$FALL-THROUGH$
			case AnyNamed:
				IPackageFragmentRoot[] packageRoots = this.nameLookup.packageFragmentRoots;
				for (IPackageFragmentRoot packageRoot : packageRoots) {
					IPackageFragmentRoot[] singleton = { packageRoot };
					if (strategy.matches(singleton, locs -> locs[0] instanceof JrtPackageFragmentRoot || getModuleDescription(locs) != null)) {
						if (this.nameLookup.hasCompilationUnit(pkgName, singleton))
							return true;
					}
				}
				return false;
			default:
				throw new IllegalArgumentException("Unexpected LookupStrategy "+strategy); //$NON-NLS-1$
		}
	}

	private IModuleDescription getModuleDescription(IPackageFragmentRoot[] roots) {
		if (this.rootToModule == null) {
			this.rootToModule = new HashMap<>();
		}
		for (IPackageFragmentRoot root : roots) {
			IModuleDescription moduleDescription = NameLookup.getModuleDescription(root, this.rootToModule, this.nameLookup.rootToResolvedEntries::get);
			if (moduleDescription != null)
				return moduleDescription;
		}
		return null;
	}

	private IPackageFragmentRoot[] findModuleContext(char[] moduleName) {
		IPackageFragmentRoot[] moduleContext = null;
		if (this.knownModuleLocations != null && moduleName != null && moduleName.length > 0) {
			moduleContext = this.knownModuleLocations.get(String.valueOf(moduleName));
			if (moduleContext == null) {
				Answer moduleAnswer = this.nameLookup.findModule(moduleName);
				if (moduleAnswer != null) {
					IProject currentProject = moduleAnswer.module.getJavaProject().getProject();
					IJavaElement current = moduleAnswer.module.getParent();
					while (moduleContext == null && current != null) {
						switch (current.getElementType()) {
							case IJavaElement.PACKAGE_FRAGMENT_ROOT:
								if (!((IPackageFragmentRoot) current).isExternal() && !(current instanceof JarPackageFragmentRoot)) {
									current = current.getJavaProject();
								} else {
									moduleContext = new IPackageFragmentRoot[] { (IPackageFragmentRoot) current }; // TODO: validate
									break;
								}
								//$FALL-THROUGH$
							case IJavaElement.JAVA_PROJECT:
								try {
									moduleContext = getOwnedPackageFragmentRoots((IJavaProject) current);
								} catch (JavaModelException e) {
									// silent?
								}
								break;
							default:
								current = current.getParent();
								if (current != null) {
									try {
										// detect when an element refers to a resource owned by another project:
										IResource resource = current.getUnderlyingResource();
										if (resource != null) {
											IProject otherProject = resource.getProject();
											if (otherProject != null && !otherProject.equals(currentProject)) {
												IJavaProject otherJavaProject = JavaCore.create(otherProject);
												if (otherJavaProject.exists())
													moduleContext = getRootsForOutputLocation(otherJavaProject, resource);
											}
										}
									} catch (JavaModelException e) {
										Util.log(e, "Failed to find package fragment root for " + current); //$NON-NLS-1$
									}
								}
						}
					}
					this.knownModuleLocations.put(String.valueOf(moduleName), moduleContext);
				}
			}
		}
		return moduleContext;
	}

	/**
	 * Returns a printable string for the array.
	 */
	protected String toStringChar(char[] name) {
		return "["  //$NON-NLS-1$
		+ new String(name) + "]" ; //$NON-NLS-1$
	}

	/**
	 * Returns a printable string for the array.
	 */
	protected String toStringCharChar(char[][] names) {
		StringBuffer result = new StringBuffer();
		for (int i = 0; i < names.length; i++) {
			result.append(toStringChar(names[i]));
		}
		return result.toString();
	}

	@Override
	public void cleanup() {
		// nothing to do
	}

	@Override
	public org.eclipse.jdt.internal.compiler.env.IModule getModule(char[] name) {
		NameLookup.Answer answer = this.nameLookup.findModule(name);
		IModule module = null;
		if (answer != null) {
			module = NameLookup.getModuleDescriptionInfo(answer.module);
		}
		return module;
	}

	@Override
	public char[][] getAllAutomaticModules() {
		return CharOperation.NO_CHAR_CHAR;
	}

	@Override
	public void applyModuleUpdates(IUpdatableModule module, UpdateKind kind) {
		if (this.moduleUpdater != null)
			this.moduleUpdater.applyModuleUpdates(module, kind);
	}

	private IPackageFragmentRoot[] getRootsForOutputLocation(IJavaProject otherJavaProject, IResource outputLocation) throws JavaModelException {
		IPath outputPath = outputLocation.getFullPath();
		List<IPackageFragmentRoot> result = new ArrayList<>();
		if (outputPath.equals(otherJavaProject.getOutputLocation())) {
			// collect roots reporting to the default output location:
			for (IClasspathEntry classpathEntry : otherJavaProject.getRawClasspath()) {
				if (classpathEntry.getOutputLocation() == null) {
					for (IPackageFragmentRoot root : otherJavaProject.findPackageFragmentRoots(classpathEntry)) {
						IResource rootResource = root.getResource();
						if (rootResource == null || !rootResource.getProject().equals(otherJavaProject.getProject()))
							continue; // outside this project
						result.add(root);
					}
				}
			}			
		}
		if (!result.isEmpty())
			return result.toArray(new IPackageFragmentRoot[result.size()]);
		// search an entry that specifically (and exclusively) reports to the output location:
		for (IClasspathEntry classpathEntry : otherJavaProject.getRawClasspath()) {
			if (outputPath.equals(classpathEntry.getOutputLocation()))
				return otherJavaProject.findPackageFragmentRoots(classpathEntry);
		}
		return null;
	}

	public static IPackageFragmentRoot[] getOwnedPackageFragmentRoots(IJavaProject javaProject) throws JavaModelException {
		IPackageFragmentRoot[] allRoots = javaProject.getPackageFragmentRoots();
		IPackageFragmentRoot[] sourceRoots = Arrays.copyOf(allRoots, allRoots.length);
		int count = 0;
		for (int i = 0; i < allRoots.length; i++) {
			IPackageFragmentRoot root = allRoots[i];
			if (root.getKind() == IPackageFragmentRoot.K_BINARY) {
				if(root instanceof JarPackageFragmentRoot) {
					// don't treat jars in a project as part of the project's module
					continue;
				}
				IResource resource = root.getResource();
				if (resource == null || !resource.getProject().equals(javaProject.getProject()))
					continue; // outside this project
			}
			sourceRoots[count++] = root;
		}
		if (count < allRoots.length)
			return Arrays.copyOf(sourceRoots, count);
		return sourceRoots;
	}
}

Back to the top