781189bd4b97f1ca7c2ea5c76e6eca54730ac0f4
[phpeclipse.git] /
1 /*******************************************************************************
2  * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others.
3  * All rights reserved. This program and the accompanying materials 
4  * are made available under the terms of the Common Public License v0.5 
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/cpl-v05.html
7  * 
8  * Contributors:
9  *     IBM Corporation - initial API and implementation
10  ******************************************************************************/
11 package net.sourceforge.phpdt.internal.compiler.lookup;
12
13 import net.sourceforge.phpdt.internal.compiler.ast.CompilationUnitDeclaration;
14 import net.sourceforge.phpdt.internal.compiler.env.IBinaryType;
15 import net.sourceforge.phpdt.internal.compiler.env.INameEnvironment;
16 import net.sourceforge.phpdt.internal.compiler.env.NameEnvironmentAnswer;
17 import net.sourceforge.phpdt.internal.compiler.impl.CompilerOptions;
18 import net.sourceforge.phpdt.internal.compiler.impl.ITypeRequestor;
19 import net.sourceforge.phpdt.internal.compiler.problem.ProblemReporter;
20 import net.sourceforge.phpdt.internal.compiler.util.CharOperation;
21 import net.sourceforge.phpdt.internal.compiler.util.HashtableOfPackage;
22 import net.sourceforge.phpdt.internal.compiler.util.Util;
23
24 public class LookupEnvironment implements BaseTypes, ProblemReasons, TypeConstants {
25         public CompilerOptions options;
26         public ProblemReporter problemReporter;
27         public ITypeRequestor typeRequestor;
28
29         PackageBinding defaultPackage;
30         ImportBinding[] defaultImports;
31         HashtableOfPackage knownPackages;
32         static final ProblemPackageBinding theNotFoundPackage = new ProblemPackageBinding(new char[0], NotFound);
33         static final ProblemReferenceBinding theNotFoundType = new ProblemReferenceBinding(new char[0], NotFound);
34
35         private INameEnvironment nameEnvironment;
36         private MethodVerifier verifier;
37         private ArrayBinding[][] uniqueArrayBindings;
38
39         private CompilationUnitDeclaration[] units = new CompilationUnitDeclaration[4];
40         private int lastUnitIndex = -1;
41         private int lastCompletedUnitIndex = -1;
42
43         // indicate in which step on the compilation we are.
44         // step 1 : build the reference binding
45         // step 2 : conect the hierarchy (connect bindings)
46         // step 3 : build fields and method bindings.
47         private int stepCompleted;
48         final static int BUILD_TYPE_HIERARCHY = 1;
49         final static int CHECK_AND_SET_IMPORTS = 2;
50         final static int CONNECT_TYPE_HIERARCHY = 3;
51         final static int BUILD_FIELDS_AND_METHODS = 4;
52 public LookupEnvironment(ITypeRequestor typeRequestor, CompilerOptions options, ProblemReporter problemReporter, INameEnvironment nameEnvironment) {
53         this.typeRequestor = typeRequestor;
54         this.options = options;
55         this.problemReporter = problemReporter;
56         this.defaultPackage = new PackageBinding(this); // assume the default package always exists
57         this.defaultImports = null;
58         this.nameEnvironment = nameEnvironment;
59         this.knownPackages = new HashtableOfPackage();
60         this.uniqueArrayBindings = new ArrayBinding[5][];
61         this.uniqueArrayBindings[0] = new ArrayBinding[50]; // start off the most common 1 dimension array @ 50
62 }
63 /* Ask the oracle for a type which corresponds to the compoundName.
64 * Answer null if the name cannot be found.
65 */
66
67 public ReferenceBinding askForType(char[][] compoundName) {
68         NameEnvironmentAnswer answer = nameEnvironment.findType(compoundName);
69         if (answer == null)
70                 return null;
71
72         if (answer.isBinaryType())
73                 // the type was found as a .class file
74                 typeRequestor.accept(answer.getBinaryType(), computePackageFrom(compoundName));
75         else if (answer.isCompilationUnit())
76                 // the type was found as a .java file, try to build it then search the cache
77                 typeRequestor.accept(answer.getCompilationUnit());
78         else if (answer.isSourceType())
79                 // the type was found as a source model
80                 typeRequestor.accept(answer.getSourceTypes(), computePackageFrom(compoundName));
81
82         return getCachedType(compoundName);
83 }
84 /* Ask the oracle for a type named name in the packageBinding.
85 * Answer null if the name cannot be found.
86 */
87
88 ReferenceBinding askForType(PackageBinding packageBinding, char[] name) {
89         if (packageBinding == null) {
90                 if (defaultPackage == null)
91                         return null;
92                 packageBinding = defaultPackage;
93         }
94         NameEnvironmentAnswer answer = nameEnvironment.findType(name, packageBinding.compoundName);
95         if (answer == null)
96                 return null;
97
98         if (answer.isBinaryType())
99                 // the type was found as a .class file
100                 typeRequestor.accept(answer.getBinaryType(), packageBinding);
101         else if (answer.isCompilationUnit())
102                 // the type was found as a .java file, try to build it then search the cache
103                 typeRequestor.accept(answer.getCompilationUnit());
104         else if (answer.isSourceType())
105                 // the type was found as a source model
106                 typeRequestor.accept(answer.getSourceTypes(), packageBinding);
107
108         return packageBinding.getType0(name);
109 }
110 /* Create the initial type bindings for the compilation unit.
111 *
112 * See completeTypeBindings() for a description of the remaining steps
113 *
114 * NOTE: This method can be called multiple times as additional source files are needed
115 */
116
117 public void buildTypeBindings(CompilationUnitDeclaration unit) {
118         CompilationUnitScope scope = new CompilationUnitScope(unit, this);
119         scope.buildTypeBindings();
120
121         int unitsLength = units.length;
122         if (++lastUnitIndex >= unitsLength)
123                 System.arraycopy(units, 0, units = new CompilationUnitDeclaration[2 * unitsLength], 0, unitsLength);
124         units[lastUnitIndex] = unit;
125 }
126 /* Cache the binary type since we know it is needed during this compile.
127 *
128 * Answer the created BinaryTypeBinding or null if the type is already in the cache.
129 */
130
131 public BinaryTypeBinding cacheBinaryType(IBinaryType binaryType) {
132         return cacheBinaryType(binaryType, true);
133 }
134 /* Cache the binary type since we know it is needed during this compile.
135 *
136 * Answer the created BinaryTypeBinding or null if the type is already in the cache.
137 */
138
139 public BinaryTypeBinding cacheBinaryType(IBinaryType binaryType, boolean needFieldsAndMethods) {
140         char[][] compoundName = CharOperation.splitOn('/', binaryType.getName());
141         ReferenceBinding existingType = getCachedType(compoundName);
142
143         if (existingType == null || existingType instanceof UnresolvedReferenceBinding)
144                 // only add the binary type if its not already in the cache
145                 return createBinaryTypeFrom(binaryType, computePackageFrom(compoundName), needFieldsAndMethods);
146         return null; // the type already exists & can be retrieved from the cache
147 }
148 /*
149 * 1. Connect the type hierarchy for the type bindings created for parsedUnits.
150 * 2. Create the field bindings
151 * 3. Create the method bindings
152 */
153
154 /* We know each known compilationUnit is free of errors at this point...
155 *
156 * Each step will create additional bindings unless a problem is detected, in which
157 * case either the faulty import/superinterface/field/method will be skipped or a
158 * suitable replacement will be substituted (such as Object for a missing superclass)
159 */
160
161 public void completeTypeBindings() {
162         stepCompleted = BUILD_TYPE_HIERARCHY;
163         
164         for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
165                 units[i].scope.checkAndSetImports();
166         }
167         stepCompleted = CHECK_AND_SET_IMPORTS;
168
169         for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
170                 units[i].scope.connectTypeHierarchy();
171         }
172         stepCompleted = CONNECT_TYPE_HIERARCHY;
173
174         for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
175                 units[i].scope.buildFieldsAndMethods();
176                 units[i] = null; // release unnecessary reference to the parsed unit
177         }
178         stepCompleted = BUILD_FIELDS_AND_METHODS;
179         lastCompletedUnitIndex = lastUnitIndex;
180 }
181 /*
182 * 1. Connect the type hierarchy for the type bindings created for parsedUnits.
183 * 2. Create the field bindings
184 * 3. Create the method bindings
185 */
186
187 /*
188 * Each step will create additional bindings unless a problem is detected, in which
189 * case either the faulty import/superinterface/field/method will be skipped or a
190 * suitable replacement will be substituted (such as Object for a missing superclass)
191 */
192
193 public void completeTypeBindings(CompilationUnitDeclaration parsedUnit) {
194         if (stepCompleted == BUILD_FIELDS_AND_METHODS) {
195                 // This can only happen because the original set of units are completely built and
196                 // are now being processed, so we want to treat all the additional units as a group
197                 // until they too are completely processed.
198                 completeTypeBindings();
199         } else {
200                 if (parsedUnit.scope == null) return; // parsing errors were too severe
201
202                 if (stepCompleted >= CHECK_AND_SET_IMPORTS)
203                         parsedUnit.scope.checkAndSetImports();
204
205                 if (stepCompleted >= CONNECT_TYPE_HIERARCHY)
206                         parsedUnit.scope.connectTypeHierarchy();
207         }
208 }
209 /*
210 * Used by other compiler tools which do not start by calling completeTypeBindings().
211 *
212 * 1. Connect the type hierarchy for the type bindings created for parsedUnits.
213 * 2. Create the field bindings
214 * 3. Create the method bindings
215 */
216
217 public void completeTypeBindings(CompilationUnitDeclaration parsedUnit, boolean buildFieldsAndMethods) {
218         if (parsedUnit.scope == null) return; // parsing errors were too severe
219
220         parsedUnit.scope.checkAndSetImports();
221         parsedUnit.scope.connectTypeHierarchy();
222
223         if (buildFieldsAndMethods)
224                 parsedUnit.scope.buildFieldsAndMethods();
225 }
226 private PackageBinding computePackageFrom(char[][] constantPoolName) {
227         if (constantPoolName.length == 1)
228                 return defaultPackage;
229
230         PackageBinding packageBinding = getPackage0(constantPoolName[0]);
231         if (packageBinding == null || packageBinding == theNotFoundPackage) {
232                 packageBinding = new PackageBinding(constantPoolName[0], this);
233                 knownPackages.put(constantPoolName[0], packageBinding);
234         }
235
236         for (int i = 1, length = constantPoolName.length - 1; i < length; i++) {
237                 PackageBinding parent = packageBinding;
238                 if ((packageBinding = parent.getPackage0(constantPoolName[i])) == null || packageBinding == theNotFoundPackage) {
239                         packageBinding = new PackageBinding(CharOperation.subarray(constantPoolName, 0, i + 1), parent, this);
240                         parent.addPackage(packageBinding);
241                 }
242         }
243         return packageBinding;
244 }
245 /* Used to guarantee array type identity.
246 */
247
248 ArrayBinding createArrayType(TypeBinding type, int dimensionCount) {
249         // find the array binding cache for this dimension
250         int dimIndex = dimensionCount - 1;
251         int length = uniqueArrayBindings.length;
252         ArrayBinding[] arrayBindings;
253         if (dimIndex < length) {
254                 if ((arrayBindings = uniqueArrayBindings[dimIndex]) == null)
255                         uniqueArrayBindings[dimIndex] = arrayBindings = new ArrayBinding[10];
256         } else {
257                 System.arraycopy(
258                         uniqueArrayBindings, 0, 
259                         uniqueArrayBindings = new ArrayBinding[dimensionCount][], 0, 
260                         length); 
261                 uniqueArrayBindings[dimIndex] = arrayBindings = new ArrayBinding[10];
262         }
263
264         // find the cached array binding for this leaf component type (if any)
265         int index = -1;
266         length = arrayBindings.length;
267         while (++index < length) {
268                 ArrayBinding currentBinding = arrayBindings[index];
269                 if (currentBinding == null) // no matching array, but space left
270                         return arrayBindings[index] = new ArrayBinding(type, dimensionCount);
271                 if (currentBinding.leafComponentType == type)
272                         return currentBinding;
273         }
274
275         // no matching array, no space left
276         System.arraycopy(
277                 arrayBindings, 0,
278                 (arrayBindings = new ArrayBinding[length * 2]), 0,
279                 length); 
280         uniqueArrayBindings[dimIndex] = arrayBindings;
281         return arrayBindings[length] = new ArrayBinding(type, dimensionCount);
282 }
283 public BinaryTypeBinding createBinaryTypeFrom(IBinaryType binaryType, PackageBinding packageBinding) {
284         return createBinaryTypeFrom(binaryType, packageBinding, true);
285 }
286 public BinaryTypeBinding createBinaryTypeFrom(IBinaryType binaryType, PackageBinding packageBinding, boolean needFieldsAndMethods) {
287         BinaryTypeBinding binaryBinding = new BinaryTypeBinding(packageBinding, binaryType, this);
288
289         // resolve any array bindings which reference the unresolvedType
290         ReferenceBinding cachedType = packageBinding.getType0(binaryBinding.compoundName[binaryBinding.compoundName.length - 1]);
291         if (cachedType != null) {
292                 if (cachedType.isBinaryBinding()) // sanity check before the cast... at this point the cache should ONLY contain unresolved types
293                         return (BinaryTypeBinding) cachedType;
294
295                 UnresolvedReferenceBinding unresolvedType = (UnresolvedReferenceBinding) cachedType;
296                 unresolvedType.resolvedType = binaryBinding;
297                 updateArrayCache(unresolvedType, binaryBinding);
298         }
299
300         packageBinding.addType(binaryBinding);
301         binaryBinding.cachePartsFrom(binaryType, needFieldsAndMethods);
302         return binaryBinding;
303 }
304 /* Used to create packages from the package statement.
305 */
306
307 PackageBinding createPackage(char[][] compoundName) {
308         PackageBinding packageBinding = getPackage0(compoundName[0]);
309         if (packageBinding == null || packageBinding == theNotFoundPackage) {
310                 packageBinding = new PackageBinding(compoundName[0], this);
311                 knownPackages.put(compoundName[0], packageBinding);
312         }
313
314         for (int i = 1, length = compoundName.length; i < length; i++) {
315                 // check to see if it collides with a known type...
316                 // this case can only happen if the package does not exist as a directory in the file system
317                 // otherwise when the source type was defined, the correct error would have been reported
318                 // unless its an unresolved type which is referenced from an inconsistent class file
319                 ReferenceBinding type = packageBinding.getType0(compoundName[i]);
320                 if (type != null && type != theNotFoundType && !(type instanceof UnresolvedReferenceBinding))
321                         return null;
322
323                 PackageBinding parent = packageBinding;
324                 if ((packageBinding = parent.getPackage0(compoundName[i])) == null || packageBinding == theNotFoundPackage) {
325                         // if the package is unknown, check to see if a type exists which would collide with the new package
326                         // catches the case of a package statement of: package java.lang.Object;
327                         // since the package can be added after a set of source files have already been compiled, we need
328                         // whenever a package statement is encountered
329                         if (nameEnvironment.findType(compoundName[i], parent.compoundName) != null)
330                                 return null;
331
332                         packageBinding = new PackageBinding(CharOperation.subarray(compoundName, 0, i + 1), parent, this);
333                         parent.addPackage(packageBinding);
334                 }
335         }
336         return packageBinding;
337 }
338 /* Answer the type for the compoundName if it exists in the cache.
339 * Answer theNotFoundType if it could not be resolved the first time
340 * it was looked up, otherwise answer null.
341 *
342 * NOTE: Do not use for nested types... the answer is NOT the same for a.b.C or a.b.C.D.E
343 * assuming C is a type in both cases. In the a.b.C.D.E case, null is the answer.
344 */
345
346 public ReferenceBinding getCachedType(char[][] compoundName) {
347         if (compoundName.length == 1) {
348                 if (defaultPackage == null)
349                         return null;
350                 return defaultPackage.getType0(compoundName[0]);
351         }
352
353         PackageBinding packageBinding = getPackage0(compoundName[0]);
354         if (packageBinding == null || packageBinding == theNotFoundPackage)
355                 return null;
356
357         for (int i = 1, packageLength = compoundName.length - 1; i < packageLength; i++)
358                 if ((packageBinding = packageBinding.getPackage0(compoundName[i])) == null || packageBinding == theNotFoundPackage)
359                         return null;
360         return packageBinding.getType0(compoundName[compoundName.length - 1]);
361 }
362 /* Answer the top level package named name if it exists in the cache.
363 * Answer theNotFoundPackage if it could not be resolved the first time
364 * it was looked up, otherwise answer null.
365 *
366 * NOTE: Senders must convert theNotFoundPackage into a real problem
367 * package if its to returned.
368 */
369
370 PackageBinding getPackage0(char[] name) {
371         return knownPackages.get(name);
372 }
373 /* Answer the top level package named name.
374 * Ask the oracle for the package if its not in the cache.
375 * Answer null if the package cannot be found.
376 */
377
378 PackageBinding getTopLevelPackage(char[] name) {
379         PackageBinding packageBinding = getPackage0(name);
380         if (packageBinding != null) {
381                 if (packageBinding == theNotFoundPackage)
382                         return null;
383                 else
384                         return packageBinding;
385         }
386
387         if (nameEnvironment.isPackage(null, name)) {
388                 knownPackages.put(name, packageBinding = new PackageBinding(name, this));
389                 return packageBinding;
390         }
391
392         knownPackages.put(name, theNotFoundPackage); // saves asking the oracle next time
393         return null;
394 }
395 /* Answer the type corresponding to the compoundName.
396 * Ask the oracle for the type if its not in the cache.
397 * Answer null if the type cannot be found... likely a fatal error.
398 */
399
400 public ReferenceBinding getType(char[][] compoundName) {
401         ReferenceBinding referenceBinding;
402
403         if (compoundName.length == 1) {
404                 if (defaultPackage == null)
405                         return null;
406
407                 if ((referenceBinding = defaultPackage.getType0(compoundName[0])) == null) {
408                         PackageBinding packageBinding = getPackage0(compoundName[0]);
409                         if (packageBinding != null && packageBinding != theNotFoundPackage)
410                                 return null; // collides with a known package... should not call this method in such a case
411                         referenceBinding = askForType(defaultPackage, compoundName[0]);
412                 }
413         } else {
414                 PackageBinding packageBinding = getPackage0(compoundName[0]);
415                 if (packageBinding == theNotFoundPackage)
416                         return null;
417
418                 if (packageBinding != null) {
419                         for (int i = 1, packageLength = compoundName.length - 1; i < packageLength; i++) {
420                                 if ((packageBinding = packageBinding.getPackage0(compoundName[i])) == null)
421                                         break;
422                                 if (packageBinding == theNotFoundPackage)
423                                         return null;
424                         }
425                 }
426
427                 if (packageBinding == null)
428                         referenceBinding = askForType(compoundName);
429                 else if ((referenceBinding = packageBinding.getType0(compoundName[compoundName.length - 1])) == null)
430                         referenceBinding = askForType(packageBinding, compoundName[compoundName.length - 1]);
431         }
432
433         if (referenceBinding == null || referenceBinding == theNotFoundType)
434                 return null;
435         if (referenceBinding instanceof UnresolvedReferenceBinding)
436                 referenceBinding = ((UnresolvedReferenceBinding) referenceBinding).resolve(this);
437
438         // compoundName refers to a nested type incorrectly (i.e. package1.A$B)
439         if (referenceBinding.isNestedType())
440                 return new ProblemReferenceBinding(compoundName, InternalNameProvided);
441         else
442                 return referenceBinding;
443 }
444 /* Answer the type corresponding to the name from the binary file.
445 * Does not ask the oracle for the type if its not found in the cache... instead an
446 * unresolved type is returned which must be resolved before used.
447 *
448 * NOTE: Does NOT answer base types nor array types!
449 *
450 * NOTE: Aborts compilation if the class file cannot be found.
451 */
452
453 ReferenceBinding getTypeFromConstantPoolName(char[] signature, int start, int end) {
454         if (end == -1)
455                 end = signature.length - 1;
456
457         char[][] compoundName = CharOperation.splitOn('/', signature, start, end);
458         ReferenceBinding binding = getCachedType(compoundName);
459         if (binding == null) {
460                 PackageBinding packageBinding = computePackageFrom(compoundName);
461                 binding = new UnresolvedReferenceBinding(compoundName, packageBinding);
462                 packageBinding.addType(binding);
463         } else if (binding == theNotFoundType) {
464                 problemReporter.isClassPathCorrect(compoundName, null);
465                 return null; // will not get here since the above error aborts the compilation
466         }
467         return binding;
468 }
469 /* Answer the type corresponding to the signature from the binary file.
470 * Does not ask the oracle for the type if its not found in the cache... instead an
471 * unresolved type is returned which must be resolved before used.
472 *
473 * NOTE: Does answer base types & array types.
474 *
475 * NOTE: Aborts compilation if the class file cannot be found.
476 */
477
478 TypeBinding getTypeFromSignature(char[] signature, int start, int end) {
479         int dimension = 0;
480         while (signature[start] == '[') {
481                 start++;
482                 dimension++;
483         }
484         if (end == -1)
485                 end = signature.length - 1;
486
487         // Just switch on signature[start] - the L case is the else
488         TypeBinding binding = null;
489         if (start == end) {
490                 switch (signature[start]) {
491                         case 'I' :
492                                 binding = IntBinding;
493                                 break;
494                         case 'Z' :
495                                 binding = BooleanBinding;
496                                 break;
497                         case 'V' :
498                                 binding = VoidBinding;
499                                 break;
500                         case 'C' :
501                                 binding = CharBinding;
502                                 break;
503                         case 'D' :
504                                 binding = DoubleBinding;
505                                 break;
506                         case 'B' :
507                                 binding = ByteBinding;
508                                 break;
509                         case 'F' :
510                                 binding = FloatBinding;
511                                 break;
512                         case 'J' :
513                                 binding = LongBinding;
514                                 break;
515                         case 'S' :
516                                 binding = ShortBinding;
517                                 break;
518                         default :
519                                 throw new Error(Util.bind("error.undefinedBaseType",String.valueOf(signature[start]))); //$NON-NLS-1$
520                 }
521         } else {
522                 binding = getTypeFromConstantPoolName(signature, start + 1, end - 1);
523         }
524
525         if (dimension == 0)
526                 return binding;
527         else
528                 return createArrayType(binding, dimension);
529 }
530 /* Ask the oracle if a package exists named name in the package named compoundName.
531 */
532
533 boolean isPackage(char[][] compoundName, char[] name) {
534         if (compoundName == null || compoundName.length == 0)
535                 return nameEnvironment.isPackage(null, name);
536         else
537                 return nameEnvironment.isPackage(compoundName, name);
538 }
539 // The method verifier is lazily initialized to guarantee the receiver, the compiler & the oracle are ready.
540
541 public MethodVerifier methodVerifier() {
542         if (verifier == null)
543                 verifier = new MethodVerifier(this);
544         return verifier;
545 }
546 public void reset() {
547         this.defaultPackage = new PackageBinding(this); // assume the default package always exists
548         this.defaultImports = null;
549         this.knownPackages = new HashtableOfPackage();
550
551         this.verifier = null;
552         for (int i = this.uniqueArrayBindings.length; --i >= 0;)
553                 this.uniqueArrayBindings[i] = null;
554         this.uniqueArrayBindings[0] = new ArrayBinding[50]; // start off the most common 1 dimension array @ 50
555
556         for (int i = this.units.length; --i >= 0;)
557                 this.units[i] = null;
558         this.lastUnitIndex = -1;
559         this.lastCompletedUnitIndex = -1;
560         
561         // name environment has a longer life cycle, and must be reset in
562         // the code which created it.
563 }
564 void updateArrayCache(UnresolvedReferenceBinding unresolvedType, ReferenceBinding resolvedType) {
565         nextDimension : for (int i = 0, length = uniqueArrayBindings.length; i < length; i++) {
566                 ArrayBinding[] arrayBindings = uniqueArrayBindings[i];
567                 if (arrayBindings != null) {
568                         for (int j = 0, max = arrayBindings.length; j < max; j++) {
569                                 ArrayBinding currentBinding = arrayBindings[j];
570                                 if (currentBinding == null)
571                                         continue nextDimension;
572                                 if (currentBinding.leafComponentType == unresolvedType) {
573                                         currentBinding.leafComponentType = resolvedType;
574                                         continue nextDimension;
575                                 }
576                         }
577                 }
578         }
579 }
580 }