From ec87a3b8e0a51fc2baec20756c00429d9e68a587 Mon Sep 17 00:00:00 2001 From: Jason Peterson Date: Mon, 15 Jul 2013 15:11:57 -0400 Subject: [384319] CPU utilization to 100% when this is appended to new object definition --- bundles/org.eclipse.wst.jsdt.core/.options | 60 + bundles/org.eclipse.wst.jsdt.core/.project | 79 +- .../.settings/.api_filters | 11 + .../org.eclipse.wst.jsdt.core/.settings/.jsdtscope | 1 - .../.settings/org.eclipse.jdt.core.prefs | 490 +- .../.settings/org.eclipse.jdt.ui.prefs | 105 +- .../org.eclipse.wst.jsdt.core/META-INF/MANIFEST.MF | 56 +- bundles/org.eclipse.wst.jsdt.core/build.properties | 2 +- .../baseBrowserLibrary--WrapperObjects.js | 6 +- .../libraries/baseBrowserLibrary.js | 6 +- .../libraries/browserWindow.js | 245 +- .../org.eclipse.wst.jsdt.core/libraries/dom5.js | 6315 ++------ .../org.eclipse.wst.jsdt.core/libraries/system.js | 55 +- bundles/org.eclipse.wst.jsdt.core/libraries/xhr.js | 4 +- .../org.eclipse.wst.jsdt.core/plugin.properties | 2 + bundles/org.eclipse.wst.jsdt.core/plugin.xml | 5 +- .../eclipse/wst/jsdt/core/BufferChangedEvent.java | 2 +- .../eclipse/wst/jsdt/core/CompletionProposal.java | 241 +- .../eclipse/wst/jsdt/core/CompletionRequestor.java | 2 +- .../org/eclipse/wst/jsdt/core/IBufferFactory.java | 2 +- .../wst/jsdt/core/IElementChangedListener.java | 2 +- .../eclipse/wst/jsdt/core/IIncludePathEntry.java | 2 +- .../eclipse/wst/jsdt/core/IJavaScriptProject.java | 3 +- .../wst/jsdt/core/IJsGlobalScopeContainer.java | 5 +- .../eclipse/wst/jsdt/core/IProblemRequestor.java | 2 +- .../src/org/eclipse/wst/jsdt/core/IType.java | 8 +- .../jsdt/core/ITypeHierarchyChangedListener.java | 2 +- .../wst/jsdt/core/JavaScriptConventions.java | 5 +- .../org/eclipse/wst/jsdt/core/JavaScriptCore.java | 5 +- .../eclipse/wst/jsdt/core/LibrarySuperType.java | 4 +- .../src/org/eclipse/wst/jsdt/core/Messages.java | 10 + .../src/org/eclipse/wst/jsdt/core/Signature.java | 2 +- .../core/ast/IAbstractVariableDeclaration.java | 28 +- .../org/eclipse/wst/jsdt/core/ast/IAssignment.java | 30 +- .../eclipse/wst/jsdt/core/ast/IFunctionCall.java | 2 +- .../wst/jsdt/core/ast/IFunctionDeclaration.java | 2 +- .../wst/jsdt/core/ast/ILocalDeclaration.java | 4 +- .../eclipse/wst/jsdt/core/ast/IObjectLiteral.java | 2 +- .../wst/jsdt/core/ast/IReturnStatement.java | 39 +- .../wst/jsdt/core/compiler/CharOperation.java | 42 +- .../eclipse/wst/jsdt/core/compiler/IScanner.java | 2 +- .../wst/jsdt/core/compiler/ITerminalSymbols.java | 2 +- .../core/compiler/libraries/LibraryLocation.java | 2 +- .../eclipse/wst/jsdt/core/dom/ASTConverter.java | 32 +- .../jsdt/core/dom/AnonymousClassDeclaration.java | 2 +- .../org/eclipse/wst/jsdt/core/dom/ArrayAccess.java | 2 +- .../eclipse/wst/jsdt/core/dom/ArrayCreation.java | 2 +- .../wst/jsdt/core/dom/ArrayInitializer.java | 2 +- .../org/eclipse/wst/jsdt/core/dom/ArrayType.java | 2 +- .../org/eclipse/wst/jsdt/core/dom/Assignment.java | 2 +- .../src/org/eclipse/wst/jsdt/core/dom/Block.java | 2 +- .../eclipse/wst/jsdt/core/dom/BodyDeclaration.java | 2 +- .../eclipse/wst/jsdt/core/dom/BooleanLiteral.java | 2 +- .../eclipse/wst/jsdt/core/dom/BreakStatement.java | 2 +- .../org/eclipse/wst/jsdt/core/dom/CatchClause.java | 2 +- .../wst/jsdt/core/dom/CharacterLiteral.java | 2 +- .../src/org/eclipse/wst/jsdt/core/dom/Comment.java | 2 +- .../wst/jsdt/core/dom/ConditionalExpression.java | 2 +- .../wst/jsdt/core/dom/ContinueStatement.java | 2 +- .../wst/jsdt/core/dom/DefaultBindingResolver.java | 33 +- .../org/eclipse/wst/jsdt/core/dom/DoStatement.java | 2 +- .../eclipse/wst/jsdt/core/dom/EmptyExpression.java | 2 +- .../eclipse/wst/jsdt/core/dom/EmptyStatement.java | 2 +- .../wst/jsdt/core/dom/EnhancedForStatement.java | 2 +- .../org/eclipse/wst/jsdt/core/dom/FieldAccess.java | 2 +- .../eclipse/wst/jsdt/core/dom/ForInStatement.java | 2 +- .../eclipse/wst/jsdt/core/dom/ForStatement.java | 2 +- .../eclipse/wst/jsdt/core/dom/FunctionBinding.java | 75 +- .../org/eclipse/wst/jsdt/core/dom/IBinding.java | 2 +- .../wst/jsdt/core/dom/IExtendedModifier.java | 2 +- .../eclipse/wst/jsdt/core/dom/IPackageBinding.java | 2 +- .../wst/jsdt/core/dom/IVariableBinding.java | 2 +- .../org/eclipse/wst/jsdt/core/dom/IfStatement.java | 2 +- .../wst/jsdt/core/dom/InstanceofExpression.java | 2 +- .../wst/jsdt/core/dom/JavaScriptUnitResolver.java | 81 +- .../wst/jsdt/core/dom/LabeledStatement.java | 2 +- .../org/eclipse/wst/jsdt/core/dom/LineComment.java | 2 +- .../eclipse/wst/jsdt/core/dom/ListExpression.java | 2 +- .../org/eclipse/wst/jsdt/core/dom/Modifier.java | 2 +- .../src/org/eclipse/wst/jsdt/core/dom/Name.java | 2 +- .../wst/jsdt/core/dom/NodeEventHandler.java | 2 +- .../org/eclipse/wst/jsdt/core/dom/NullLiteral.java | 2 +- .../eclipse/wst/jsdt/core/dom/NumberLiteral.java | 2 +- .../eclipse/wst/jsdt/core/dom/ObjectLiteral.java | 2 +- .../wst/jsdt/core/dom/ObjectLiteralField.java | 2 +- .../eclipse/wst/jsdt/core/dom/PackageBinding.java | 2 +- .../wst/jsdt/core/dom/ParenthesizedExpression.java | 2 +- .../wst/jsdt/core/dom/PostfixExpression.java | 2 +- .../wst/jsdt/core/dom/PrefixExpression.java | 2 +- .../eclipse/wst/jsdt/core/dom/PrimitiveType.java | 2 +- .../eclipse/wst/jsdt/core/dom/QualifiedName.java | 2 +- .../eclipse/wst/jsdt/core/dom/QualifiedType.java | 2 +- .../jsdt/core/dom/RecoveredVariableBinding.java | 2 +- .../jsdt/core/dom/RegularExpressionLiteral.java | 2 +- .../eclipse/wst/jsdt/core/dom/ReturnStatement.java | 2 +- .../org/eclipse/wst/jsdt/core/dom/SimpleType.java | 2 +- .../jsdt/core/dom/SingleVariableDeclaration.java | 2 +- .../eclipse/wst/jsdt/core/dom/StringLiteral.java | 7 +- .../wst/jsdt/core/dom/SuperFieldAccess.java | 2 +- .../org/eclipse/wst/jsdt/core/dom/SwitchCase.java | 2 +- .../eclipse/wst/jsdt/core/dom/SwitchStatement.java | 2 +- .../org/eclipse/wst/jsdt/core/dom/TagElement.java | 2 +- .../eclipse/wst/jsdt/core/dom/ThisExpression.java | 2 +- .../eclipse/wst/jsdt/core/dom/ThrowStatement.java | 2 +- .../eclipse/wst/jsdt/core/dom/TryStatement.java | 2 +- .../org/eclipse/wst/jsdt/core/dom/TypeBinding.java | 2 +- .../jsdt/core/dom/TypeDeclarationStatement.java | 2 +- .../org/eclipse/wst/jsdt/core/dom/TypeLiteral.java | 2 +- .../wst/jsdt/core/dom/UndefinedLiteral.java | 2 +- .../wst/jsdt/core/dom/VariableDeclaration.java | 2 +- .../core/dom/VariableDeclarationExpression.java | 2 +- .../jsdt/core/dom/VariableDeclarationFragment.java | 2 +- .../eclipse/wst/jsdt/core/dom/WhileStatement.java | 2 +- .../eclipse/wst/jsdt/core/dom/WithStatement.java | 2 +- .../wst/jsdt/core/dom/rewrite/ListRewrite.java | 2 +- .../core/formatter/CodeFormatterApplication.java | 2 +- .../wst/jsdt/core/formatter/messages.properties | 5 +- .../jsdt/core/infer/DefaultInferrenceProvider.java | 16 +- .../wst/jsdt/core/infer/IInferEngineExtension.java | 21 + .../eclipse/wst/jsdt/core/infer/InferEngine.java | 5595 +++++--- .../eclipse/wst/jsdt/core/infer/InferOptions.java | 2 +- .../wst/jsdt/core/infer/InferredAttribute.java | 32 +- .../eclipse/wst/jsdt/core/infer/InferredType.java | 1411 +- .../wst/jsdt/core/infer/InferrenceManager.java | 117 +- .../wst/jsdt/core/infer/InferrenceProvider.java | 66 +- .../org/eclipse/wst/jsdt/core/messages.properties | 12 + .../wst/jsdt/core/search/FieldReferenceMatch.java | 2 +- .../wst/jsdt/core/search/MethodReferenceMatch.java | 2 +- .../wst/jsdt/core/search/ModuleMatchRequestor.java | 21 + .../eclipse/wst/jsdt/core/search/SearchEngine.java | 1520 +- .../eclipse/wst/jsdt/core/search/SearchMatch.java | 2 +- .../wst/jsdt/core/search/SearchPattern.java | 3839 +++-- .../wst/jsdt/core/search/TypeNameMatch.java | 14 +- .../jsdt/internal/codeassist/CompletionEngine.java | 2465 ++-- .../jsdt/internal/codeassist/ISearchRequestor.java | 46 +- .../codeassist/InternalCompletionProposal.java | 32 +- .../internal/codeassist/MissingTypesGuesser.java | 28 +- .../internal/codeassist/RelevanceConstants.java | 13 +- .../jsdt/internal/codeassist/SelectionEngine.java | 101 +- .../codeassist/UnresolvedReferenceNameFinder.java | 4 +- .../CompletionOnExplicitConstructorCall.java | 2 +- .../complete/CompletionOnImportReference.java | 2 +- .../codeassist/complete/CompletionOnKeyword2.java | 2 +- .../complete/CompletionOnMessageSend.java | 2 +- .../complete/CompletionOnSingleNameReference.java | 2 +- .../codeassist/complete/CompletionParser.java | 4 +- .../wst/jsdt/internal/codeassist/impl/Engine.java | 7 +- .../select/SelectionOnImportReference.java | 2 +- .../codeassist/select/SelectionOnLocalName.java | 2 +- .../codeassist/select/SelectionOnMethodName.java | 49 + .../select/SelectionOnPackageReference.java | 2 +- .../select/SelectionOnSingleNameReference.java | 17 + .../codeassist/select/SelectionParser.java | 76 + .../wst/jsdt/internal/compiler/Compiler.java | 105 +- .../internal/compiler/ISourceElementRequestor.java | 22 +- .../internal/compiler/SourceElementParser.java | 526 +- .../wst/jsdt/internal/compiler/ast/ASTNode.java | 6 +- .../compiler/ast/AbstractMethodDeclaration.java | 474 +- .../compiler/ast/AbstractVariableDeclaration.java | 36 +- .../wst/jsdt/internal/compiler/ast/Argument.java | 32 +- .../internal/compiler/ast/ArrayInitializer.java | 6 +- .../compiler/ast/ArrayQualifiedTypeReference.java | 2 +- .../wst/jsdt/internal/compiler/ast/Assignment.java | 415 +- .../wst/jsdt/internal/compiler/ast/Clinit.java | 8 +- .../compiler/ast/CompilationUnitDeclaration.java | 126 +- .../compiler/ast/ConditionalExpression.java | 6 +- .../compiler/ast/ConstructorDeclaration.java | 44 +- .../compiler/ast/ExplicitConstructorCall.java | 2 +- .../wst/jsdt/internal/compiler/ast/Expression.java | 50 +- .../internal/compiler/ast/FieldDeclaration.java | 367 +- .../jsdt/internal/compiler/ast/FieldReference.java | 808 +- .../internal/compiler/ast/FunctionExpression.java | 18 +- .../internal/compiler/ast/ImportReference.java | 2 +- .../wst/jsdt/internal/compiler/ast/Javadoc.java | 2 +- .../internal/compiler/ast/LocalDeclaration.java | 318 +- .../jsdt/internal/compiler/ast/MessageSend.java | 613 +- .../internal/compiler/ast/MethodDeclaration.java | 59 +- .../jsdt/internal/compiler/ast/ObjectLiteral.java | 19 +- .../compiler/ast/QualifiedNameReference.java | 41 +- .../internal/compiler/ast/ReturnStatement.java | 301 +- .../internal/compiler/ast/SingleNameReference.java | 293 +- .../jsdt/internal/compiler/ast/SuperReference.java | 2 +- .../internal/compiler/ast/SwitchStatement.java | 5 +- .../jsdt/internal/compiler/ast/ThisReference.java | 25 +- .../jsdt/internal/compiler/ast/ThrowStatement.java | 5 +- .../internal/compiler/ast/TypeDeclaration.java | 65 +- .../internal/compiler/batch/ClasspathFile.java | 6 +- .../internal/compiler/batch/CompilationUnit.java | 8 +- .../internal/compiler/batch/messages.properties | 7 +- .../jsdt/internal/compiler/env/ClassSignature.java | 2 +- .../flow/ExceptionHandlingFlowContext.java | 4 +- .../jsdt/internal/compiler/flow/FlowContext.java | 4 +- .../internal/compiler/impl/CompilerOptions.java | 9 +- .../jsdt/internal/compiler/impl/IntConstant.java | 2 +- .../internal/compiler/lookup/ArrayBinding.java | 4 +- .../compiler/lookup/BinaryTypeBinding.java | 4 +- .../jsdt/internal/compiler/lookup/BlockScope.java | 140 +- .../jsdt/internal/compiler/lookup/ClassScope.java | 121 +- .../compiler/lookup/CombinedSourceTypeBinding.java | 14 +- .../compiler/lookup/CompilationUnitBinding.java | 10 +- .../compiler/lookup/CompilationUnitScope.java | 2220 +-- .../compiler/lookup/ExtraCompilerModifiers.java | 2 +- .../internal/compiler/lookup/FieldBinding.java | 17 +- .../compiler/lookup/FunctionTypeBinding.java | 9 +- .../internal/compiler/lookup/GlobalBinding.java | 10 + .../internal/compiler/lookup/ImportBinding.java | 2 +- .../compiler/lookup/LibraryAPIsBinding.java | 2 +- .../internal/compiler/lookup/LibraryAPIsScope.java | 2 +- .../internal/compiler/lookup/LocalTypeBinding.java | 27 +- .../compiler/lookup/LocalVariableBinding.java | 25 +- .../compiler/lookup/LookupEnvironment.java | 1839 +-- .../compiler/lookup/MemberTypeBinding.java | 4 +- .../compiler/lookup/MetatdataTypeBinding.java | 1466 +- .../internal/compiler/lookup/MethodBinding.java | 1241 +- .../jsdt/internal/compiler/lookup/MethodScope.java | 208 +- .../internal/compiler/lookup/MethodVerifier.java | 10 +- .../compiler/lookup/MissingBinaryTypeBinding.java | 4 +- .../compiler/lookup/MultipleTypeBinding.java | 2 +- .../internal/compiler/lookup/PackageBinding.java | 8 +- .../internal/compiler/lookup/ProblemReasons.java | 2 +- .../internal/compiler/lookup/ReferenceBinding.java | 38 +- .../wst/jsdt/internal/compiler/lookup/Scope.java | 157 +- .../compiler/lookup/SourceTypeBinding.java | 2564 +++- .../wst/jsdt/internal/compiler/lookup/TagBits.java | 2 +- .../jsdt/internal/compiler/lookup/TypeBinding.java | 6 +- .../wst/jsdt/internal/compiler/messages.properties | 5 +- .../compiler/parser/AbstractCommentParser.java | 9 +- .../internal/compiler/parser/JavadocParser.java | 2 - .../wst/jsdt/internal/compiler/parser/Parser.java | 14227 ++++++++++--------- .../compiler/parser/ParserBasicInformation.java | 2 +- .../compiler/parser/SourceTypeConverter.java | 4 +- .../compiler/parser/readableNames.properties | 13 + .../internal/compiler/problem/ProblemReporter.java | 15 +- .../internal/compiler/problem/messages.properties | 10 +- .../jsdt/internal/compiler/util/EclipseUtil.java | 71 - .../internal/compiler/util/SuffixConstants.java | 11 +- .../wst/jsdt/internal/compiler/util/Util.java | 75 +- .../eclipse/wst/jsdt/internal/core/BinaryType.java | 5 +- .../jsdt/internal/core/BinaryTypeConverter.java | 4 +- .../internal/core/CancelableProblemFactory.java | 9 +- .../eclipse/wst/jsdt/internal/core/ClassFile.java | 73 +- .../wst/jsdt/internal/core/CompilationUnit.java | 2611 ++-- .../core/CompilationUnitProblemFinder.java | 13 +- .../core/CompilationUnitStructureRequestor.java | 37 +- .../core/CopyPackageFragmentRootOperation.java | 2 +- .../wst/jsdt/internal/core/DeltaProcessor.java | 55 +- .../wst/jsdt/internal/core/JarEntryDirectory.java | 60 + .../wst/jsdt/internal/core/JarEntryFile.java | 77 + .../wst/jsdt/internal/core/JarEntryResource.java | 98 + .../wst/jsdt/internal/core/JarPackageFragment.java | 280 + .../jsdt/internal/core/JarPackageFragmentInfo.java | 23 + .../jsdt/internal/core/JarPackageFragmentRoot.java | 300 + .../internal/core/JarPackageFragmentRootInfo.java | 21 + .../core/JavaCorePreferenceInitializer.java | 2 +- .../eclipse/wst/jsdt/internal/core/JavaModel.java | 5 +- .../wst/jsdt/internal/core/JavaModelManager.java | 9 +- .../wst/jsdt/internal/core/JavaProject.java | 37 +- .../jsdt/internal/core/JavaProjectElementInfo.java | 4 +- .../org/eclipse/wst/jsdt/internal/core/Member.java | 50 + .../wst/jsdt/internal/core/MetadataFile.java | 9 +- .../eclipse/wst/jsdt/internal/core/NameLookup.java | 21 +- .../wst/jsdt/internal/core/NamedMember.java | 17 +- .../wst/jsdt/internal/core/PackageFragment.java | 9 +- .../jsdt/internal/core/PackageFragmentRoot.java | 8 +- .../core/ReconcileWorkingCopyOperation.java | 10 +- .../jsdt/internal/core/SearchableEnvironment.java | 479 +- .../wst/jsdt/internal/core/SelectionRequestor.java | 8 +- .../jsdt/internal/core/SourceConstructorInfo.java | 2 +- .../wst/jsdt/internal/core/SourceMapper.java | 12 +- .../wst/jsdt/internal/core/SourceMethod.java | 13 +- .../wst/jsdt/internal/core/SourceMethodInfo.java | 2 +- .../eclipse/wst/jsdt/internal/core/SourceType.java | 1431 +- .../jsdt/internal/core/SourceTypeElementInfo.java | 4 +- .../core/builder/AbstractImageBuilder.java | 2 +- .../internal/core/builder/BatchImageBuilder.java | 2 +- .../core/builder/ICompilationUnitLocator.java | 2 +- .../core/builder/IncrementalImageBuilder.java | 5 +- .../core/builder/ValidationParticipantResult.java | 2 +- .../core/dom/rewrite/ASTRewriteAnalyzer.java | 17 +- .../core/dom/rewrite/ASTRewriteFlattener.java | 2 +- .../core/hierarchy/HierarchyBinaryType.java | 2 +- .../internal/core/hierarchy/HierarchyBuilder.java | 15 +- .../internal/core/hierarchy/HierarchyResolver.java | 1748 +-- .../core/hierarchy/IndexBasedHierarchyBuilder.java | 918 +- .../core/hierarchy/RegionBasedTypeHierarchy.java | 6 +- .../internal/core/hierarchy/TypeHierarchy.java | 1936 +-- .../wst/jsdt/internal/core/index/DiskIndex.java | 66 +- .../wst/jsdt/internal/core/index/Index.java | 11 + .../core/index/PostponedRunnablesManager.java | 365 + .../internal/core/interpret/InterpreterEngine.java | 4 +- .../internal/core/search/BasicSearchEngine.java | 1316 +- .../jsdt/internal/core/search/HierarchyScope.java | 2 +- .../internal/core/search/IFunctionRequester.java | 41 + .../internal/core/search/IModuleRequestor.java | 46 + .../search/IRestrictedAccessTypeRequestor.java | 2 +- .../internal/core/search/IVariableRequester.java | 38 + .../internal/core/search/IndexQueryRequestor.java | 18 +- .../jsdt/internal/core/search/IndexSelector.java | 6 +- .../internal/core/search/JavaSearchDocument.java | 9 +- .../core/search/JavaSearchParticipant.java | 9 +- .../jsdt/internal/core/search/JavaSearchScope.java | 36 +- .../core/search/JavaSearchTypeNameMatch.java | 19 +- .../core/search/ModuleMatchRequestorWrapper.java | 237 + .../core/search/TypeNameMatchRequestorWrapper.java | 443 +- .../core/search/TypeNameRequestorWrapper.java | 2 +- .../core/search/indexing/AbstractIndexer.java | 119 +- .../core/search/indexing/AddJarFileToIndex.java | 254 + .../search/indexing/AddLibraryFileToIndex.java | 187 +- .../core/search/indexing/IIndexConstants.java | 70 +- .../core/search/indexing/IndexManager.java | 54 +- .../core/search/indexing/IndexingParser.java | 2 +- .../core/search/indexing/SourceIndexer.java | 67 +- .../search/indexing/SourceIndexerRequestor.java | 31 +- .../search/matching/ClassFileMatchLocator.java | 35 +- .../matching/ConstructorDeclarationPattern.java | 250 - .../core/search/matching/ConstructorLocator.java | 630 +- .../core/search/matching/ConstructorPattern.java | 821 +- .../DeclarationOfAccessedFieldsPattern.java | 4 +- .../DeclarationOfReferencedMethodsPattern.java | 4 +- .../core/search/matching/FieldLocator.java | 15 +- .../core/search/matching/FieldPattern.java | 577 +- .../core/search/matching/MatchLocator.java | 45 +- .../core/search/matching/MatchLocatorParser.java | 21 +- .../core/search/matching/MatchingNodeSet.java | 2 +- .../core/search/matching/MethodLocator.java | 120 +- .../core/search/matching/MethodPattern.java | 937 +- .../matching/MultiTypeDeclarationPattern.java | 333 +- .../internal/core/search/matching/OrLocator.java | 2 +- .../internal/core/search/matching/OrPattern.java | 26 +- .../search/matching/PackageReferenceLocator.java | 2 +- .../core/search/matching/PatternLocator.java | 59 +- .../matching/QualifiedTypeDeclarationPattern.java | 123 - .../matching/SecondaryTypeDeclarationPattern.java | 8 +- .../search/matching/SuperTypeNamesCollector.java | 20 +- .../search/matching/SuperTypeReferenceLocator.java | 12 +- .../search/matching/SuperTypeReferencePattern.java | 298 +- .../search/matching/TypeDeclarationLocator.java | 41 +- .../search/matching/TypeDeclarationPattern.java | 842 +- .../core/search/matching/TypeReferenceLocator.java | 2 +- .../core/search/matching/TypeSynonymsPattern.java | 180 + .../core/search/matching/VariableLocator.java | 2 +- .../wst/jsdt/internal/core/util/ASTNodeFinder.java | 8 +- .../jsdt/internal/core/util/BindingKeyParser.java | 5 +- .../internal/core/util/BindingKeyResolver.java | 4 +- .../jsdt/internal/core/util/ConvertUtility.java | 92 +- .../core/util/DefaultSourcePathProvider.java | 6 - .../wst/jsdt/internal/core/util/HandleFactory.java | 80 +- .../jsdt/internal/core/util/KeyToSignature.java | 4 +- .../wst/jsdt/internal/core/util/Messages.java | 4 +- .../wst/jsdt/internal/core/util/PublicScanner.java | 2 +- .../internal/core/util/QualificationHelpers.java | 236 + .../internal/core/util/ReferenceInfoAdapter.java | 4 +- .../core/util/ResourceCompilationUnit.java | 2 +- .../eclipse/wst/jsdt/internal/core/util/Util.java | 15 +- .../jsdt/internal/core/util/messages.properties | 25 +- .../internal/formatter/CodeFormatterVisitor.java | 10 +- .../internal/formatter/DefaultCodeFormatter.java | 4 +- .../wst/jsdt/internal/formatter/options.properties | 5 +- .../wst/jsdt/internal/oaametadata/Alias.java | 10 + .../wst/jsdt/internal/oaametadata/Author.java | 10 + .../oaametadata/DepreciatedOrAvailable.java | 10 + .../wst/jsdt/internal/oaametadata/Enum.java | 10 + .../jsdt/internal/oaametadata/MetadataReader.java | 2 +- .../wst/jsdt/launching/AbstractVMInstallType.java | 2 +- .../wst/jsdt/launching/ExecutionArguments.java | 2 +- .../jsdt/launching/IRuntimeClasspathEntry2.java | 2 +- .../jsdt/launching/IRuntimeClasspathProvider.java | 2 +- .../org/eclipse/wst/jsdt/launching/IVMInstall.java | 2 +- .../eclipse/wst/jsdt/launching/IVMInstall2.java | 2 +- .../eclipse/wst/jsdt/launching/IVMInstall3.java | 2 +- .../eclipse/wst/jsdt/launching/IVMInstallType.java | 2 +- .../org/eclipse/wst/jsdt/launching/IVMRunner.java | 2 +- .../eclipse/wst/jsdt/launching/JREContainer.java | 8 - .../jsdt/launching/JREContainerInitializer.java | 4 +- .../eclipse/wst/jsdt/launching/JavaRuntime.java | 6 +- .../jsdt/launching/LaunchingMessages.properties | 4 +- .../wst/jsdt/launching/LibraryLocation.java | 2 +- .../eclipse/wst/jsdt/launching/StandardVMType.java | 2 +- .../wst/jsdt/launching/VMRunnerConfiguration.java | 2 +- .../org/eclipse/wst/jsdt/launching/VMStandin.java | 2 +- ...erLibraryJsGlobalScopeContainerInitializer.java | 51 +- .../wst/jsdt/libraries/BasicLibraryContainer.java | 22 + .../org/eclipse/wst/jsdt/libraries/Messages.java | 4 + .../eclipse/wst/jsdt/libraries/messages.properties | 7 +- bundles/org.eclipse.wst.jsdt.manipulation/.project | 62 +- .../plugin.properties | 4 +- .../JavaManipulationMessages.properties | 5 +- .../descriptors/DescriptorMessages.properties | 5 +- .../org.eclipse.wst.jsdt.support.firefox/.project | 74 +- .../META-INF/MANIFEST.MF | 4 +- .../plugin.properties | 9 +- .../jsdt/internal/ui/wizards/FirefoxMessages.java | 10 + .../internal/ui/wizards/FirefoxMessages.properties | 4 +- bundles/org.eclipse.wst.jsdt.support.ie/.project | 74 +- .../META-INF/MANIFEST.MF | 4 +- .../plugin.properties | 7 +- .../wst/jsdt/internal/ui/wizards/IEMessages.java | 10 + .../jsdt/internal/ui/wizards/IEMessages.properties | 4 +- bundles/org.eclipse.wst.jsdt.ui/.options | 1 + bundles/org.eclipse.wst.jsdt.ui/.project | 67 +- .../.settings/org.eclipse.jdt.core.prefs | 504 +- .../.settings/org.eclipse.jdt.ui.prefs | 105 +- .../org.eclipse.wst.jsdt.ui/META-INF/MANIFEST.MF | 4 +- bundles/org.eclipse.wst.jsdt.ui/about.html | 2 +- bundles/org.eclipse.wst.jsdt.ui/about.properties | 4 +- bundles/org.eclipse.wst.jsdt.ui/build.properties | 4 +- .../icons/full/etool16/loading1.gif | Bin 0 -> 355 bytes .../icons/full/etool16/loading2.gif | Bin 0 -> 348 bytes .../icons/full/etool16/loading3.gif | Bin 0 -> 353 bytes .../icons/full/etool16/loading4.gif | Bin 0 -> 349 bytes bundles/org.eclipse.wst.jsdt.ui/plugin.properties | 4 +- bundles/org.eclipse.wst.jsdt.ui/plugin.xml | 196 +- .../schema/JsGlobalScopeContainerPage.exsd | 31 +- .../schema/javadocCompletionProcessor.exsd | 2 +- .../jsdt/internal/corext/CorextMessages.properties | 5 +- .../internal/corext/buildpath/BuildpathDelta.java | 2 +- .../internal/corext/buildpath/CPJavaProject.java | 2 +- .../callhierarchy/CallHierarchyMessages.properties | 5 +- .../corext/callhierarchy/IImplementorFinder.java | 2 +- .../callhierarchy/JavaImplementorFinder.java | 2 +- .../codemanipulation/CodeGenerationMessages.java | 2 +- .../CodeGenerationMessages.properties | 5 +- .../jsdt/internal/corext/fix/CleanUpConstants.java | 2 +- .../wst/jsdt/internal/corext/fix/FixMessages.java | 2 +- .../internal/corext/fix/FixMessages.properties | 5 +- .../corext/javadoc/JavaDocCommentReader.java | 57 +- .../refactoring/IRefactoringSearchRequestor.java | 2 +- .../refactoring/JavaRefactoringArguments.java | 2 +- .../binary/SourceCreationOperation.java | 2 +- .../refactoring/binary/StubCreationOperation.java | 2 +- .../changes/RefactoringDescriptorChange.java | 2 +- .../changes/UndoCompilationUnitChange.java | 2 +- .../refactoring/code/ExtractTempRefactoring.java | 2 +- .../corext/refactoring/code/LocalTypeAnalyzer.java | 2 +- .../refactoring/code/flow/ReturnFlowInfo.java | 2 +- .../corext/refactoring/nls/NLSElement.java | 2 +- .../corext/refactoring/nls/NLSMessages.properties | 5 +- .../corext/refactoring/nls/NLSSubstitution.java | 2 +- .../nls/changes/NLSChangesMessages.properties | 5 +- .../participants/ResourceModifications.java | 2 +- .../corext/refactoring/refactoring.properties | 5 +- .../refactoring/rename/JavaRenameRefactoring.java | 2 +- .../refactoring/rename/RenameAnalyzeUtil.java | 4 +- .../refactoring/rename/RenameMethodProcessor.java | 28 +- .../reorg/CreateTargetExecutionLog.java | 2 +- .../reorg/JDTCopyRefactoringDescriptor.java | 2 +- .../reorg/JDTMoveRefactoringDescriptor.java | 2 +- .../refactoring/reorg/JavaCopyRefactoring.java | 2 +- .../refactoring/reorg/JavaDeleteRefactoring.java | 2 +- .../reorg/MonitoringCreateTargetQueries.java | 2 +- .../corext/refactoring/reorg/NullReorgQueries.java | 2 +- ...angeMethodSignatureRefactoringContribution.java | 2 +- .../ChangeTypeRefactoringContribution.java | 2 +- .../ConvertAnonymousRefactoringContribution.java | 2 +- .../scripting/CopyRefactoringContribution.java | 2 +- .../scripting/DeleteRefactoringContribution.java | 2 +- .../ExtractMethodRefactoringContribution.java | 2 +- .../ExtractSupertypeRefactoringContribution.java | 2 +- .../InlineConstantRefactoringContribution.java | 2 +- .../InlineTempRefactoringContribution.java | 2 +- .../IntroduceFactoryRefactoringContribution.java | 2 +- ...ntroduceIndirectionRefactoringContribution.java | 2 +- .../IntroduceParameterRefactoringContribution.java | 2 +- .../MoveMemberTypeRefactoringContribution.java | 2 +- .../MoveMethodRefactoringContribution.java | 2 +- .../scripting/MoveRefactoringContribution.java | 2 +- .../MoveStaticMembersRefactoringContribution.java | 2 +- .../PromoteTempToFieldRefactoringContribution.java | 2 +- .../scripting/PullUpRefactoringContribution.java | 2 +- .../scripting/PushDownRefactoringContribution.java | 2 +- .../SelfEncapsulateRefactoringContribution.java | 2 +- .../UseSupertypeRefactoringContribution.java | 2 +- .../structure/ExtractSupertypeRefactoring.java | 2 +- .../refactoring/structure/JavaMoveRefactoring.java | 2 +- .../refactoring/tagging/ICommentProvider.java | 2 +- .../refactoring/tagging/IDelegateUpdating.java | 2 +- .../tagging/IScriptableRefactoring.java | 2 +- .../tagging/ISimilarDeclarationUpdating.java | 2 +- .../template/java/CodeTemplateContextType.java | 2 +- .../template/java/CompilationUnitCompletion.java | 10 +- .../corext/template/java/ElementTypeResolver.java | 2 +- .../template/java/ExclusivePositionUpdater.java | 2 +- .../corext/template/java/FieldResolver.java | 2 +- .../internal/corext/template/java/JavaContext.java | 2 +- .../corext/template/java/JavaTemplateMessages.java | 2 +- .../template/java/JavaTemplateMessages.properties | 5 +- .../corext/template/java/JavaVariable.java | 2 +- .../corext/template/java/LocalVarResolver.java | 2 +- .../corext/template/java/NameResolver.java | 2 +- .../internal/corext/template/java/TemplateSet.java | 2 +- .../corext/template/java/TypeVariableResolver.java | 2 +- .../internal/corext/template/java/VarResolver.java | 2 +- .../wst/jsdt/internal/corext/util/Messages.java | 2 +- .../wst/jsdt/internal/corext/util/SearchUtils.java | 2 +- .../wst/jsdt/internal/ui/IJavaStatusConstants.java | 2 +- .../jsdt/internal/ui/JavaPerspectiveFactory.java | 32 +- .../wst/jsdt/internal/ui/JavaPluginImages.java | 12 +- .../wst/jsdt/internal/ui/JavaScriptPlugin.java | 2 +- .../wst/jsdt/internal/ui/JavaTaskListAdapter.java | 8 +- .../wst/jsdt/internal/ui/JavaUIMessages.java | 2 +- .../wst/jsdt/internal/ui/JavaUIMessages.properties | 4 +- .../org/eclipse/wst/jsdt/internal/ui/Logger.java | 4 + .../wst/jsdt/internal/ui/ProductProperties.java | 2 +- .../ui/actions/AbstractToggleLinkingAction.java | 2 +- .../internal/ui/actions/ActionMessages.properties | 4 +- .../internal/ui/actions/BlockCommentAction.java | 2 +- .../ui/actions/ConfigureContainerAction.java | 22 +- .../jsdt/internal/ui/actions/FoldingMessages.java | 2 +- .../internal/ui/actions/FoldingMessages.properties | 5 +- .../jsdt/internal/ui/actions/QuickMenuAction.java | 2 +- .../internal/ui/actions/SelectionConverter.java | 4 +- .../internal/ui/browsing/IPackagesViewViewer.java | 2 +- .../ui/browsing/JavaBrowsingMessages.properties | 4 +- .../internal/ui/browsing/ToggleLinkingAction.java | 2 +- .../callhierarchy/CallHierarchyMessages.properties | 4 +- .../ui/compare/AddFromHistoryAction.properties | 4 +- .../internal/ui/compare/CompareAction.properties | 4 +- .../jsdt/internal/ui/compare/CompareMessages.java | 2 +- .../internal/ui/compare/CompareMessages.properties | 5 +- .../ui/compare/CompareWithEditionAction.properties | 4 +- .../ui/compare/EclipsePreferencesAdapter.java | 2 +- .../internal/ui/compare/JavaTokenComparator.java | 2 +- .../ui/compare/ReplaceWithEditionAction.properties | 4 +- .../internal/ui/dialogs/DialogsMessages.properties | 4 +- .../ui/dialogs/FilteredTypesSelectionDialog.java | 3331 ++--- .../internal/ui/dialogs/OverrideMethodDialog.java | 42 +- .../jsdt/internal/ui/dialogs/TypeInfoViewer.java | 2 +- .../internal/ui/dialogs/TypeSelectionDialog2.java | 2 +- .../internal/ui/filters/CustomFiltersDialog.java | 2 +- .../wst/jsdt/internal/ui/filters/FieldsFilter.java | 2 +- .../internal/ui/filters/FilterMessages.properties | 4 +- .../jsdt/internal/ui/filters/LibraryFilter.java | 9 +- .../jsdt/internal/ui/filters/NonPublicFilter.java | 2 +- .../jsdt/internal/ui/filters/StaticsFilter.java | 2 +- .../internal/ui/fix/MultiFixMessages.properties | 5 +- .../ui/fix/SaveParticipantMessages.properties | 5 +- .../jsdt/internal/ui/fix/UnusedCodeCleanUp.java | 2 +- .../internal/ui/infoviews/AbstractInfoView.java | 2 +- .../ui/infoviews/InfoViewMessages.properties | 5 +- .../jsdt/internal/ui/infoviews/JavadocView.java | 26 +- .../ui/javadocexport/JavadocExportMessages.java | 2 +- .../javadocexport/JavadocExportMessages.properties | 4 +- .../javadocexport/JavadocSpecificsWizardPage.java | 2 +- .../jsdt/internal/ui/javaeditor/ASTProvider.java | 2 +- ...asicCompilationUnitEditorActionContributor.java | 2 +- .../CompilationUnitDocumentProvider.java | 10 +- .../ui/javaeditor/CompilationUnitEditor.java | 2 +- .../ConstructedJavaEditorMessages.properties | 6 +- .../javaeditor/EditorHighlightingSynchronizer.java | 2 +- .../jsdt/internal/ui/javaeditor/EditorUtility.java | 5 +- .../ui/javaeditor/ICompoundEditListener.java | 2 +- .../javaeditor/InternalClassFileEditorInput.java | 8 +- .../ui/javaeditor/JavaAnnotationImageProvider.java | 2 +- .../ui/javaeditor/JavaAnnotationIterator.java | 2 +- .../jsdt/internal/ui/javaeditor/JavaEditor.java | 2 +- .../internal/ui/javaeditor/JavaEditorMessages.java | 2 +- .../ui/javaeditor/JavaEditorMessages.properties | 4 +- .../ui/javaeditor/JavaElementHyperlink.java | 2 +- .../javaeditor/JavaElementHyperlinkDetector.java | 54 +- .../internal/ui/javaeditor/JavaOutlinePage.java | 2 +- .../javaeditor/OverrideIndicatorImageProvider.java | 2 +- .../ui/javaeditor/RemoveOccurrenceAnnotations.java | 2 +- .../javaeditor/SpecificContentAssistExecutor.java | 2 +- .../ISaveParticipantPreferenceConfiguration.java | 2 +- .../saveparticipant/SaveParticipantDescriptor.java | 2 +- .../saveparticipant/SaveParticipantMessages.java | 2 +- .../SaveParticipantMessages.properties | 4 +- .../selectionactions/SelectionActionMessages.java | 2 +- .../SelectionActionMessages.properties | 4 +- .../internal/ui/model/JavaModelAdapterFactory.java | 2 +- .../JavaRefactoringDescriptorResourceMapping.java | 2 +- .../JavaRefactoringHistoryResourceMapping.java | 2 +- .../internal/ui/model/JavaResourceMapping.java | 2 +- .../internal/ui/model/ModelMessages.properties | 5 +- .../ui/navigator/CommonLayoutActionGroup.java | 2 +- .../ui/navigator/JavaNavigatorContentProvider.java | 20 +- .../ui/navigator/JavaNavigatorLabelProvider.java | 2 +- .../PackageExplorerOpenActionProvider.java | 11 +- .../ui/navigator/deferred/ClearPlaceHolderJob.java | 49 + .../ui/navigator/deferred/LoadingModelNode.java | 167 + .../deferred/LoadingModelUIAnimationJob.java | 54 + .../ui/navigator/deferred/NonConflictingRule.java | 25 + .../ui/packageview/GotoRequiredProjectAction.java | 11 +- .../internal/ui/packageview/LayoutActionGroup.java | 2 +- .../internal/ui/packageview/LibraryContainer.java | 9 +- .../PackageExplorerContentProvider.java | 78 +- .../packageview/PackageExplorerLabelProvider.java | 9 +- .../ui/packageview/PackageExplorerPart.java | 2 +- .../internal/ui/packageview/PackagesMessages.java | 4 +- .../ui/packageview/PackagesMessages.properties | 8 +- .../ui/packageview/ToggleLinkingAction.java | 2 +- .../WorkingSetAwareContentProvider.java | 2 +- .../ui/preferences/AbstractConfigurationBlock.java | 2 +- .../ui/preferences/AppearancePreferencePage.java | 2 +- .../ui/preferences/BuildPathsPropertyPage.java | 4 +- .../CodeAssistFavoritesPreferencePage.java | 2 +- .../ui/preferences/CodeAssistPreferencePage.java | 2 +- .../preferences/CodeFormatterPreferencePage.java | 2 +- .../ui/preferences/ColorSettingPreviewCode.txt | 2 +- .../IPreferenceAndPropertyConfigurationBlock.java | 2 +- .../preferences/IPreferenceConfigurationBlock.java | 2 +- .../preferences/JavaBuildConfigurationBlock.java | 2 +- .../JavaEditorAppearanceConfigurationBlock.java | 2 +- .../ui/preferences/JavadocConfigurationBlock.java | 2 +- .../JavadocProblemsConfigurationBlock.java | 2 +- .../MarkOccurrencesConfigurationBlock.java | 2 +- .../ui/preferences/MockupPreferenceStore.java | 2 +- .../ui/preferences/OverlayPreferenceStore.java | 2 +- .../ui/preferences/PreferencesMessages.properties | 5 +- .../ui/preferences/cleanup/CleanUpMessages.java | 2 +- .../preferences/cleanup/CleanUpMessages.properties | 5 +- .../ui/preferences/cleanup/CodeStyleTabPage.java | 2 +- .../ui/preferences/formatter/BracesTabPage.java | 2 +- .../formatter/FormatterMessages.properties | 7 +- .../ui/refactoring/ExtractSupertypeWizard.java | 2 +- .../ui/refactoring/IntroduceIndirectionWizard.java | 2 +- .../ui/refactoring/nls/NLSUIMessages.properties | 4 +- .../nls/search/NLSSearchMessages.properties | 4 +- .../ui/refactoring/refactoringui.properties | 4 +- .../ui/refactoring/reorg/RenameLinkedMode.java | 36 + .../reorg/RenameTypeWizardInputPage.java | 2 +- ...nameTypeWizardSimilarElementsOptionsDialog.java | 2 +- .../ui/refactoring/reorg/ReorgMessages.properties | 4 +- .../jsdt/internal/ui/search/JavaSearchQuery.java | 2 +- .../internal/ui/search/SearchMessages.properties | 4 +- .../jsdt/internal/ui/text/AbstractJavaScanner.java | 2 +- .../jsdt/internal/ui/text/CombinedWordRule.java | 2 +- .../ui/text/CompositeReconcilingStrategy.java | 2 +- .../ui/text/DocumentCharacterIterator.java | 2 +- .../internal/ui/text/FastJavaPartitionScanner.java | 2 +- .../jsdt/internal/ui/text/HTMLAnnotationHover.java | 2 +- .../jsdt/internal/ui/text/ITypingRunListener.java | 2 +- .../jsdt/internal/ui/text/JavaBreakIterator.java | 2 +- .../wst/jsdt/internal/ui/text/JavaChangeHover.java | 2 +- .../jsdt/internal/ui/text/JavaColorManager.java | 2 +- .../ui/text/JavaOutlineInformationControl.java | 2 +- .../ui/text/JavaPresentationReconciler.java | 2 +- .../jsdt/internal/ui/text/JavaWordIterator.java | 2 +- .../ui/text/SequenceCharacterIterator.java | 2 +- .../internal/ui/text/SmartBackspaceManager.java | 2 +- .../eclipse/wst/jsdt/internal/ui/text/Symbols.java | 2 +- .../jsdt/internal/ui/text/TextMessages.properties | 6 +- .../wst/jsdt/internal/ui/text/TypingRun.java | 2 +- .../jsdt/internal/ui/text/TypingRunDetector.java | 2 +- .../ui/text/comment/CommentFormattingContext.java | 2 +- .../text/correction/CorrectionMessages.properties | 4 +- .../text/correction/JavaCorrectionProcessor.java | 2 +- .../NewCUCompletionUsingWizardProposal.java | 101 +- .../folding/EmptyJavaFoldingPreferenceBlock.java | 2 +- .../ui/text/folding/FoldingMessages.properties | 5 +- .../JavaFoldingStructureProviderDescriptor.java | 2 +- .../ui/text/html/BrowserInformationControl.java | 2 +- .../jsdt/internal/ui/text/html/HTMLMessages.java | 2 +- .../internal/ui/text/html/HTMLMessages.properties | 5 +- .../jsdt/internal/ui/text/html/HTMLPrinter.java | 2 +- .../internal/ui/text/html/HTMLTextPresenter.java | 2 +- .../text/java/AbstractJavaCompletionProposal.java | 20 +- .../internal/ui/text/java/AlphabeticSorter.java | 2 +- .../java/CompletionProposalComputerDescriptor.java | 2 +- .../java/CompletionProposalComputerRegistry.java | 64 +- .../text/java/ContentAssistComputerParameter.java | 2 +- .../internal/ui/text/java/FieldProposalInfo.java | 148 +- .../ui/text/java/HippieProposalComputer.java | 2 +- .../ui/text/java/IProblemRequestorExtension.java | 2 +- .../ui/text/java/JavaCompletionProposal.java | 4 +- .../ui/text/java/JavaContentAssistHandler.java | 2 +- .../ui/text/java/JavaMethodCompletionProposal.java | 11 +- .../ui/text/java/JavaTextMessages.properties | 5 +- .../ui/text/java/JavaTypeCompletionProposal.java | 2 +- .../ui/text/java/JavadocDoubleClickStrategy.java | 2 +- .../ui/text/java/LazyJavaCompletionProposal.java | 2 +- .../text/java/LazyJavaTypeCompletionProposal.java | 6 +- .../internal/ui/text/java/MemberProposalInfo.java | 2 +- .../internal/ui/text/java/MethodProposalInfo.java | 96 +- .../jsdt/internal/ui/text/java/ProposalInfo.java | 33 +- .../internal/ui/text/java/RelevanceSorter.java | 2 +- .../java/hover/AbstractJavaEditorTextHover.java | 33 +- .../ui/text/java/hover/AnnotationHover.java | 2 +- .../ui/text/java/hover/BestMatchHover.java | 50 +- .../text/java/hover/JavaEditorTextHoverProxy.java | 42 +- .../ui/text/java/hover/JavaExpandHover.java | 2 +- .../text/java/hover/JavaHoverMessages.properties | 4 +- .../internal/ui/text/java/hover/JavadocHover.java | 17 +- .../internal/ui/text/java/hover/ProblemHover.java | 2 +- .../ui/text/javadoc/IHtmlTagConstants.java | 2 +- .../ui/text/javadoc/IJavaDocTagConstants.java | 2 +- .../ui/text/javadoc/JavaDocMessages.properties | 5 +- .../JavadocContentAssistInvocationContext.java | 2 +- .../engine/DefaultPhoneticDistanceAlgorithm.java | 2 +- .../engine/DefaultPhoneticHashProvider.java | 2 +- .../text/spelling/engine/DefaultSpellChecker.java | 2 +- .../engine/IPhoneticDistanceAlgorithm.java | 2 +- .../spelling/engine/IPhoneticHashProvider.java | 2 +- .../ui/text/spelling/engine/ISpellCheckEngine.java | 2 +- .../text/spelling/engine/ISpellCheckIterator.java | 2 +- .../ui/text/spelling/engine/ISpellChecker.java | 2 +- .../ui/text/spelling/engine/ISpellDictionary.java | 2 +- .../ui/text/spelling/engine/ISpellEvent.java | 2 +- .../text/spelling/engine/ISpellEventListener.java | 2 +- .../engine/LocaleSensitiveSpellDictionary.java | 2 +- .../text/spelling/engine/RankedWordProposal.java | 2 +- .../ui/text/spelling/engine/SpellEvent.java | 2 +- .../contentassist/InclusivePositionUpdater.java | 2 +- .../text/template/contentassist/MultiVariable.java | 2 +- .../template/contentassist/MultiVariableGuess.java | 2 +- .../TemplateContentAssistMessages.properties | 4 +- .../TemplateInformationControlCreator.java | 2 +- .../TemplatePreferencesMessages.properties | 4 +- .../internal/ui/typehierarchy/MethodsViewer.java | 2 +- .../ui/typehierarchy/ToggleLinkingAction.java | 2 +- .../typehierarchy/TypeHierarchyMessages.properties | 4 +- .../wst/jsdt/internal/ui/util/ConvertAction.java | 118 +- .../wst/jsdt/internal/ui/util/CoreUtility.java | 7 +- .../internal/ui/util/TableLayoutComposite.java | 2 +- .../ui/viewsupport/JavaElementImageProvider.java | 8 +- .../SelectionListenerWithASTManager.java | 37 +- .../ui/wizards/JavaProjectWizardFirstPage.java | 2 +- .../internal/ui/wizards/NewJSFileWizardPage.java | 136 +- .../wst/jsdt/internal/ui/wizards/NewJSWizard.java | 4 +- .../ui/wizards/NewWizardMessages.properties | 8 +- .../OpenJavaScriptFileWizardToolbarAction.java | 2 +- .../OpenJavaScriptProjectWizardToolbarAction.java | 2 +- .../internal/ui/wizards/TypedViewerFilter.java | 2 +- .../wizards/buildpaths/AddSourceFolderWizard.java | 2 +- .../ui/wizards/buildpaths/BuildPathWizard.java | 2 +- .../ui/wizards/buildpaths/CPListElement.java | 2 +- .../ui/wizards/buildpaths/CPListElementSorter.java | 2 +- .../ui/wizards/buildpaths/CPListLabelProvider.java | 2 +- .../wizards/buildpaths/CPUserLibraryElement.java | 2 +- .../CreateMultipleSourceFoldersDialog.java | 2 +- .../ui/wizards/buildpaths/EditFilterWizard.java | 2 +- .../JsGlobalScopeContainerSelectionPage.java | 2 +- .../wizards/buildpaths/ProjectsWorkbookPage.java | 2 +- .../wizards/buildpaths/SourceAttachmentBlock.java | 2 +- .../wizards/buildpaths/UserLibraryWizardPage.java | 2 +- .../newsourcepage/AddFolderToBuildpathAction.java | 2 +- .../newsourcepage/BuildpathModifierAction.java | 2 +- .../newsourcepage/ClasspathModifierQueries.java | 2 +- .../CreateLinkedSourceFolderAction.java | 2 +- .../newsourcepage/CreateSourceFolderAction.java | 2 +- .../newsourcepage/DialogPackageExplorer.java | 2 +- .../DialogPackageExplorerActionGroup.java | 2 +- .../buildpaths/newsourcepage/EditFilterAction.java | 2 +- .../buildpaths/newsourcepage/HintTextGroup.java | 2 +- .../NewSourceContainerWorkbookPage.java | 2 +- .../buildpaths/newsourcepage/ResetAllAction.java | 2 +- .../ui/wizards/dialogfields/ListDialogField.java | 2 +- .../workingsets/AbstractWorkingSetWizardPage.java | 2 +- .../ui/workingsets/ClearWorkingSetAction.java | 2 +- .../workingsets/WorkingSetFilterActionGroup.java | 2 +- .../WorkingSetMenuContributionItem.java | 2 +- .../ui/workingsets/WorkingSetMessages.properties | 4 +- .../BasicBrowserLibraryContainerUIExtension.java | 2 +- .../jsdt/ui/IJavaScriptElementSearchConstants.java | 2 +- .../src/org/eclipse/wst/jsdt/ui/ISharedImages.java | 2 +- .../eclipse/wst/jsdt/ui/JSdocContentAccess.java | 146 +- .../wst/jsdt/ui/JavaScriptElementComparator.java | 7 +- .../wst/jsdt/ui/JavaScriptElementLabels.java | 10 +- .../src/org/eclipse/wst/jsdt/ui/JavaScriptUI.java | 2 +- .../wst/jsdt/ui/ProblemsLabelDecorator.java | 2 +- .../eclipse/wst/jsdt/ui/ProjectLibraryRoot.java | 5 +- .../StandardJavaScriptElementContentProvider.java | 8 +- .../wst/jsdt/ui/actions/CCPActionGroup.java | 2 +- .../jsdt/ui/actions/DeclarationsSearchGroup.java | 2 +- .../wst/jsdt/ui/actions/ExtractMethodAction.java | 2 +- .../wst/jsdt/ui/actions/GenerateActionGroup.java | 2 +- .../ui/actions/IJavaEditorActionDefinitionIds.java | 2 +- .../jsdt/ui/actions/ImplementorsSearchGroup.java | 2 +- .../wst/jsdt/ui/actions/JavaSearchActionGroup.java | 2 +- .../wst/jsdt/ui/actions/JdtActionConstants.java | 2 +- .../jsdt/ui/actions/OccurrencesSearchGroup.java | 2 +- .../wst/jsdt/ui/actions/OpenEditorActionGroup.java | 2 +- .../jsdt/ui/actions/OpenNewClassWizardAction.java | 2 +- .../wst/jsdt/ui/actions/OpenViewActionGroup.java | 2 +- .../jsdt/ui/actions/ReadReferencesSearchGroup.java | 2 +- .../wst/jsdt/ui/actions/ReferencesSearchGroup.java | 2 +- .../jsdt/ui/actions/SelectionDispatchAction.java | 2 +- .../wst/jsdt/ui/actions/ShowActionGroup.java | 2 +- .../ui/actions/WriteReferencesSearchGroup.java | 2 +- .../org/eclipse/wst/jsdt/ui/messages.properties | 5 +- .../wst/jsdt/ui/search/ISearchRequestor.java | 2 +- .../text/JavaScriptSourceViewerConfiguration.java | 2 +- .../text/folding/IJavaFoldingPreferenceBlock.java | 2 +- .../folding/IJavaFoldingStructureProvider.java | 2 +- .../ui/text/java/CompletionProposalCollector.java | 21 +- .../ui/text/java/CompletionProposalComparator.java | 2 +- .../text/java/CompletionProposalLabelProvider.java | 149 +- .../text/java/IJavaCompletionProposalComputer.java | 2 +- .../wst/jsdt/ui/text/java/JavaTextMessages.java | 1 + .../jsdt/ui/text/java/JavaTextMessages.properties | 6 +- .../wst/jsdt/ui/wizards/BaseLibraryWizardPage.java | 112 +- .../wst/jsdt/ui/wizards/BuildPathDialogAccess.java | 2 +- .../ui/wizards/IJsGlobalScopeContainerPage.java | 26 +- .../wizards/JavaCapabilityConfigurationPage.java | 2 +- .../wst/jsdt/ui/wizards/NewElementWizardPage.java | 2 +- .../wst/jsdt/ui/wizards/NewTypeWizardPage.java | 2 +- .../templates/default-templates.properties | 4 +- .../unittests/internal/MasterJSDTTestSuite.java | 18 +- features/org.eclipse.wst.jsdt.feature/feature.xml | 243 +- 799 files changed, 42979 insertions(+), 38079 deletions(-) create mode 100644 bundles/org.eclipse.wst.jsdt.core/.options create mode 100644 bundles/org.eclipse.wst.jsdt.core/.settings/.api_filters create mode 100644 bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/IInferEngineExtension.java create mode 100644 bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/ModuleMatchRequestor.java create mode 100644 bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnMethodName.java delete mode 100644 bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/EclipseUtil.java create mode 100644 bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JarEntryDirectory.java create mode 100644 bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JarEntryFile.java create mode 100644 bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JarEntryResource.java create mode 100644 bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JarPackageFragment.java create mode 100644 bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JarPackageFragmentInfo.java create mode 100644 bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JarPackageFragmentRoot.java create mode 100644 bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JarPackageFragmentRootInfo.java create mode 100644 bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/index/PostponedRunnablesManager.java create mode 100644 bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/IFunctionRequester.java create mode 100644 bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/IModuleRequestor.java create mode 100644 bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/IVariableRequester.java create mode 100644 bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/ModuleMatchRequestorWrapper.java create mode 100644 bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/AddJarFileToIndex.java delete mode 100644 bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/ConstructorDeclarationPattern.java delete mode 100644 bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/QualifiedTypeDeclarationPattern.java create mode 100644 bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/TypeSynonymsPattern.java create mode 100644 bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/QualificationHelpers.java create mode 100644 bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/libraries/BasicLibraryContainer.java create mode 100644 bundles/org.eclipse.wst.jsdt.ui/icons/full/etool16/loading1.gif create mode 100644 bundles/org.eclipse.wst.jsdt.ui/icons/full/etool16/loading2.gif create mode 100644 bundles/org.eclipse.wst.jsdt.ui/icons/full/etool16/loading3.gif create mode 100644 bundles/org.eclipse.wst.jsdt.ui/icons/full/etool16/loading4.gif create mode 100644 bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/deferred/ClearPlaceHolderJob.java create mode 100644 bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/deferred/LoadingModelNode.java create mode 100644 bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/deferred/LoadingModelUIAnimationJob.java create mode 100644 bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/deferred/NonConflictingRule.java diff --git a/bundles/org.eclipse.wst.jsdt.core/.options b/bundles/org.eclipse.wst.jsdt.core/.options new file mode 100644 index 00000000..22cfe7ea --- /dev/null +++ b/bundles/org.eclipse.wst.jsdt.core/.options @@ -0,0 +1,60 @@ +# Turn on debug tracing for org.eclipse.wst.jsdt.core plugin +org.eclipse.wst.jsdt.core/debug=false + +# Reports buffer manager activity +org.eclipse.wst.jsdt.core/debug/buffermanager=false + +# Reports builder activity : nature of build, built state reading, indictment process +org.eclipse.wst.jsdt.core/debug/builder=false + +# Reports compiler +org.eclipse.wst.jsdt.core/debug/compiler=false + +# Reports codeassist completion activity : recovered unit, inferred completions +org.eclipse.wst.jsdt.core/debug/completion=false + +# Reports classpath variable initialization, and classpath container resolution +org.eclipse.wst.jsdt.core/debug/cpresolution=false + +# Reports internals of classpath variable initialization, and classpath container resolution +org.eclipse.wst.jsdt.core/debug/cpresolution/advanced=false + +# Report type hierarchy connections, refreshes and deltas +org.eclipse.wst.jsdt.core/debug/hierarchy=false + +# Reports background indexer activity: indexing, saving index file, index queries +org.eclipse.wst.jsdt.core/debug/indexmanager=false + +# Print notified element deltas +org.eclipse.wst.jsdt.core/debug/javadelta=false +org.eclipse.wst.jsdt.core/debug/javadelta/verbose=false + +# Reports InferEngine activity +org.eclipse.wst.jsdt.core/debug/inferEngine=false + +# Reports various Java model activities +org.eclipse.wst.jsdt.core/debug/javamodel=false + +# Reports Java model elements opening/closing +org.eclipse.wst.jsdt.core/debug/javamodel/cache=false + +# Reports post actions addition/run +org.eclipse.wst.jsdt.core/debug/postaction=false + +# Reports name resolution activity +org.eclipse.wst.jsdt.core/debug/resolution=false + +# Reports search activity +org.eclipse.wst.jsdt.core/debug/search=false + +# Reports source mapper activity +org.eclipse.wst.jsdt.core/debug/sourcemapper=false + +# Reports open on selection activity : recovered unit, inferred selection +org.eclipse.wst.jsdt.core/debug/selection=false + +# Reports access to zip and jar files through the Java model +org.eclipse.wst.jsdt.core/debug/zipaccess=false + +org.eclipse.wst.jsdt.core/perf/Parser/inferTypes=10 +org.eclipse.wst.jsdt.core/perfReport/Parser/inferTypes=false \ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.core/.project b/bundles/org.eclipse.wst.jsdt.core/.project index b4d46ea6..7f3f159b 100644 --- a/bundles/org.eclipse.wst.jsdt.core/.project +++ b/bundles/org.eclipse.wst.jsdt.core/.project @@ -1,39 +1,40 @@ - - - org.eclipse.wst.jsdt.core - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder - - - - - org.eclipse.wst.jsdt.core.javascriptValidator - - - - - org.eclipse.pde.api.tools.apiAnalysisBuilder - - - - - org.eclipse.pde.PluginNature - org.eclipse.jdt.core.javanature - org.eclipse.wst.jsdt.core.jsNature - org.eclipse.pde.api.tools.apiAnalysisNature - - + + + org.eclipse.wst.jsdt.core + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + org.eclipse.wst.jsdt.core.javascriptValidator + + + + + org.eclipse.pde.api.tools.apiAnalysisBuilder + + + + + + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + org.eclipse.wst.jsdt.core.jsNature + org.eclipse.pde.api.tools.apiAnalysisNature + + diff --git a/bundles/org.eclipse.wst.jsdt.core/.settings/.api_filters b/bundles/org.eclipse.wst.jsdt.core/.settings/.api_filters new file mode 100644 index 00000000..31e74832 --- /dev/null +++ b/bundles/org.eclipse.wst.jsdt.core/.settings/.api_filters @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.core/.settings/.jsdtscope b/bundles/org.eclipse.wst.jsdt.core/.settings/.jsdtscope index ed6635a3..baf8b316 100644 --- a/bundles/org.eclipse.wst.jsdt.core/.settings/.jsdtscope +++ b/bundles/org.eclipse.wst.jsdt.core/.settings/.jsdtscope @@ -1,5 +1,4 @@ - diff --git a/bundles/org.eclipse.wst.jsdt.core/.settings/org.eclipse.jdt.core.prefs b/bundles/org.eclipse.wst.jsdt.core/.settings/org.eclipse.jdt.core.prefs index 6e072159..53cf527d 100644 --- a/bundles/org.eclipse.wst.jsdt.core/.settings/org.eclipse.jdt.core.prefs +++ b/bundles/org.eclipse.wst.jsdt.core/.settings/org.eclipse.jdt.core.prefs @@ -1,96 +1,394 @@ -#Wed Oct 24 19:49:45 EDT 2007 -eclipse.preferences.version=1 -org.eclipse.jdt.core.builder.cleanOutputFolder=clean -org.eclipse.jdt.core.builder.duplicateResourceTask=warning -org.eclipse.jdt.core.builder.invalidClasspath=ignore -org.eclipse.jdt.core.builder.resourceCopyExclusionFilter=*.launch -org.eclipse.jdt.core.circularClasspath=error -org.eclipse.jdt.core.classpath.exclusionPatterns=enabled -org.eclipse.jdt.core.classpath.multipleOutputLocations=enabled -org.eclipse.jdt.core.codeComplete.argumentPrefixes= -org.eclipse.jdt.core.codeComplete.argumentSuffixes= -org.eclipse.jdt.core.codeComplete.fieldPrefixes= -org.eclipse.jdt.core.codeComplete.fieldSuffixes= -org.eclipse.jdt.core.codeComplete.localPrefixes= -org.eclipse.jdt.core.codeComplete.localSuffixes= -org.eclipse.jdt.core.codeComplete.staticFieldPrefixes= -org.eclipse.jdt.core.codeComplete.staticFieldSuffixes= -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=disabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2 -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.4 -org.eclipse.jdt.core.compiler.debug.lineNumber=generate -org.eclipse.jdt.core.compiler.debug.localVariable=generate -org.eclipse.jdt.core.compiler.debug.sourceFile=generate -org.eclipse.jdt.core.compiler.doc.comment.support=enabled -org.eclipse.jdt.core.compiler.maxProblemPerUnit=100 -org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning -org.eclipse.jdt.core.compiler.problem.autoboxing=ignore -org.eclipse.jdt.core.compiler.problem.deprecation=ignore -org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled -org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=enabled -org.eclipse.jdt.core.compiler.problem.discouragedReference=warning -org.eclipse.jdt.core.compiler.problem.emptyStatement=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning -org.eclipse.jdt.core.compiler.problem.fallthroughCase=warning -org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled -org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore -org.eclipse.jdt.core.compiler.problem.finalParameterBound=ignore -org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=error -org.eclipse.jdt.core.compiler.problem.forbiddenReference=error -org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning -org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning -org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore -org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=error -org.eclipse.jdt.core.compiler.problem.invalidJavadoc=ignore -org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsDeprecatedRef=enabled -org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsNotVisibleRef=enabled -org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsVisibility=private -org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore -org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=error -org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingJavadocComments=ignore -org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsOverriding=enabled -org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsVisibility=public -org.eclipse.jdt.core.compiler.problem.missingJavadocTags=ignore -org.eclipse.jdt.core.compiler.problem.missingJavadocTagsOverriding=enabled -org.eclipse.jdt.core.compiler.problem.missingJavadocTagsVisibility=private -org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingSerialVersion=error -org.eclipse.jdt.core.compiler.problem.noEffectAssignment=error -org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning -org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore -org.eclipse.jdt.core.compiler.problem.nullReference=ignore -org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning -org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore -org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=error -org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore -org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning -org.eclipse.jdt.core.compiler.problem.redundantNullCheck=warning -org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=enabled -org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=error -org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled -org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore -org.eclipse.jdt.core.compiler.problem.typeParameterHiding=ignore -org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning -org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore -org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning -org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore -org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning -org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled -org.eclipse.jdt.core.compiler.problem.unusedImport=error -org.eclipse.jdt.core.compiler.problem.unusedLabel=error -org.eclipse.jdt.core.compiler.problem.unusedLocal=warning -org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore -org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled -org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning -org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.source=1.3 -org.eclipse.jdt.core.incompatibleJDKLevel=ignore -org.eclipse.jdt.core.incompleteClasspath=error +#Tue Jul 17 18:19:32 EDT 2012 +org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert +org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line +org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_try_resources=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert +org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert +org.eclipse.jdt.core.compiler.problem.localVariableHiding=warning +org.eclipse.jdt.core.formatter.alignment_for_assignment=0 +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert +org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=error +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert +org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_try_resources=insert +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2 +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=false +org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false +org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert +org.eclipse.jdt.core.compiler.problem.emptyStatement=error +org.eclipse.jdt.core.compiler.problem.missingJavadocTagsVisibility=private +org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore +org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=insert +org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=error +org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert +org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore +org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert +org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=warning +org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert +org.eclipse.jdt.core.formatter.blank_lines_after_imports=1 +org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsVisibility=public +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation=0 +org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=error +org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning +org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore +org.eclipse.jdt.core.formatter.comment.format_source_code=true +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true +org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1 +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_try=insert +org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert +org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false +org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert +org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column=true +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert +org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1 +org.eclipse.jdt.core.classpath.exclusionPatterns=enabled +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16 +org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=3 +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert +org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.formatter.comment.format_header=false +org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert +org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=64 +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert +org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning +org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16 +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.comment.line_length=78 +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert +org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsNotVisibleRef=enabled +org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled +org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert +org.eclipse.jdt.core.classpath.multipleOutputLocations=enabled +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=insert +org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert +org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert +org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning +org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.builder.cleanOutputFolder=clean +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled +org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert +org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert +org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=true +org.eclipse.jdt.core.formatter.continuation_indentation=3 +org.eclipse.jdt.core.codeComplete.fieldSuffixes= +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field=insert +org.eclipse.jdt.core.compiler.problem.invalidJavadoc=ignore +org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert +org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=16 +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert +org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=enabled +org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert +org.eclipse.jdt.core.formatter.blank_lines_before_method=1 +org.eclipse.jdt.core.compiler.problem.missingJavadocTagsOverriding=enabled +org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=false +org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16 +org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1 +org.eclipse.jdt.core.builder.resourceCopyExclusionFilter=*.launch +org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert +org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line +org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.incompleteClasspath=error +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert +org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 +org.eclipse.jdt.core.formatter.join_lines_in_comments=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true +org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsOverriding=enabled +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=warning +org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0 +org.eclipse.jdt.core.formatter.comment.format_block_comments=true +org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert +org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16 +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=insert +org.eclipse.jdt.core.formatter.alignment_for_union_type_in_multicatch=16 +org.eclipse.jdt.core.formatter.comment.format_html=true +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16 +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert +org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore +org.eclipse.jdt.core.compiler.problem.autoboxing=ignore +org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning +org.eclipse.jdt.core.compiler.problem.fallthroughCase=warning +org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled +org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled +org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsDeprecatedRef=enabled +org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert +org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=error +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert +org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore +org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 +org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=insert +org.eclipse.jdt.core.compiler.problem.redundantNullCheck=warning +org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=error +org.eclipse.jdt.core.compiler.problem.forbiddenReference=error +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert +org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries=true +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_member=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert +org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true +org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=insert +org.eclipse.jdt.core.codeComplete.staticFinalFieldSuffixes= +org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16 +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert +org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=insert +org.eclipse.jdt.core.circularClasspath=error +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_try=do not insert +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 +org.eclipse.jdt.core.codeComplete.fieldPrefixes= +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert +org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line +org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch=true +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert +org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=warning +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert +org.eclipse.jdt.core.codeComplete.staticFieldSuffixes= +org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0 +org.eclipse.jdt.core.formatter.alignment_for_method_declaration=0 +org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning +org.eclipse.jdt.core.formatter.tabulation.char=tab +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert +org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled +org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true +org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled +org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert +org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false +org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false +org.eclipse.jdt.core.formatter.compact_else_if=true +org.eclipse.jdt.core.codeComplete.localPrefixes= +org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert +org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert +org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false +org.eclipse.jdt.core.compiler.problem.missingSerialVersion=error +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled +org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning +org.eclipse.jdt.core.formatter.disabling_tag=@formatter\:off +org.eclipse.jdt.core.formatter.align_type_members_on_columns=false +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=insert +org.eclipse.jdt.core.compiler.problem.finalParameterBound=ignore +org.eclipse.jdt.core.codeComplete.localSuffixes= +org.eclipse.jdt.core.formatter.join_wrapped_lines=true +org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true +org.eclipse.jdt.core.formatter.use_on_off_tags=false +org.eclipse.jdt.core.compiler.problem.discouragedReference=warning +org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16 +org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert +org.eclipse.jdt.core.formatter.comment.format_line_comments=true +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert +org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert +org.eclipse.jdt.core.formatter.comment.indent_parameter_description=true +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.indentation.size=4 +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert +org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16 +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.comment.indent_root_tags=true +org.eclipse.jdt.core.compiler.problem.deprecation=ignore +org.eclipse.jdt.core.compiler.problem.potentialNullReference=warning +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert +org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsVisibility=private +org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore +org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16 +org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled +org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert +org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false +org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true +org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert +org.eclipse.jdt.core.formatter.blank_lines_before_package=0 +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert +org.eclipse.jdt.core.formatter.indent_empty_lines=false +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16 +org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested=true +org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=warning +org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore +org.eclipse.jdt.core.compiler.problem.deadCode=warning +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter=do not insert +org.eclipse.jdt.core.codeComplete.staticFinalFieldPrefixes= +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert +org.eclipse.jdt.core.compiler.problem.noEffectAssignment=error +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert +org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore +org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line +org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 +org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=48 +org.eclipse.jdt.core.codeComplete.argumentPrefixes= +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert +org.eclipse.jdt.core.compiler.problem.unusedImport=error +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert +org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=true +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert +org.eclipse.jdt.core.compiler.problem.unusedLabel=error +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=insert +org.eclipse.jdt.core.builder.invalidClasspath=ignore +org.eclipse.jdt.core.codeComplete.argumentSuffixes= +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert +org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore +org.eclipse.jdt.core.incompatibleJDKLevel=ignore +org.eclipse.jdt.core.formatter.alignment_for_resources_in_try=80 +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.compiler.problem.nullReference=error +org.eclipse.jdt.core.codeComplete.staticFieldPrefixes= +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.problem.missingJavadocComments=ignore +org.eclipse.jdt.core.formatter.blank_lines_before_imports=1 +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.alignment_for_compact_if=32 +org.eclipse.jdt.core.compiler.problem.typeParameterHiding=ignore +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=disabled +org.eclipse.jdt.core.formatter.insert_new_line_after_label=do not insert +org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=insert +org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments=false +org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_try=do not insert +org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled +org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=3 +org.eclipse.jdt.core.formatter.lineSplit=999 +org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=enabled +org.eclipse.jdt.core.compiler.maxProblemPerUnit=100 +org.eclipse.jdt.core.compiler.source=1.3 +org.eclipse.jdt.core.formatter.tabulation.size=4 +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert +org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning +org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line +org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert +org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1 +org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries=true +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert +org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning +org.eclipse.jdt.core.builder.duplicateResourceTask=warning +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert +org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=warning +org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=insert +org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert +org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning +org.eclipse.jdt.core.compiler.problem.unusedLocal=warning +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.compiler.doc.comment.support=enabled +org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert +org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.problem.missingJavadocTags=ignore +org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.enabling_tag=@formatter\:on +org.eclipse.jdt.core.compiler.compliance=1.4 +org.eclipse.jdt.core.formatter.blank_lines_after_package=1 +org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=64 +org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert +org.eclipse.jdt.core.formatter.blank_lines_before_field=0 diff --git a/bundles/org.eclipse.wst.jsdt.core/.settings/org.eclipse.jdt.ui.prefs b/bundles/org.eclipse.wst.jsdt.core/.settings/org.eclipse.jdt.ui.prefs index c91d09d8..150dbff6 100644 --- a/bundles/org.eclipse.wst.jsdt.core/.settings/org.eclipse.jdt.ui.prefs +++ b/bundles/org.eclipse.wst.jsdt.core/.settings/org.eclipse.jdt.ui.prefs @@ -1,51 +1,54 @@ -#Wed Oct 24 19:41:31 EDT 2007 -cleanup.add_default_serial_version_id=true -cleanup.add_generated_serial_version_id=false -cleanup.add_missing_annotations=false -cleanup.add_missing_deprecated_annotations=true -cleanup.add_missing_nls_tags=false -cleanup.add_missing_override_annotations=true -cleanup.add_serial_version_id=true -cleanup.always_use_blocks=true -cleanup.always_use_parentheses_in_expressions=true -cleanup.always_use_this_for_non_static_field_access=false -cleanup.always_use_this_for_non_static_method_access=false -cleanup.convert_to_enhanced_for_loop=false -cleanup.format_source_code=false -cleanup.make_local_variable_final=true -cleanup.make_parameters_final=false -cleanup.make_private_fields_final=true -cleanup.make_variable_declarations_final=false -cleanup.never_use_blocks=false -cleanup.never_use_parentheses_in_expressions=false -cleanup.organize_imports=true -cleanup.qualify_static_field_accesses_with_declaring_class=false -cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true -cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true -cleanup.qualify_static_member_accesses_with_declaring_class=true -cleanup.qualify_static_method_accesses_with_declaring_class=false -cleanup.remove_private_constructors=true -cleanup.remove_unnecessary_casts=true -cleanup.remove_unnecessary_nls_tags=true -cleanup.remove_unused_imports=true -cleanup.remove_unused_local_variables=false -cleanup.remove_unused_private_fields=true -cleanup.remove_unused_private_members=true -cleanup.remove_unused_private_methods=true -cleanup.remove_unused_private_types=true -cleanup.use_blocks=true -cleanup.use_blocks_only_for_return_and_throw=false -cleanup.use_parentheses_in_expressions=true -cleanup.use_this_for_non_static_field_access=false -cleanup.use_this_for_non_static_field_access_only_if_necessary=true -cleanup.use_this_for_non_static_method_access=false -cleanup.use_this_for_non_static_method_access_only_if_necessary=true -cleanup_profile=_SSE Team Styles -cleanup_settings_version=2 -eclipse.preferences.version=1 -internal.default.compliance=default -org.eclipse.jdt.ui.exception.name=e -org.eclipse.jdt.ui.gettersetter.use.is=true -org.eclipse.jdt.ui.keywordthis=false -org.eclipse.jdt.ui.overrideannotation=false -org.eclipse.jdt.ui.text.custom_code_templates= +#Tue Jul 17 18:19:32 EDT 2012 +cleanup.format_source_code=false +cleanup_profile=_SSE Team Styles +org.eclipse.jdt.ui.text.custom_code_templates= +cleanup.add_missing_annotations=false +cleanup.use_this_for_non_static_method_access_only_if_necessary=true +cleanup.remove_unused_private_types=true +cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true +cleanup.qualify_static_method_accesses_with_declaring_class=false +cleanup.add_generated_serial_version_id=false +cleanup.make_variable_declarations_final=false +cleanup.always_use_this_for_non_static_field_access=false +org.eclipse.jdt.ui.overrideannotation=false +internal.default.compliance=default +org.eclipse.jdt.ui.keywordthis=false +cleanup.never_use_parentheses_in_expressions=false +cleanup.add_serial_version_id=true +cleanup_settings_version=2 +cleanup.remove_unused_private_methods=true +cleanup.use_this_for_non_static_field_access=false +cleanup.use_blocks_only_for_return_and_throw=false +cleanup.remove_unused_private_members=true +org.eclipse.jdt.ui.exception.name=e +cleanup.always_use_this_for_non_static_method_access=false +cleanup.remove_unnecessary_nls_tags=true +cleanup.qualify_static_field_accesses_with_declaring_class=false +formatter_profile=_SSE Formatting +cleanup.add_missing_nls_tags=false +cleanup.use_this_for_non_static_field_access_only_if_necessary=true +cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true +org.eclipse.jdt.ui.gettersetter.use.is=true +cleanup.remove_unnecessary_casts=true +cleanup.qualify_static_member_accesses_with_declaring_class=true +cleanup.use_parentheses_in_expressions=true +cleanup.remove_unused_private_fields=true +cleanup.make_parameters_final=false +eclipse.preferences.version=1 +cleanup.remove_unused_imports=true +cleanup.organize_imports=true +cleanup.convert_to_enhanced_for_loop=false +cleanup.remove_private_constructors=true +cleanup.always_use_blocks=true +cleanup.never_use_blocks=false +cleanup.always_use_parentheses_in_expressions=true +formatter_settings_version=11 +cleanup.use_this_for_non_static_method_access=false +cleanup.remove_unused_local_variables=false +cleanup.make_private_fields_final=true +org.eclipse.jdt.ui.javadoc=true +cleanup.add_missing_deprecated_annotations=true +cleanup.add_default_serial_version_id=true +cleanup.use_blocks=true +cleanup.add_missing_override_annotations=true +cleanup.make_local_variable_final=true diff --git a/bundles/org.eclipse.wst.jsdt.core/META-INF/MANIFEST.MF b/bundles/org.eclipse.wst.jsdt.core/META-INF/MANIFEST.MF index 6aa16997..133bdcca 100644 --- a/bundles/org.eclipse.wst.jsdt.core/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.wst.jsdt.core/META-INF/MANIFEST.MF @@ -1,6 +1,6 @@ Manifest-Version: 1.0 Bundle-SymbolicName: org.eclipse.wst.jsdt.core; singleton:=true -Bundle-Version: 1.1.202.qualifier +Bundle-Version: 1.3.0.qualifier Bundle-ManifestVersion: 2 Bundle-Name: %pluginName Bundle-Vendor: %providerName @@ -15,38 +15,38 @@ Export-Package: org.eclipse.wst.jsdt.core, org.eclipse.wst.jsdt.core.infer, org.eclipse.wst.jsdt.core.search, org.eclipse.wst.jsdt.core.util, - org.eclipse.wst.jsdt.internal.codeassist;x-friends:="org.eclipse.wst.jsdt.ui", - org.eclipse.wst.jsdt.internal.codeassist.complete;x-friends:="org.eclipse.wst.jsdt.ui", - org.eclipse.wst.jsdt.internal.codeassist.impl;x-friends:="org.eclipse.wst.jsdt.ui", - org.eclipse.wst.jsdt.internal.codeassist.select;x-friends:="org.eclipse.wst.jsdt.ui", - org.eclipse.wst.jsdt.internal.compiler;x-internal:=true, - org.eclipse.wst.jsdt.internal.compiler.ast;x-internal:=true, - org.eclipse.wst.jsdt.internal.compiler.batch;x-internal:=true, - org.eclipse.wst.jsdt.internal.compiler.classfmt;x-internal:=true, - org.eclipse.wst.jsdt.internal.compiler.env;x-internal:=true, - org.eclipse.wst.jsdt.internal.compiler.flow;x-internal:=true, - org.eclipse.wst.jsdt.internal.compiler.impl;x-internal:=true, - org.eclipse.wst.jsdt.internal.compiler.lookup;x-internal:=true, - org.eclipse.wst.jsdt.internal.compiler.parser;x-internal:=true, - org.eclipse.wst.jsdt.internal.compiler.parser.diagnose;x-internal:=true, - org.eclipse.wst.jsdt.internal.compiler.problem;x-internal:=true, - org.eclipse.wst.jsdt.internal.compiler.util;x-friends:="org.eclipse.wst.jsdt.ui,org.eclipse.wst.jsdt.web.core", - org.eclipse.wst.jsdt.internal.core;x-friends:="org.eclipse.wst.jsdt.ui,org.eclipse.wst.jsdt.web.core", + org.eclipse.wst.jsdt.internal.codeassist;x-internal:=true, + org.eclipse.wst.jsdt.internal.codeassist.complete;x-internal:=true, + org.eclipse.wst.jsdt.internal.codeassist.impl;x-internal:=true, + org.eclipse.wst.jsdt.internal.codeassist.select;x-internal:=true, + org.eclipse.wst.jsdt.internal.compiler;x-friends:="org.eclipse.jdt.compiler.tool", + org.eclipse.wst.jsdt.internal.compiler.ast;x-friends:="org.eclipse.wst.jsdt.compiler.tool", + org.eclipse.wst.jsdt.internal.compiler.batch;x-friends:="org.eclipse.wst.jsdt.compiler.tool", + org.eclipse.wst.jsdt.internal.compiler.classfmt;x-friends:="org.eclipse.wst.jsdt.compiler.tool", + org.eclipse.wst.jsdt.internal.compiler.env;x-friends:="org.eclipse.wst.jsdt.compiler.tool", + org.eclipse.wst.jsdt.internal.compiler.flow;x-friends:="org.eclipse.wst.jsdt.compiler.tool", + org.eclipse.wst.jsdt.internal.compiler.impl;x-friends:="org.eclipse.wst.jsdt.compiler.tool", + org.eclipse.wst.jsdt.internal.compiler.lookup;x-friends:="org.eclipse.wst.jsdt.compiler.tool", + org.eclipse.wst.jsdt.internal.compiler.parser;x-friends:="org.eclipse.wst.jsdt.compiler.tool", + org.eclipse.wst.jsdt.internal.compiler.parser.diagnose;x-friends:="org.eclipse.wst.jsdt.compiler.tool", + org.eclipse.wst.jsdt.internal.compiler.problem;x-friends:="org.eclipse.wst.jsdt.compiler.tool", + org.eclipse.wst.jsdt.internal.compiler.util;x-friends:="org.eclipse.wst.jsdt.compiler.tool", + org.eclipse.wst.jsdt.internal.core;x-friends:="org.eclipse.wst.jsdt.ui", org.eclipse.wst.jsdt.internal.core.builder;x-internal:=true, org.eclipse.wst.jsdt.internal.core.dom.rewrite;x-internal:=true, org.eclipse.wst.jsdt.internal.core.hierarchy;x-internal:=true, - org.eclipse.wst.jsdt.internal.core.index;x-friends:="org.eclipse.wst.jsdt.ui,org.eclipse.wst.jsdt.web.core", - org.eclipse.wst.jsdt.internal.core.interpret;x-internal:=true, + org.eclipse.wst.jsdt.internal.core.index, + org.eclipse.wst.jsdt.internal.core.interpret, org.eclipse.wst.jsdt.internal.core.interpret.builtin;x-internal:=true, - org.eclipse.wst.jsdt.internal.core.search;x-friends:="org.eclipse.wst.jsdt.ui,org.eclipse.wst.jsdt.web.core", - org.eclipse.wst.jsdt.internal.core.search.indexing;x-friends:="org.eclipse.wst.jsdt.ui,org.eclipse.wst.jsdt.web.core", + org.eclipse.wst.jsdt.internal.core.search;x-internal:=true, + org.eclipse.wst.jsdt.internal.core.search.indexing;x-internal:=true, org.eclipse.wst.jsdt.internal.core.search.matching;x-internal:=true, - org.eclipse.wst.jsdt.internal.core.search.processing;x-friends:="org.eclipse.wst.jsdt.ui,org.eclipse.wst.jsdt.web.core", - org.eclipse.wst.jsdt.internal.core.util;x-friends:="org.eclipse.wst.jsdt.ui,org.eclipse.wst.jsdt.web.core", - org.eclipse.wst.jsdt.internal.formatter;x-friends:="org.eclipse.wst.jsdt.ui", - org.eclipse.wst.jsdt.internal.formatter.align;x-friends:="org.eclipse.wst.jsdt.ui", - org.eclipse.wst.jsdt.internal.formatter.comment;x-friends:="org.eclipse.wst.jsdt.ui", - org.eclipse.wst.jsdt.internal.oaametadata;x-friends:="org.eclipse.wst.jsdt.ui", + org.eclipse.wst.jsdt.internal.core.search.processing;x-internal:=true, + org.eclipse.wst.jsdt.internal.core.util;x-friends:="org.eclipse.wst.jsdt.ui", + org.eclipse.wst.jsdt.internal.formatter;x-internal:=true, + org.eclipse.wst.jsdt.internal.formatter.align;x-internal:=true, + org.eclipse.wst.jsdt.internal.formatter.comment;x-internal:=true, + org.eclipse.wst.jsdt.internal.oaametadata, org.eclipse.wst.jsdt.launching, org.eclipse.wst.jsdt.libraries Import-Package: com.ibm.icu.text; version="3.8" diff --git a/bundles/org.eclipse.wst.jsdt.core/build.properties b/bundles/org.eclipse.wst.jsdt.core/build.properties index 6df812ef..0e4a8f8e 100644 --- a/bundles/org.eclipse.wst.jsdt.core/build.properties +++ b/bundles/org.eclipse.wst.jsdt.core/build.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2005, 2007 IBM Corporation and others. +# Copyright (c) 2005, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/libraries/baseBrowserLibrary--WrapperObjects.js b/bundles/org.eclipse.wst.jsdt.core/libraries/baseBrowserLibrary--WrapperObjects.js index 8d8eb4fc..f9bb9a69 100644 --- a/bundles/org.eclipse.wst.jsdt.core/libraries/baseBrowserLibrary--WrapperObjects.js +++ b/bundles/org.eclipse.wst.jsdt.core/libraries/baseBrowserLibrary--WrapperObjects.js @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. + * Copyright (c) 2008, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -1545,7 +1545,7 @@ Element.prototype.hasAttributeNS=function(namespaceURI, localName){}; * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html */ function Text(){}; -Text.prototype = new CharacterData(){}; +Text.prototype = new CharacterData(); /** * function splitText(offset) * @type Method @@ -1576,7 +1576,7 @@ Text.prototype.splitText=function(offset){}; * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html */ function Comment(){}; -Comment.prototype = new CharacterData(){}; +Comment.prototype = new CharacterData(); /** * Object CDATASection() * Comment inherits all of the methods and properties from Text. diff --git a/bundles/org.eclipse.wst.jsdt.core/libraries/baseBrowserLibrary.js b/bundles/org.eclipse.wst.jsdt.core/libraries/baseBrowserLibrary.js index aad16dc3..2fc99ea6 100644 --- a/bundles/org.eclipse.wst.jsdt.core/libraries/baseBrowserLibrary.js +++ b/bundles/org.eclipse.wst.jsdt.core/libraries/baseBrowserLibrary.js @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. + * Copyright (c) 2008, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -496,10 +496,10 @@ Document.prototype.getElementById=function(elementId){return new HTMLElement();} * @memberOf Node * @since Standard ECMA-262 3rd. Edition * @since Level 2 Document Object Model Core Definition. - * @see Object + * @see EventTarget */ function Node(){}; -Node.prototype=new Object(); +Node.prototype=new EventTarget(); /** * Constant Node.ELEMENT_NODE=1 * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html diff --git a/bundles/org.eclipse.wst.jsdt.core/libraries/browserWindow.js b/bundles/org.eclipse.wst.jsdt.core/libraries/browserWindow.js index 4342f176..cfbf452b 100644 --- a/bundles/org.eclipse.wst.jsdt.core/libraries/browserWindow.js +++ b/bundles/org.eclipse.wst.jsdt.core/libraries/browserWindow.js @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. + * Copyright (c) 2008, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -18,7 +18,7 @@ BarProp.prototype = new Array(); * @since Common Usage, no standard */ function Window(){}; -Window.prototype = new Global(); +Window.prototype = new EventTarget(); Window.prototype.self = new Window(); Window.prototype.window = new Window(); Window.prototype.frames = new Array(); @@ -176,162 +176,161 @@ Window.prototype.scrollMaxX=0; Window.prototype.scrollMaxY=0; Window.prototype.fullScreen=""; Window.prototype.frameElement=""; -Window.prototype.sessionStorage=""; /* End properites */ /** * function alert() - * @param {String} arg - * @memberOf Window + * @param {String} message + * @memberOf Window */ -Window.prototype.alert = function(arg){}; +Window.prototype.alert = function(message){}; /** * function blur() - * @memberOf Window + * @memberOf Window */ Window.prototype.blur = function(){}; /** - * function clearInterval(arg) - * @param arg - * @memberOf Window + * function clearInterval(intervalID) + * @param intervalID + * @memberOf Window */ -Window.prototype.clearInterval = function(arg){}; +Window.prototype.clearInterval = function(intervalID){}; /** - * function clearTimeout(arg) - * @param arg - * @memberOf Window + * function clearTimeout(intervalID) + * @param intervalID + * @memberOf Window */ -Window.prototype.clearTimeout = function(arg){}; +Window.prototype.clearTimeout = function(intervalID){}; /** * function close() - * @memberOf Window + * @memberOf Window */ Window.prototype.close = function(){}; /** * function confirm() * @param {String} arg - * @memberOf Window + * @memberOf Window * @returns {Boolean} */ Window.prototype.confirm = function(arg){return false;}; /** * function focus() - * @memberOf Window + * @memberOf Window */ Window.prototype.focus = function(){}; /** - * function getComputedStyle(arg1, arg2) - * @param {Element} arg1 - * @param {String} arg2 - * @memberOf Window + * function getComputedStyle(element, pseudoElt ) + * @param {Element} element + * @param {String} pseudoElt + * @memberOf Window * @returns {Object} */ -Window.prototype.getComputedStyle = function(arg1,arg2){return new Object();}; +Window.prototype.getComputedStyle = function(element,pseudoElt ){return new Object();}; /** - * function moveTo(arg1, arg2) - * @param {Number} arg1 - * @param {Number} arg2 - * @memberOf Window + * function moveTo(x, y) + * @param {Number} x + * @param {Number} y + * @memberOf Window */ -Window.prototype.moveTo = function(arg1,arg2){}; +Window.prototype.moveTo = function(x,y){}; /** - * function moveBy(arg1, arg2) - * @param {Number} arg1 - * @param {Number} arg2 - * @memberOf Window + * function moveBy(deltaX, deltaY) + * @param {Number} deltaX + * @param {Number} deltaY + * @memberOf Window */ -Window.prototype.moveBy = function(arg1,arg2){}; +Window.prototype.moveBy = function(deltaX,deltaY){}; /** * function open(optionalArg1, optionalArg2, optionalArg3, optionalArg4) - * @param {String} optionalArg1 - * @param {String} optionalArg2 - * @param {String} optionalArg3 + * @param {String} url + * @param {String} windowName + * @param {String} windowFeatures * @param {Boolean} optionalArg4 - * @memberOf Window + * @memberOf Window * @returns {Window} */ -Window.prototype.open = function(optionalArg1, optionalArg2, optionalArg3, optionalArg4){return new Window();}; +Window.prototype.open = function(url, windowName, windowFeatures, optionalArg4){return new Window();}; /** * function print() - * @memberOf Window + * @memberOf Window */ Window.prototype.print = function(){}; /** - * function prompt(arg1, arg2) - * @param {String} arg1 - * @param {String} arg2 - * @memberOf Window + * function prompt(text, value) + * @param {String} text + * @param {String} value + * @memberOf Window * @returns {String} */ -Window.prototype.prompt = function(){return "";}; +Window.prototype.prompt = function(text, value){return "";}; /** - * function resizeTo(arg1, arg2) - * @param {Number} arg1 - * @param {Number} arg2 - * @memberOf Window + * function resizeTo(newOuterWidth,newOuterHeight) + * @param {Number} newOuterWidth + * @param {Number} newOuterHeighr + * @memberOf Window */ -Window.prototype.resizeTo=function(arg1,arg2){}; +Window.prototype.resizeTo=function(newOuterWidth,newOuterHeight){}; /** - * function resizeBy(arg1, arg2) - * @param {Number} arg1 - * @param {Number} arg2 - * @memberOf Window + * function resizeBy(deltaX, deltaY) + * @param {Number} deltaX + * @param {Number} deltaY + * @memberOf Window */ -Window.prototype.resizeBy=function(arg1,arg2){}; +Window.prototype.resizeBy=function(deltaX,deltaY){}; /** - * function scrollTo(arg1, arg2) - * @param {Number} arg1 - * @param {Number} arg2 - * @memberOf Window + * function scrollTo(x,y) + * @param {Number} x + * @param {Number} y + * @memberOf Window */ -Window.prototype.scrollTo=function(arg1,arg2){}; +Window.prototype.scrollTo=function(x,y){}; /** - * function scrollBy(arg1, arg2) - * @param {Number} arg1 - * @param {Number} arg2 - * @memberOf Window + * function scrollBy(pixelX,pixelY) + * @param {Number} pixelX + * @param {Number} pixelY + * @memberOf Window */ -Window.prototype.scrollBy=function(arg1,arg2){}; +Window.prototype.scrollBy=function(pixelX,pixelY){}; /** * function setInterval(arg1, arg2) - * @param {Object} arg1 - * @param {Number} arg2 - * @memberOf Window + * @param {Function} callback + * @param {Number} delay + * @memberOf Window * @returns {Number} */ -Window.prototype.setInterval=function(arg1, arg2){return 0;}; +Window.prototype.setInterval=function(callback, delay){return 0;}; /** - * function setTimeout(arg1, arg2) - * @param {Object} arg1 - * @param {Number} arg2 - * @memberOf Window + * function setTimeout(callback, delay) + * @param {Function} callback + * @param {Number} delay + * @memberOf Window * @returns {Number} */ -Window.prototype.setTimeout=function(arg1, arg2){ return 0;}; +Window.prototype.setTimeout=function(callback, delay){ return 0;}; /** - * function atob(arg) - * @param {String} arg - * @memberOf Window + * function atob(encodedData) + * @param {String} encodedData + * @memberOf Window * @returns {String} */ -Window.prototype.atob=function(arg){return "";}; +Window.prototype.atob=function(encodedData){return "";}; /** * function btoa(arg) - * @param {String} arg - * @memberOf Window + * @param {String} stringToEncode + * @memberOf Window * @returns {String} */ -Window.prototype.btoa=function(arg){return "";}; +Window.prototype.btoa=function(stringToEncode){return "";}; /** - * function setResizable(arg) - * @param {Boolean} arg - * @memberOf Window + * function setResizable(resizable) + * @param {Boolean} resizable + * @memberOf Window */ -Window.prototype.setResizable=function(arg){}; +Window.prototype.setResizable=function(resizable){}; -Window.prototype.captureEvents=function(arg1){}; -Window.prototype.releaseEvents=function(arg1){}; -Window.prototype.routeEvent=function(arg1){}; +Window.prototype.captureEvents=function(eventType){}; +Window.prototype.releaseEvents=function(eventType){}; +Window.prototype.routeEvent=function(eventType){}; Window.prototype.enableExternalCapture=function(){}; Window.prototype.disableExternalCapture=function(){}; Window.prototype.find=function(){}; @@ -339,13 +338,11 @@ Window.prototype.back=function(){}; Window.prototype.forward=function(){}; Window.prototype.home=function(){}; Window.prototype.stop=function(){}; -Window.prototype.scroll=function(arg1,arg2){}; - -/* - * These functions may need to be moved into a browser specific library. +/** + * @param {Number} pixelX + * @param {Number} pixelY */ -Window.prototype.dispatchEvent=function(arg1){}; -Window.prototype.removeEventListener=function(arg1,arg2,arg3){}; +Window.prototype.scroll=function(pixelX,pixelY){}; /* End functions */ /** @@ -558,4 +555,64 @@ Navigator.prototype.height = 0; * @type Number * @memberOf Screen */ -Navigator.prototype.width = 0; \ No newline at end of file +Navigator.prototype.width = 0; + +Event.prototype=new Object(); +// PhaseType +Event.prototype.CAPTURING_PHASE = 1; +Event.prototype.AT_TARGET = 2; +Event.prototype.BUBBLING_PHASE = 3; + +Event.prototype.type=""; +Event.prototype.target=new EventTarget(); +Event.prototype.currentTarget=new EventTarget(); +Event.prototype.eventPhase=0; +Event.prototype.bubbles=false; +Event.prototype.cancelable=false; +Event.prototype.timeStamp=0; +Event.prototype.stopPropagation=function(){}; +Event.prototype.preventDefault=function(){}; +/** + * @param {String} eventTypeArg + * @param {Boolean} canBubbleArg + * @param {Boolean} cancelableArg + */ +Event.prototype.initEvent=function(eventTypeArg, + canBubbleArg, + cancelableArg){}; +function EventListener(){}; +EventListener.prototype=new Object(); +/** + * @param {Event} event + * @memberOf EventListener + */ +EventListener.prototype.handleEvent=function(event){}; + +function EventTarget(){}; +EventTarget.prototype=new Object(); +/* + * These functions may need to be moved into a browser specific library. + */ +/** + * @memberOf Window + * @param event {Event} + * @throws {EventException} + */ +EventTarget.prototype.dispatchEvent=function(event){}; + +// https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener +/** + * @memberOf Window + * @param {String} type + * @param {EventListener} listener + * @param {Boolean} useCapture + */ +EventTarget.prototype.addEventListener=function(type, listener, useCapture){}; +// https://developer.mozilla.org/en-US/docs/DOM/element.removeEventListener +/** + * @memberOf Window + * @param {String} type + * @param {EventListener} listener + * @param {Boolean} useCapture + */ +EventTarget.prototype.removeEventListener=function(type, listener, useCapture){}; diff --git a/bundles/org.eclipse.wst.jsdt.core/libraries/dom5.js b/bundles/org.eclipse.wst.jsdt.core/libraries/dom5.js index aad16dc3..a75f1756 100644 --- a/bundles/org.eclipse.wst.jsdt.core/libraries/dom5.js +++ b/bundles/org.eclipse.wst.jsdt.core/libraries/dom5.js @@ -1,5393 +1,922 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -/** - * Object DOMException() - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @augments Object - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Object - */ -function DOMException(){}; -DOMException.prototype = new Object(); -/** - * Constant DOMException.INDEX_SIZE_ERR=1 - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @constant - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -DOMException.INDEX_SIZE_ERR=1; -/** - * Constant DOMException.DOMSTRING_SIZE_ERR=2 - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @constant - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -DOMException.DOMSTRING_SIZE_ERR=2; -/** - * Constant DOMException.HIERARCHY_REQUEST_ERR=3 - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @constant - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -DOMException.HIERARCHY_REQUEST_ERR=3; -/** - * Constant DOMException.WRONG_DOCUMENT_ERR=4 - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @constant - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -DOMException.WRONG_DOCUMENT_ERR=4; -/** - * Constant DOMException.INVALID_CHARACTER_ERR=5 - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @constant - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -DOMException.INVALID_CHARACTER_ERR=5; -/** - * Constant DOMException.NO_DATA_ALLOWED_ER=6 - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @constant - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -DOMException.NO_DATA_ALLOWED_ER=6; -/** - * Constant DOMException.NO_MODIFICATION_ALLOWED_ERR=7 - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @constant - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -DOMException.NO_MODIFICATION_ALLOWED_ERR=7; -/** - * Constant DOMException.NOT_FOUND_ERR=8 - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @constant - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -DOMException.NOT_FOUND_ERR=8; -/** - * Constant DOMException.NOT_SUPPORTED_ERR=9 - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @constant - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -DOMException.NOT_SUPPORTED_ERR=9; -/** - * Constant DOMException.INUSE_ATTRIBUTE_ERR=10 - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @constant - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -DOMException.INUSE_ATTRIBUTE_ERR=10; -/** - * Constant DOMException.INVALID_STATE_ERR=11 - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @constant - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -DOMException.INVALID_STATE_ERR=11; -/** - * Constant DOMException.SYNTAX_ERR=12 - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @constant - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -DOMException.SYNTAX_ERR=12; -/** - * Constant DOMException.INVALID_MODIFICATION_ER=13 - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @constant - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -DOMException.INVALID_MODIFICATION_ER=13; -/** - * Constant DOMException.NAMESPACE_ERR=14 - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @constant - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -DOMException.NAMESPACE_ERR=14; -/** - * Constant DOMException.NVALID_ACCESS_ERR=15 - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @constant - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -DOMException.INVALID_ACCESS_ERR=15; -/** - * Property code - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -DOMException.prototype.code=0; - -/** - * Object DOMImplementation() - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @augments Object - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Object - */ -function DOMImplementation(){}; -DOMImplementation.prototype = new Object(); -/** - * function hasFeature(feature, version) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {String} feature - * @param {String} version - * @returns {Boolean} - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -DOMImplementation.prototype.hasFeature = function(feature, version){return false;}; -/** - * function createDocumentType(qualifiedName, publicId, systemId) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {String} qualifiedName - * @param {String} publicId - * @param {String} systemId - * @returns {DocumentType} - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see DocumentType - */ -DOMImplementation.prototype.createDocumentType = function(qualifiedName, publicId, systemId){return new DocumentType();}; -/** - * function createDocument(namespaceURI, qualifiedName, doctype) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {String} namespaceURI - * @param {String} qualifiedName - * @param {DocumentType} doctype - * @returns {Document} - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Document - */ -DOMImplementation.prototype.createDocument = function(namespaceURI, qualifiedName, doctype){return new HTMLDocument();}; - -/** - * Object DocumentFragment() - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @augments Node - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Node - */ -function DocumentFragment(){}; -DocumentFragment.prototype=new Node(); - -/** - * Object Document() - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @augments Node - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Node - */ -function Document(){}; -Document.prototype = new Node(); -/** - * Property defaultView - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type Window - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Window - */ -Document.prototype.defaultView = new Window(); -/** - * Property doctype - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type DocumentType - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see DocumentType - */ -Document.prototype.doctype = new DocumentType(); -/** - * Property implementation - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type DOMImplementation - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see DOMImplementation - */ -Document.prototype.implementation = new DOMImplementation(); -/** - * Property documentElement - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type Element - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Element - */ -Document.prototype.documentElement= new HTMLElement(); -/** - * Property styleSheets - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type Array - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Document.prototype.styleSheets= new Array(); -/** - * function createElement(tagName) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {String} tagName - * @returns {Element} - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Element - */ -Document.prototype.createElement=function(tagName){return new HTMLElement();}; -/** - * function createDocumentFragment() - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @returns {DocumentFragment} - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see DocumentFragment - */ -Document.prototype.createDocumentFragment=function(){return new DocumentFragment();}; -/** - * function createTextNode(data) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {String} data - * @returns {Text} - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Text - */ -Document.prototype.createTextNode=function(data){return new Text();}; -/** - * function createComment(data) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {String} data - * @returns {Comment} - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Comment - */ -Document.prototype.createComment=function(data){return new Comment();}; -/** - * function createCDATASection(data) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {String} data - * @returns {CDATASection} - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see CDATASection - */ -Document.prototype.createCDATASection=function(data){}; -/** - * function createProcessingInstruction(target, data) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type ProcessingInstruction - * @param {String} target - * @param {String} data - * @returns {ProcessingInstruction} - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see ProcessingInstruction -*/ -Document.prototype.createProcessingInstruction=function(target, data){return new ProcessingInstruction();}; -/** - * function createAttribute(name) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {String} name - * @returns {Attr} - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Attr - */ -Document.prototype.createAttribute=function(name){return new Attr();}; -/** - * function createEntityReference(name) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {String} name - * @returns {EntityReference} - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see EntityReference - */ -Document.prototype.createEntityReference=function(name){return new EntityReference();}; -/** - * function getElementsByTagName(tagname) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {String} tagname - * @returns {NodeList} - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see NodeList - */ -Document.prototype.getElementsByTagName=function(tagname){return new NodeList();}; -/** - * function importNode(importedNode, deep) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {Node} importedNode - * @param {Boolean} deep - * @returns {Node} - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Node - */ -Document.prototype.importNode=function(importedNode, deep){return new Node();}; -/** - * function createElementNS(namespaceURI, qualifiedName) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {String} namespaceURI - * @param {String} qualifiedName - * @returns {Element} - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Element - */ -Document.prototype.createElementNS=function(namespaceURI, qualifiedName){return new HTMLElement();}; -/** - * function createEvent(String eventType) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {String} eventType - * @returns {Object} - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Element - */ -Document.prototype.createEvent=function(eventType){return new Object();}; -/** - * function createAttributeNS(namespaceURI, qualifiedName) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {String} namespaceURI - * @param {String} qualifiedName - * @returns {Attr} - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Attr - */ -Document.prototype.createAttributeNS=function(namespaceURI, qualifiedName){return new Attr();}; -/** - * function getElementsByTagNameNS(namespaceURI, localName) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {String} namespaceURI - * @param {String} localName - * @returns {NodeList} - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see NodeList - */ -Document.prototype.getElementsByTagNameNS=function(namespaceURI, localName){return new NodeList();}; -/** - * function getElementById(elementId) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {String} elementId - * @returns {Element} - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Element - */ -Document.prototype.getElementById=function(elementId){return new HTMLElement();}; - -/** - * Object Node() - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @augments Object - * @constructor - * @memberOf Node - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Object - */ -function Node(){}; -Node.prototype=new Object(); -/** - * Constant Node.ELEMENT_NODE=1 - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @constant - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Node.ELEMENT_NODE=1; -/** - * Constant Node.ATTRIBUTE_NODE=2 - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @constant - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Node.ATTRIBUTE_NODE=2; -/** - * Constant Node.TEXT_NODE=3 - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @constant - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Node.TEXT_NODE=3; -/** - * Constant Node.CDATA_SECTION_NODE=4 - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @constant - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Node.CDATA_SECTION_NODE=4; -/** - * Constant Node.ENTITY_REFERENCE_NODE=5 - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @constant - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Node.ENTITY_REFERENCE_NODE=5; -/** - * Constant Node.ENTITY_NODE=6 - * @type Number - * @memberOf Node - * @see Node - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - - * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html -*/ -Node.ENTITY_NODE=6; -/** - * Constant Node.PROCESSING_INSTRUCTION_NODE=7 - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @constant - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Node.PROCESSING_INSTRUCTION_NODE=7; -/** - * Constant Node.COMMENT_NODE=8 - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @constant - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Node.COMMENT_NODE=8; -/** - * Constant Node.DOCUMENT_NODE=9 - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @constant - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Node.DOCUMENT_NODE=9; -/** - * Constant Node.DOCUMENT_TYPE_NODE=10 - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @constant - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Node.DOCUMENT_TYPE_NODE=10; -/** - * Constant Node.DOCUMENT_FRAGMENT_NODE=11 - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @constant - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Node.DOCUMENT_FRAGMENT_NODE=11; -/** - * Constant Node.NOTATION_NODE=12 - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @constant - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Node.NOTATION_NODE=12; -/** - * Property nodeName - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Node.prototype.nodeName = ""; -/** - * Property nodeValue - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type String - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Node.prototype.nodeValue = ""; -/** - * Property nodeType - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Node.prototype.nodeType = 0; -/** - * Property parentNode - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type Node - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Node - */ -Node.prototype.parentNode=new Node(); -/** - * Property childNodes - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type NodeList - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see NodeList -*/ -Node.prototype.childNodes=new NodeList(); -/** - * Property firstChild - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type Node - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Node - */ -Node.prototype.firstChild=new Node(); -/** - * Property lastChild - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type Node - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Node - */ -Node.prototype.lastChild=new Node(); -/** - * Property previousSibling - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type Node - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Node - */ -Node.prototype.previousSibling=new Node(); -/** - * Property nextSibling - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type Node - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Node - */ -Node.prototype.nextSibling=new Node(); -/** - * Property attributes - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type NamedNodeMap - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see NamedNodeMap - */ -Node.prototype.attributes=new NamedNodeMap(); -/** - * Property ownerDocument - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type Document - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Document - */ -Node.prototype.ownerDocument = new HTMLDocument(); -/** - * Property namespaceURI - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Node.prototype.namespaceURI=""; -/** - * Property prefix - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type String - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Node.prototype.prefix = ""; -/** - * Property localName - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Node.prototype.localName= ""; -/** - * function insertBefore(newChild, refChild) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {Node} newChild - * @param {Node} refChild - * @returns {Node} - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Node - */ -Node.prototype.insertBefore = function(newChild, refChild){return new Node();}; -/** - * function replaceChild(newChild, oldChild) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {Node} newChild - * @param {Node} oldChild - * @returns {Node} - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Node - */ -Node.prototype.replaceChild = function(newChild, oldChild){return new Node();}; -/** - * function removeChild(oldChild) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {Node} oldChild - * @returns {Node} - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Node - */ -Node.prototype.removeChild = function(oldChild){return new Node();}; -/** - * function appendChild(newChild) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {Node} newChild - * @returns {Node} - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Node - */ -Node.prototype.appendChild = function(newChild){return new Node();}; -/** - * function hasChildNodes() - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @returns {Boolean} - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Node.prototype.hasChildNodes=function(){return false;}; -/** - * function cloneNode(deep) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {Boolean} deep - * @returns {Node} - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Node - */ -Node.prototype.cloneNode=function(deep){return new Node();}; -/** - * function normalize() - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Node.prototype.normalize = function(){}; -/** - * function isSupported(feature, version) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {String} feature - * @param {String} version - * @returns {Boolean} - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Node.prototype.isSupported=function(feature, version){return false;}; -/** - * function hasAttributes() - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @returns {Boolean} - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Node.prototype.hasAttributes=function(){return false;}; - -/** - * Object NodeList() - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @augments Object - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Object - */ -function NodeList(){}; -NodeList.prototype = new Object(); -/** - * Property length - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -NodeList.prototype.length=0; -/** - * function item(index) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * Note: This object can also be dereferenced using square bracket notation (e.g. obj[1]). Dereferencing with an integer index is equivalent to invoking the item method with that index - * - * @param {Number} index - * @returns {Node} - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Node -*/ -NodeList.prototype.item = function(index){return new Node();}; - -/** - * Object NamedNodeMap() - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @augments Object - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Object - */ -function NamedNodeMap(){}; -NamedNodeMap.prototype = new Object(); -/** - * Property length - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -NamedNodeMap.prototype.length=0; -/** - * function getNamedItem(name) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {String} name - * @returns {Node} - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Node - */ -NamedNodeMap.prototype.getNamedItem=function(name){return new Node();}; -/** - * function setNamedItem(arg) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {Node} arg - * @returns {Node} - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Node - */ -NamedNodeMap.prototype.setNamedItem=function(arg){return new Node();}; -/** - * function removeNamedItem(name) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {String} name - * @returns {Node} - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Node - */ -NamedNodeMap.prototype.removeNamedItem=function(name){return new Node();}; -/** - * function item(index) - * Note: This object can also be dereferenced using square bracket notation (e.g. obj[1]). Dereferencing with an integer index is equivalent to invoking the item method with that index. - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {Number} index - * @returns {Node} - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Node - */ -NamedNodeMap.prototype.item=function(index){return new Node();}; -/** - * function getNamedItemNS(namespaceURI, localName) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {String} namespaceURI - * @param {String} localName - * @returns {Node} - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Node - */ -NamedNodeMap.prototype.getNamedItemNS=function(namespaceURI, localName){return new Node();}; -/** - * function setNamedItemNS(arg) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {Node} arg - * @returns {Node} - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Node - */ -NamedNodeMap.prototype.setNamedItemNS=function(arg){return new Node();}; -/** - * function removeNamedItemNS(namespaceURI, localName) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {String} namespaceURI - * @param {String} localName - * @returns {Node} - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Node - */ -NamedNodeMap.prototype.removeNamedItemNS=function(namespaceURI, localName){return new Node();}; - -/** - * Object CharacterData() - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @augments Node - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Node - */ -function CharacterData(){}; -CharacterData.prototype=new Node(); -/** - * Property data - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type String - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -CharacterData.prototype.data=""; -/** - * Property length - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -CharacterData.prototype.length=0; -/** - * function substringData(offset, count) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {Number} offset - * @param {Number} count - * @returns {String} - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -CharacterData.prototype.substringData=function(offset, count){return "";}; -/** - * function appendData(arg) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {String} arg - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -CharacterData.prototype.appendData=function(arg){}; -/** - * function insertData(offset, arg) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {Number} offset - * @param {String} arg - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -CharacterData.prototype.insertData=function(offset, arg){}; -/** - * function deleteData(offset, count) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {Number} offset - * @param {Number} count - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -CharacterData.prototype.deleteData=function(offset, count){}; -/** - * function replaceData(offset, count, arg) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {Number} offset - * @param {Number} count - * @param {String} arg - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -CharacterData.prototype.replaceData=function(offset, count, arg){}; - -/** - * Object Attr() - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @augments Node - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Node - */ -function Attr(){}; -Attr.prototype = new Node(); -/** - * Property name - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Attr.prototype.name = ""; -/** - * Property specified - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type Boolean - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Attr.prototype.specified = false; -/** - * Property value - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type String - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Attr.prototype.value = ""; -/** - * Property ownerElement - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type Element - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Element - */ -Attr.prototype.ownerElement = new Element(); - -/** - * Object Element() - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @augments Node - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Node - */ -function Element(){}; -Element.prototype=new Node(); -/** - * Property tagName - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Element.prototype.tagName=""; -/** - * function addEventListener(Stirng type, Function listener, Boolean useCapture) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {String} type - * @param {Function} listener - * @param {Boolean} useCapture - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Element.prototype.addEventListener=function(type, listener, useCapture){}; -/** - * function attachEvent(String type, Function listener) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {String} type - * @param {Function} listener - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Element.prototype.attachEvent=function(type, listener){}; -/** - * function detachEvent(String type, Function listener) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {String} type - * @param {Function} listener - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Element.prototype.detachEvent=function(type, listener){}; -/** - * function dispatchEvent(Object event) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {Object} event - * @returns {Boolean} - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Element.prototype.dispatchEvent=function(event){return false;}; -/** - * function getAttribute(name) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {String} name - * @returns {String} - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Element.prototype.getAttribute=function(name){return "";}; -/** - * function setAttribute(name, value) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {String} name - * @param {String} value - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Element.prototype.setAttribute=function(name, value){}; -/** - * function removeAttribute(name) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {String} name - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Element.prototype.removeAttribute=function(name){}; -/** - * function getAttributeNode(name) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {String} name - * @returns {Attr} - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Element.prototype.getAttributeNode=function(name){return new Attr();}; -/** - * function setAttributeNode(newAttr) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {Attr} newAttr - * @returns {Attr} - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Element.prototype.setAttributeNode=function(newAttr){return new Attr();}; -/** - * function removeAttributeNode(oldAttr) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {Attr} oldAttr - * @returns {Attr} - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Element.prototype.removeAttributeNode=function(oldAttr){return new Attr();}; -/** - * function getElementsByTagName(name) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {String} name - * @returns {NodeList} - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Element.prototype.getElementsByTagName=function(name){return new NodeList();}; -/** - * function getAttributeNS(namespaceURI, localName) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {String} namespaceURI - * @param {String} localName - * @returns {String} - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Element.prototype.getAttributeNS=function(namespaceURI, localName){return "";}; -/** - * function setAttributeNS(namespaceURI, qualifiedName, value) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {String} namespaceURI - * @param {String} qualifiedName - * @param {String} value - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Element.prototype.setAttributeNS=function(namespaceURI, qualifiedName, value){}; -/** - * function removeAttributeNS(namespaceURI, localName) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {String} namespaceURI - * @param {String} localName - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Element.prototype.removeAttributeNS=function(namespaceURI, localName){}; -/** - * function getAttributeNodeNS(namespaceURI, localName) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {String} namespaceURI - * @param {String} localName - * @returns {Attr} - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Element.prototype.getAttributeNodeNS=function(namespaceURI, localName){return new Attr();}; -/** - * function setAttributeNodeNS(newAttr) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {Attr} newAttr - * @returns {Attr} - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Element.prototype.setAttributeNodeNS=function(newAttr){return new Attr();}; -/** - * function getElementsByTagNameNS(namespaceURI, localName) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {String} namespaceURI - * @param {String} localName - * @returns {NodeList} - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Element.prototype.getElementsByTagNameNS=function(namespaceURI, localName){return new NodeList();}; -/** - * function hasAttribute(name) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {String} name - * @returns {Boolean} - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Element.prototype.hasAttribute=function(name){return false;}; -/** - * function hasAttributeNS(namespaceURI, localName) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {String} namespaceURI - * @param {String} localName - * @returns {Boolean} - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Element.prototype.hasAttributeNS=function(namespaceURI, localName){return false;}; - -/** - * Object Text() - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @augments CharacterData - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see CharacterData - */ -function Text(){}; -Text.prototype = new CharacterData(); -/** - * function splitText(offset) - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @param {Number} offset - * @returns {Text} - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Text - */ -Text.prototype.splitText = function(offset) {return new Text();}; - -/** - * Object Comment() - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @augments CharacterData - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see CharacterData - */ -function Comment(){}; -Comment.prototype = new CharacterData(); - -/** - * Object CDATASection() - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @augments Text - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Text - */ -function CDATASection(){}; -CDATASection.prototype = new Text(); - -/** - * Object DocumentType() - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @augments Node - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Node - */ -function DocumentType(){}; -DocumentType.prototype = new Node(); -/** - * Property name - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -DocumentType.prototype.name=""; -/** - * Property entities - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type NamedNodeMap - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -DocumentType.prototype.entities = new NamedNodeMap(); -/** - * Property notations - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type NamedNodeMap - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -DocumentType.prototype.notations=new NamedNodeMap(); -/** - * Property publicId - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -DocumentType.prototype.publicId=""; -/** - * Property systemId - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -DocumentType.prototype.systemId=""; -/** - * Property internalSubset - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -DocumentType.prototype.internalSubset=""; - -/** - * Object Notation() - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @augments Node - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Node - */ -function Notation(){}; -Notation.prototype=new Node(); -/** - * Property publicId - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Notation.prototype.publicId=""; -/** - * Property systemId - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Notation.prototype.systemId=""; - -/** - * Object Entity() - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @augments Node - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Node - */ -function Entity(){}; -Entity.prototype=new Node(); -/** - * Property publicId - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Entity.prototype.publicId=""; -/** - * Property systemId - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Entity.prototype.systemId=""; -/** - * Property notationName - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -Entity.prototype.notationName=""; - -/** - * Object EntityReference() - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @augments Node - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Node - */ -function EntityReference(){}; -EntityReference.prototype=new Node(); - -/** - * Object ProcessingInstruction() - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @augments Node - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - * @see Node - */ -function ProcessingInstruction(){}; -ProcessingInstruction.prototype=new Node(); -/** - * Property target - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -ProcessingInstruction.prototype.target=""; -/** - * Property target - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * - * @type String - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -ProcessingInstruction.prototype.data=""; - - -/*HTML DOM Below this line*/ - -/** - * Object HTMLCollection() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments Object - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -function HTMLCollection(){}; -HTMLCollection.prototype = new Object(); -/** - * Property length - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLCollection.prototype.length=0; -/** - * function item(index) - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @param {Number} index - * @returns {Node} - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLCollection.prototype.item = function(index){return new Node();}; -/** - * function namedItem(name) - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @param {String} name - * @returns {Node} - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLCollection.prototype.namedItem = function(index){return new Node();}; - -/** - * Object HTMLOptionsCollection() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments Object - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -function HTMLOptionsCollection(){}; -HTMLOptionsCollection.prototype = new Object(); -/** - * Property length - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Number - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLOptionsCollection.prototype.length=0; -/** - * function item(index) - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @param {Number} index - * @returns {Node} - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLOptionsCollection.prototype.item = function(index){return new Node();}; -/** - * function namedItem(name) - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @param {String} name - * @returns {Node} - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLOptionsCollection.prototype.namedItem = function(index){return new Node();}; - -/** - * Object HTMLDocument() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments Document - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see Document - */ -function HTMLDocument(){}; -HTMLDocument.prototype = new Document(); -/** - * Property title - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLDocument.prototype.title=""; -/** - * Property referrer - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLDocument.prototype.referrer=""; -/** - * Property domain - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLDocument.prototype.domain=""; -/** - * Property URL - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLDocument.prototype.URL=""; -/** - * Property body - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type HTMLElement - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLDocument.prototype.body=new HTMLElement(); -/** - * Property images - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type HTMLCollection - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLDocument.prototype.images=new HTMLCollection(); -/** - * Property applets - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type HTMLCollection - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLDocument.prototype.applets=new HTMLCollection(); -/** - * Property links - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type HTMLCollection - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLDocument.prototype.links=new HTMLCollection(); -/** - * Property forms - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type HTMLCollection - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLDocument.prototype.forms=new HTMLCollection(); -/** - * Property anchors - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type HTMLCollection - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLDocument.prototype.anchors=new HTMLCollection(); -/** - * Property cookie - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLDocument.prototype.cookie=""; -/** - * Property lastModified - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLDocument.prototype.lastModified=""; -/** - * function open() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLDocument.prototype.open = function(){}; -/** - * function close() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLDocument.prototype.close = function(){}; -/** - * function write(text) - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @param {String} text - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLDocument.prototype.write = function(text){}; -/** - * function writeln(text) - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @param {String} text - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLDocument.prototype.writeln = function(text){}; -/** - * function getElementsByName(elementName) - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @param {String} elementName - * @returns {NodeList} - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLDocument.prototype.getElementsByName = function(elementName){return new NodeList();}; - -/** - * Object HTMLElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments Element - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see Element - */ -function HTMLElement(){}; -HTMLElement.prototype = new Element(); -/** - * Property id - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLElement.prototype.id=""; -/** - * Property title - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLElement.prototype.title=""; -/** - * Property lang - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLElement.prototype.lang=""; -/** - * Property dir - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLElement.prototype.dir=""; -/** - * Property className - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLElement.prototype.className=""; -/** - * Property innerHTML - * - * @type String - */ -HTMLElement.prototype.innerHTML=""; -/** - * Property offsetHeight - * - * @type Number - */ -HTMLElement.prototype.offsetHeight=0; -/** - * Property offsetWidth - * - * @type Number - */ -HTMLElement.prototype.offsetWidth=0; -/** - * Property offsetLeft - * - * @type Number - */ -HTMLElement.prototype.offsetLeft=0; -/** - * Property offsetTop - * - * @type Number - */ -HTMLElement.prototype.offsetTop=0; -/** - * Property offsetParent - * - * @type HTMLElement - */ -HTMLElement.prototype.offsetParent = new HTMLElement(); -/** - * Property scrollHeight - * - * @type Number - */ -HTMLElement.prototype.scrollHeight=0; -/** - * Property scrollWidth - * - * @type Number - */ -HTMLElement.prototype.scrollWidth=0; -/** - * Property scrollLeft - * - * @type Number - */ -HTMLElement.prototype.scrollLeft=0; -/** - * Property scrollTop - * - * @type Number - */ -HTMLElement.prototype.scrollTop=0; -/** - * Property style - * - * @type CSS2Properties - */ -HTMLElement.prototype.style = new CSS2Properties(); - -/** - * Object HTMLHtmlElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLHtmlElement(){}; -HTMLHtmlElement.prototype = new HTMLElement(); -/** - * Property version - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLHtmlElement.prototype.version=""; - -/** - * Object HTMLHeadElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLHeadElement(){}; -HTMLHeadElement.prototype = new HTMLElement(); -/** - * Property profile - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLHeadElement.prototype.profile=""; - -/** - * Object HTMLLinkElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLLinkElement(){}; -HTMLLinkElement.prototype = new HTMLElement(); -/** - * Property disabled - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Boolean - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLLinkElement.prototype.disabled=false; -/** - * Property charset - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLLinkElement.prototype.charset=""; -/** - * Property href - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLLinkElement.prototype.href=""; -/** - * Property hreflang - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLLinkElement.prototype.hreflang=""; -/** - * Property media - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLLinkElement.prototype.media=""; -/** - * Property rel - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLLinkElement.prototype.rel=""; -/** - * Property rev - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLLinkElement.prototype.rev=""; -/** - * Property target - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLLinkElement.prototype.target=""; -/** - * Property type - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLLinkElement.prototype.type=""; - -/** - * Object HTMLTitleElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLTitleElement(){}; -HTMLTitleElement.prototype = new HTMLElement(); -/** - * Property text - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTitleElement.prototype.text=""; - -/** - * Object HTMLMetaElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLMetaElement(){}; -HTMLMetaElement.prototype = new HTMLElement(); -/** - * Property content - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLMetaElement.prototype.content=""; -/** - * Property httpEquiv - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLMetaElement.prototype.httpEquiv=""; -/** - * Property name - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLMetaElement.prototype.name=""; -/** - * Property scheme - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLMetaElement.prototype.scheme=""; - -/** - * Object HTMLBaseElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLBaseElement(){}; -HTMLBaseElement.prototype = new HTMLElement(); -/** - * Property href - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLBaseElement.prototype.href=""; -/** - * Property target - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLBaseElement.prototype.target=""; - -/** - * Object HTMLIsIndexElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLIsIndexElement(){}; -HTMLIsIndexElement.prototype = new HTMLElement(); -/** - * Property form - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type HTMLFormElement - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLIsIndexElement.prototype.form=new HTMLFormElement(); -/** - * Property prompt - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLIsIndexElement.prototype.prompt=""; - -/** - * Object HTMLStyleElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLStyleElement(){}; -HTMLStyleElement.prototype = new HTMLElement(); -/** - * Property disabled - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Boolean - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLStyleElement.prototype.disabled=false; -/** - * Property media - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLStyleElement.prototype.media=""; -/** - * Property type - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLStyleElement.prototype.type=""; - -/** - * Object HTMLBodyElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLBodyElement(){}; -HTMLBodyElement.prototype = new HTMLElement(); -/** - * Property aLink - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLBodyElement.prototype.aLink=""; -/** - * Property background - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLBodyElement.prototype.background=""; -/** - * Property bgColor - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLBodyElement.prototype.bgColor=""; -/** - * Property link - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLBodyElement.prototype.link=""; -/** - * Property text - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLBodyElement.prototype.text=""; -/** - * Property vLink - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLBodyElement.prototype.vLink=""; - -/** - * Object HTMLFormElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLFormElement(){}; -HTMLFormElement.prototype = new HTMLElement(); -/** - * Property elements - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type HTMLCollection - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLFormElement.prototype.elements=new HTMLCollection(); -/** - * Property length - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLFormElement.prototype.length=0; -/** - * Property name - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLFormElement.prototype.name=""; -/** - * Property acceptCharset - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLFormElement.prototype.acceptCharset=""; -/** - * Property action - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLFormElement.prototype.action=""; -/** - * Property enctype - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLFormElement.prototype.enctype=""; -/** - * Property method - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLFormElement.prototype.method=""; -/** - * Property target - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLFormElement.prototype.target=""; -/** - * function submit() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLFormElement.prototype.submit = function(){}; -/** - * function reset() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLFormElement.prototype.reset = function(){}; - -/** - * Object HTMLSelectElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLSelectElement(){}; -HTMLSelectElement.prototype = new HTMLElement(); -/** - * Property type - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLSelectElement.prototype.type=""; -/** - * Property selectedIndex - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLSelectElement.prototype.selectedIndex=0; -/** - * Property value - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLSelectElement.prototype.value=""; -/** - * Property length - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Number - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLSelectElement.prototype.length=0; -/** - * Property form - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type HTMLFormElement - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLSelectElement.prototype.form = new HTMLFormElement(); -/** - * Property options - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type HTMLOptionsCollection - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLSelectElement.prototype.options= new HTMLOptionsCollection(); -/** - * Property disabled - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Boolean - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLSelectElement.prototype.disabled=false; -/** - * Property multiple - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Boolean - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLSelectElement.prototype.multiple=false; -/** - * Property name - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLSelectElement.prototype.name=""; -/** - * Property size - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLSelectElement.prototype.size=0; -/** - * Property tabIndex - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLSelectElement.prototype.tabIndex=0; -/** - * function add(element, before) - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @param {HTMLElement} element - * @param {HTMLElement} before - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLSelectElement.prototype.add = function(element, before){}; -/** - * function remove(index) - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @param {Number} index - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLSelectElement.prototype.remove = function(index){}; -/** - * function blur() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLSelectElement.prototype.blur = function(){}; -/** - * function focus() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLSelectElement.prototype.focus = function(){}; - -/** - * Object HTMLOptGroupElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLOptGroupElement(){}; -HTMLOptGroupElement.prototype = new HTMLElement(); -/** - * Property disabled - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Boolean - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLOptGroupElement.prototype.disabled=false; -/** - * Property label - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLOptGroupElement.prototype.label=""; - -/** - * Object Option() - * @constructor - * @param {String} text - * @param {String} value - * @param {Boolean} defaultSelected - * @param {Boolean} selected - */ -function Option(text, value, defaultSelected, selected){}; -Option.prototype = new HTMLOptionElement(); -/** - * Object HTMLOptionElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLOptionElement(){}; -HTMLOptionElement.prototype = new HTMLElement(); -/** - * Property form - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type HTMLFormElement - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLOptionElement.prototype.form = new HTMLFormElement(); -/** - * Property defaultSelected - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Boolean - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLOptionElement.prototype.defaultSelected=false; -/** - * Property text - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLOptionElement.prototype.text=""; -/** - * Property index - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLOptionElement.prototype.index=0; -/** - * Property disabled - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Boolean - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLOptionElement.prototype.disabled=false; -/** - * Property label - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLOptionElement.prototype.label=""; -/** - * Property selected - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Boolean - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLOptionElement.prototype.selected=false; -/** - * Property value - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLOptionElement.prototype.value=""; - -/** - * Object HTMLInputElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLInputElement(){}; -HTMLInputElement.prototype = new HTMLElement(); -/** - * Property defaultValue - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLInputElement.prototype.defaultValue=""; -/** - * Property defaultChecked - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Boolean - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLInputElement.prototype.defaultChecked=false; -/** - * Property form - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type HTMLFormElement - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLInputElement.prototype.form = new HTMLFormElement(); -/** - * Property accept - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLInputElement.prototype.accept=""; -/** - * Property accessKey - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLInputElement.prototype.accessKey=""; -/** - * Property align - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLInputElement.prototype.align=""; -/** - * Property alt - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLInputElement.prototype.alt=""; -/** - * Property checked - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Boolean - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLInputElement.prototype.checked=false; -/** - * Property disabled - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Boolean - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLInputElement.prototype.disabled=false; -/** - * Property masLength - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLInputElement.prototype.maxLenght=0; -/** - * Property name - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLInputElement.prototype.name=""; -/** - * Property readOnly - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Boolean - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLInputElement.prototype.readOnly=false; -/** - * Property size - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLInputElement.prototype.size=0; -/** - * Property src - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLInputElement.prototype.src=""; -/** - * Property tabIndex - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLInputElement.prototype.tabIndex=0; -/** - * Property type - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLInputElement.prototype.type=""; -/** - * Property useMap - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLInputElement.prototype.useMap=""; -/** - * Property value - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLInputElement.prototype.value=""; -/** - * function blur() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLInputElement.prototype.blur = function(){}; -/** - * function focus() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLInputElement.prototype.focus = function(){}; -/** - * function select() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLInputElement.prototype.select = function(){}; -/** - * function click() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLInputElement.prototype.click = function(){}; - -/** - * Object HTMLTextAreaElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLTextAreaElement(){}; -HTMLTextAreaElement.prototype = new HTMLElement(); -/** - * Property defaultValue - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTextAreaElement.prototype.defaultValue=""; -/** - * Property form - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type HTMLFormElement - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTextAreaElement.prototype.form= new HTMLFormElement(); -/** - * Property accessKey - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTextAreaElement.prototype.accessKey=""; -/** - * Property cols - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTextAreaElement.prototype.cols=0; -/** - * Property disabled - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Boolean - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTextAreaElement.prototype.disabled=false; -/** - * Property name - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTextAreaElement.prototype.name=""; -/** - * Property readOnly - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Boolean - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTextAreaElement.prototype.readOnly=false; -/** - * Property rows - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTextAreaElement.prototype.rows=0; -/** - * Property tabIndex - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTextAreaElement.prototype.tabIndex=0; -/** - * Property type - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTextAreaElement.prototype.type=""; -/** - * Property value - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTextAreaElement.prototype.value=""; -/** - * function blur() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTextAreaElement.prototype.blur = function(){}; -/** - * function focus() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTextAreaElement.prototype.focus = function(){}; -/** - * function select() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTextAreaElement.prototype.select = function(){}; - -/** - * Object HTMLButtonElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLButtonElement(){}; -HTMLButtonElement.prototype = new HTMLElement(); -/** - * Property form - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type HTMLFormElement - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLButtonElement.prototype.form = new HTMLFormElement(); -/** - * Property accessKey - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLButtonElement.prototype.accessKey = ""; -/** - * Property disabled - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Boolean - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLButtonElement.prototype.disabled=false; -/** - * Property name - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLButtonElement.prototype.name=""; -/** - * Property tabIndex - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLButtonElement.prototype.tabIndex=0; -/** - * Property type - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLButtonElement.prototype.type=""; -/** - * Property value - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLButtonElement.prototype.value=""; - -/** - * Object HTMLLabelElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLLabelElement(){}; -HTMLLabelElement.prototype = new HTMLElement(); -/** - * Property form - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type HTMLFormElement - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLLabelElement.prototype.form = new HTMLFormElement(); -/** - * Property accessKey - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLLabelElement.prototype.accessKey=""; -/** - * Property htmlFor - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLLabelElement.prototype.htmlFor=""; - -/** - * Object HTMLFieldSetElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLFieldSetElement(){}; -HTMLFieldSetElement.prototype = new HTMLElement(); -/** - * Property form - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type HTMLFormElement - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLFieldSetElement.prototype.form = new HTMLFormElement(); - -/** - * Object HTMLLegendElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLLegendElement(){}; -HTMLLegendElement.prototype = new HTMLElement(); -/** - * Property form - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type HTMLFormElement - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLLegendElement.prototype.form = new HTMLFormElement(); -/** - * Property accessKey - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLLegendElement.prototype.accessKey=""; -/** - * Property align - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLLegendElement.prototype.align=""; - -/** - * Object HTMLUListElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLUListElement(){}; -HTMLUListElement.prototype = new HTMLElement(); -/** - * Property compact - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Boolean - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLUListElement.prototype.compact=false; -/** - * Property type - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLUListElement.prototype.type=""; - -/** - * Object HTMLOListElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLOListElement(){}; -HTMLOListElement.prototype = new HTMLElement(); -/** - * Property compact - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Boolean - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLOListElement.prototype.compact=false; -/** - * Property start - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLOListElement.prototype.start=0; -/** - * Property type - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLOListElement.prototype.type=""; - -/** - * Object HTMLDListElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLDListElement(){}; -HTMLDListElement.prototype = new HTMLElement(); -/** - * Property compact - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Boolean - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLDListElement.prototype.compact=false; - -/** - * Object HTMLDirectoryElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLDirectoryElement(){}; -HTMLDirectoryElement.prototype = new HTMLElement(); -/** - * Property compact - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Boolean - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLDirectoryElement.prototype.compact=false; - -/** - * Object HTMLMenuElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLMenuElement(){}; -HTMLMenuElement.prototype = new HTMLElement(); -/** - * Property compact - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Boolean - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLMenuElement.prototype.compact=false; - -/** - * Object HTMLLIElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLLIElement(){}; -HTMLLIElement.prototype = new HTMLElement(); -/** - * Property type - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLLIElement.prototype.type=""; -/** - * Property value - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLLIElement.prototype.value=0; - -/** - * Object HTMLDivElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLDivElement(){}; -HTMLDivElement.prototype = new HTMLElement(); -/** - * Property align - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLDivElement.prototype.align=""; - -/** - * Object HTMLParagraphElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLParagraphElement(){}; -HTMLParagraphElement.prototype = new HTMLElement(); -/** - * Property align - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLParagraphElement.prototype.align=""; - -/** - * Object HTMLHeadingElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLHeadingElement(){}; -HTMLHeadingElement.prototype = new HTMLElement(); -/** - * Property align - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLHeadingElement.prototype.align=""; - -/** - * Object HTMLQuoteElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLQuoteElement(){}; -HTMLQuoteElement.prototype = new HTMLElement(); -/** - * Property align - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLQuoteElement.prototype.align=""; - -/** - * Object HTMLPreElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLPreElement(){}; -HTMLPreElement.prototype = new HTMLElement(); -/** - * Property width - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLPreElement.prototype.width=0; - -/** - * Object HTMLBRElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLBRElement(){}; -HTMLBRElement.prototype = new HTMLElement(); -/** - * Property clear - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLBRElement.prototype.clear=""; - -/** - * Object HTMLBaseFontElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLBaseFontElement(){}; -HTMLBaseFontElement.prototype = new HTMLElement(); -/** - * Property color - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLBaseFontElement.prototype.color=""; -/** - * Property face - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLBaseFontElement.prototype.face=""; -/** - * Property size - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLBaseFontElement.prototype.size=0; - -/** - * Object HTMLBaseFontElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLFontElement(){}; -HTMLFontElement.prototype = new HTMLElement(); -/** - * Property color - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLFontElement.prototype.color=""; -/** - * Property face - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLFontElement.prototype.face=""; -/** - * Property size - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLFontElement.prototype.size=0; - -/** - * Object HTMLHRElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLHRElement(){}; -HTMLHRElement.prototype = new HTMLElement(); -/** - * Property align - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLHRElement.prototype.align=""; -/** - * Property noShade - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Boolean - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLHRElement.prototype.noShade=false; -/** - * Property size - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLHRElement.prototype.size=""; -/** - * Property width - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLHRElement.prototype.width=""; - -/** - * Object HTMLModElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLModElement(){}; -HTMLModElement.prototype = new HTMLElement(); -/** - * Property cite - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLModElement.prototype.cite=""; -/** - * Property dateTime - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLModElement.prototype.dateTime=""; - -/** - * Object HTMLAnchorElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLAnchorElement(){}; -HTMLAnchorElement.prototype = new HTMLElement(); -/** - * Property accessKey - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLAnchorElement.prototype.accessKey=""; -/** - * Property charset - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLAnchorElement.prototype.charset=""; -/** - * Property coords - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLAnchorElement.prototype.coords=""; -/** - * Property href - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLAnchorElement.prototype.href=""; -/** - * Property hreflang - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLAnchorElement.prototype.hreflang=""; -/** - * Property name - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLAnchorElement.prototype.name=""; -/** - * Property rel - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLAnchorElement.prototype.rel=""; -/** - * Property rev - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLAnchorElement.prototype.rev=""; -/** - * Property shape - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLAnchorElement.prototype.shape=""; -/** - * Property tabIndex - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLAnchorElement.prototype.tabIndex=0; -/** - * Property target - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLAnchorElement.prototype.target=""; -/** - * Property type - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLAnchorElement.prototype.type=""; -/** - * function blur() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLAnchorElement.prototype.blur = function(){}; -/** - * function focus() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLAnchorElement.prototype.focus = function(){}; - -/** - * Object Image() - * @constructor - * @param {Number} width - * @param {Number} height - */ -function Image(width, height){}; -Image.prototype = new HTMLImageElement(); -/** - * Object HTMLImageElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLImageElement(){}; -HTMLImageElement.prototype = new HTMLElement(); -/** - * Property name - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLImageElement.prototype.name=""; -/** - * Property align - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLImageElement.prototype.align=""; -/** - * Property alt - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLImageElement.prototype.alt=""; -/** - * Property border - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLImageElement.prototype.border=""; -/** - * Property height - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLImageElement.prototype.height=0; -/** - * Property hspace - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLImageElement.prototype.hspace=0; -/** - * Property isMap - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Boolean - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLImageElement.prototype.isMap=false; -/** - * Property longDesc - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLImageElement.prototype.longDesc=""; -/** - * Property src - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLImageElement.prototype.src=""; -/** - * Property useMap - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLImageElement.prototype.useMap=""; -/** - * Property vspace - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLImageElement.prototype.vspace=0; -/** - * Property width - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLImageElement.prototype.width=0; - -/** - * Object HTMLObjectElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLObjectElement(){}; -HTMLObjectElement.prototype = new HTMLElement(); -/** - * Property form - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type HTMLFormElement - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLObjectElement.prototype.form = new HTMLFormElement(); -/** - * Property code - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLObjectElement.prototype.code=""; -/** - * Property align - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLObjectElement.prototype.align=""; -/** - * Property archive - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLObjectElement.prototype.archive=""; -/** - * Property border - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLObjectElement.prototype.border=""; -/** - * Property codeBase - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLObjectElement.prototype.codeBase=""; -/** - * Property codeType - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLObjectElement.prototype.codeType=""; -/** - * Property data - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLObjectElement.prototype.data=""; -/** - * Property declare - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Boolean - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLObjectElement.prototype.declare=false; -/** - * Property height - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLObjectElement.prototype.height=""; -/** - * Property hspace - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLObjectElement.prototype.hspace=0; -/** - * Property name - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLObjectElement.prototype.name=""; -/** - * Property standby - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLObjectElement.prototype.standby=""; -/** - * Property tabIndex - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLObjectElement.prototype.tabIndex=0; -/** - * Property type - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLObjectElement.prototype.type=""; -/** - * Property useMap - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLObjectElement.prototype.useMap=""; -/** - * Property vspace - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLObjectElement.prototype.vspace=0; -/** - * Property width - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLObjectElement.prototype.width=""; -/** - * Property contentDocument - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Document - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLObjectElement.prototype.contentDocument= new HTMLDocument(); - -/** - * Object HTMLParamElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLParamElement(){}; -HTMLParamElement.prototype = new HTMLElement(); -/** - * Property name - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLParamElement.prototype.name=""; -/** - * Property type - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLParamElement.prototype.type=""; -/** - * Property value - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLParamElement.prototype.value=""; -/** - * Property valueType - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLParamElement.prototype.valueType=""; - -/** - * Object HTMLAppletElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLAppletElement(){}; -HTMLAppletElement.prototype = new HTMLElement(); -/** - * Property align - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLAppletElement.prototype.align=""; -/** - * Property alt - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLAppletElement.prototype.alt=""; -/** - * Property archive - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLAppletElement.prototype.archive=""; -/** - * Property code - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLAppletElement.prototype.code=""; -/** - * Property codeBase - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLAppletElement.prototype.codeBase=""; -/** - * Property height - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLAppletElement.prototype.hight=""; -/** - * Property hspace - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLAppletElement.prototype.hspace=0; -/** - * Property name - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLAppletElement.prototype.name=""; -/** - * Property object - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLAppletElement.prototype.object=""; -/** - * Property vspace - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLAppletElement.prototype.vspace=0; -/** - * Property width - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLAppletElement.prototype.width=""; - -/** - * Object HTMLMapElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLMapElement(){}; -HTMLMapElement.prototype = new HTMLElement(); -/** - * Property areas - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type HTMLCollection - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLMapElement.prototype.areas = new HTMLCollection(); -/** - * Property name - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLMapElement.prototype.name=""; - -/** - * Object HTMLAreaElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLAreaElement(){}; -HTMLAreaElement.prototype = new HTMLElement(); -/** - * Property accessKey - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLAreaElement.prototype.accessKey=""; -/** - * Property alt - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLAreaElement.prototype.alt=""; -/** - * Property coords - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLAreaElement.prototype.coords=""; -/** - * Property href - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLAreaElement.prototype.href=""; -/** - * Property noHref - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Boolean - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLAreaElement.prototype.noHref=false; -/** - * Property shape - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLAreaElement.prototype.shape=""; -/** - * Property tabIndex - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLAreaElement.prototype.tabIndex=0; -/** - * Property target - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLAreaElement.prototype.target=""; - -/** - * Object HTMLScriptElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLScriptElement(){}; -HTMLScriptElement.prototype = new HTMLElement(); -/** - * Property text - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLScriptElement.prototype.text=""; -/** - * Property htmlFor - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLScriptElement.prototype.htmlFor=""; -/** - * Property event - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLScriptElement.prototype.event=""; -/** - * Property charset - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLScriptElement.prototype.charset=""; -/** - * Property defer - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLScriptElement.prototype.defer=""; -/** - * Property src - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLScriptElement.prototype.src=""; -/** - * Property type - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLScriptElement.prototype.type=""; - -/** - * Object HTMLTableElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLTableElement(){}; -HTMLTableElement.prototype = new HTMLElement(); -/** - * Property caption - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type HTMLTableCaptionElement - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableElement.prototype.caption = new HTMLTableCaptionElement(); -/** - * Property tHead - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type HTMLTableSectionElement - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableElement.prototype.tHead = new HTMLTableSelectionElement(); -/** - * Property tFoot - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type HTMLTableSectionElement - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableElement.prototype.tFoot = new HTMLTableSelectionElement(); -/** - * Property rows - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type HTMLCollection - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableElement.prototype.rows = new HTMLCollection(); -/** - * Property tBodies - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type HTMLCollection - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableElement.prototype.tBodies = new HTMLCollection(); -/** - * Property align - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableElement.prototype.align=""; -/** - * Property bgColor - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableElement.prototype.bgColor=""; -/** - * Property border - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableElement.prototype.border=""; -/** - * Property cellPadding - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableElement.prototype.cellPadding=""; -/** - * Property cellSpacing - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableElement.prototype.cellSpacing=""; -/** - * Property frame - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableElement.prototype.frame=""; -/** - * Property rules - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableElement.prototype.rules=""; -/** - * Property summary - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableElement.prototype.summary=""; -/** - * Property width - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableElement.prototype.width=""; -/** - * function createTHead(); - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @returns {HTMLElement} - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableElement.prototype.createTHead = function(){return new HTMLElement();}; -/** - * function deleteTHead(); - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableElement.prototype.deleteTHead = function(){}; -/** - * function createTFoot(); - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @returns {HTMLElement} - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableElement.prototype.createTFoot = function(){return new HTMLElement();}; -/** - * function deleteTFoot(); - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableElement.prototype.deleteTFoot = function(){}; -/** - * function createCaption(); - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @returns {HTMLElement} - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableElement.prototype.createCaption = function(){return new HTMLElement();}; -/** - * function deleteCaption(); - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableElement.prototype.deleteCaption = function(){}; -/** - * function insertRow(index) - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @param {Number} index - * @returns {HTMLElement} - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableElement.prototype.insertRow = function(index){return new HTMLElement();}; -/** - * function deleteRow(index) - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @param {Number} index - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableElement.prototype.deleteRow = function(index){}; - -/** - * Object HTMLTableCaptionElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLTableCaptionElement(){}; -HTMLTableCaptionElement.prototype = new HTMLElement(); -/** - * Property align - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableCaptionElement.prototype.align=""; - -/** - * Object HTMLTableColElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLTableColElement(){}; -HTMLTableColElement.prototype = new HTMLElement(); -/** - * Property align - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableColElement.prototype.align=""; -/** - * Property ch - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableColElement.prototype.ch=""; -/** - * Property chOff - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableColElement.prototype.chOff=""; -/** - * Property span - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableColElement.prototype.span=0; -/** - * Property vAlign - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableColElement.prototype.vAlign=""; -/** - * Property width - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableColElement.prototype.width=""; - -/** - * Object HTMLTableSelectionElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLTableSelectionElement(){}; -HTMLTableSelectionElement.prototype = new HTMLElement(); -/** - * Property align - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableSelectionElement.prototype.align=""; -/** - * Property ch - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableSelectionElement.prototype.ch=""; -/** - * Property chOff - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableSelectionElement.prototype.chOff=""; -/** - * Property vAlign - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableSelectionElement.prototype.vAlign=""; -/** - * Property rows - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableSelectionElement.prototype.rows=""; -/** - * function insertRow(index) - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @param {Number} index - * @returns {HTMLElement} - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableSelectionElement.prototype.insertRow = function(index){return new HTMLElement();}; -/** - * function deleteRow(index) - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @param {Number} index - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableSelectionElement.prototype.deleteRow = function(index){}; - -/** - * Object HTMLTableRowElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLTableRowElement(){}; -HTMLTableRowElement.prototype = new HTMLElement(); -/** - * Property rowIndex - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableRowElement.prototype.rowIndex=0; -/** - * Property sectionRowIndex - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableRowElement.prototype.sectionRowIndex=0; -/** - * Property cells - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type HTMLCollection - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableRowElement.prototype.cells = new HTMLCollection(); -/** - * Property align - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableRowElement.prototype.align=""; -/** - * Property bgColor - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableRowElement.prototype.bgColor=""; -/** - * Property ch - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableRowElement.prototype.ch=""; -/** - * Property chOff - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableRowElement.prototype.chOff=""; -/** - * Property vAlign - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableRowElement.prototype.vAlign=""; -/** - * function insertCell(index) - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @param {Number} index - * @returns {HTMLElement} - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableRowElement.prototype.insertCell = function(index){return new HTMLElement();}; -/** - * function insertCell(index) - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @param {Number} index - * @throws DOMException - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableRowElement.prototype.deleteCell = function(index){}; - -/** - * Object HTMLTableRowElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLTableCellElement(){}; -HTMLTableCellElement.prototype = new HTMLElement(); -/** - * Property cellIndex - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableCellElement.prototype.cellIndex=0; -/** - * Property abbr - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableCellElement.prototype.abbr=""; -/** - * Property align - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableCellElement.prototype.align=""; -/** - * Property axis - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableCellElement.prototype.axis=""; -/** - * Property bgColor - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableCellElement.prototype.bgColor=""; -/** - * Property ch - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableCellElement.prototype.ch=""; -/** - * Property chOff - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableCellElement.prototype.chOff=""; -/** - * Property colSpan - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableCellElement.prototype.colSpan=0; -/** - * Property headers - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableCellElement.prototype.headers=""; -/** - * Property height - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableCellElement.prototype.height=""; -/** - * Property noWrap - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Boolean - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableCellElement.prototype.noWrap=false; -/** - * Property rowSpan - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Number - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableCellElement.prototype.rowSpan=0; -/** - * Property scope - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableCellElement.prototype.scope=""; -/** - * Property vAlign - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableCellElement.prototype.vAlign=""; -/** - * Property width - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLTableCellElement.prototype.width=""; - -/** - * Object HTMLFrameSetElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLFrameSetElement(){}; -HTMLFrameSetElement.prototype = new HTMLElement(); -/** - * Property cols - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLFrameSetElement.prototype.cols=""; -/** - * Property rows - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLFrameSetElement.prototype.rows=""; - -/** - * Object HTMLFrameElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLFrameElement(){}; -HTMLFrameElement.prototype = new HTMLElement(); -/** - * Property frameBorder - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLFrameElement.prototype.frameBorder=""; -/** - * Property longDesc - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLFrameElement.prototype.longDesc=""; -/** - * Property marginHeight - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLFrameElement.prototype.marginHeight=""; -/** - * Property marginWidth - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLFrameElement.prototype.marginWidth=""; -/** - * Property name - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLFrameElement.prototype.name=""; -/** - * Property noResize - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Boolean - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLFrameElement.prototype.noResize=false; -/** - * Property scrolling - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLFrameElement.prototype.scrolling=""; -/** - * Property src - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLFrameElement.prototype.src=""; -/** - * Property contentDocument - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Document - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLFrameElement.prototype.contentDocument= new HTMLDocument(); - -/** - * Object HTMLIFrameElement() - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @augments HTMLElement - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - * @see HTMLElement - */ -function HTMLIFrameElement(){}; -HTMLIFrameElement.prototype = new HTMLElement(); -/** - * Property align - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLIFrameElement.prototype.align=""; -/** - * Property frameBorder - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLIFrameElement.prototype.frameBorder=""; -/** - * Property height - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLIFrameElement.prototype.height=""; -/** - * Property longDesc - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLIFrameElement.prototype.longDesc=""; -/** - * Property marginHeight - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLIFrameElement.prototype.marginHeight=""; -/** - * Property marginWidth - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLIFrameElement.prototype.marginWidth=""; -/** - * Property name - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLIFrameElement.prototype.name=""; -/** - * Property scrolling - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLIFrameElement.prototype.scrolling=""; -/** - * Property src - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLIFrameElement.prototype.src=""; -/** - * Property width - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type String - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLIFrameElement.prototype.width=""; -/** - * Property contentDocument - * http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html - * - * @type Document - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model HTML Specification. - */ -HTMLIFrameElement.prototype.contentDocument= new HTMLDocument(); - -/* Stylesheets */ -/** - * Object CSS2Properties() - * http://www.w3.org/TR/2000/REC-DOM-Level-2-Style-20001113/ecma-script-binding.html - * - * @augments Object - * @constructor - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Style Specification. - */ -function CSS2Properties(){}; -CSS2Properties.prototype = new Object(); \ No newline at end of file +/******************************************************************************* + * Copyright (c) 2013 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + ******************************************************************************/ + +/** + * function querySelector(selectors) + * http://www.w3.org/TR/2012/PR-selectors-api-20121213 + * @param {String} selectors + * @memberOf Document + * @returns {Element} + */ +Document.prototype.querySelector=function(selectors){return new Element();}; + +/** + * function querySelectorAll(selectors) + * http://www.w3.org/TR/2012/PR-selectors-api-20121213 + * @param {String} selectors + * @memberOf Document + * @returns {NodeList} + */ +Document.prototype.querySelectorAll=function(selectors){return new NodeList();}; + +/** + * function querySelector(selectors) + * http://www.w3.org/TR/2012/PR-selectors-api-20121213 + * @param {String} selectors + * @memberOf DocumentFragment + * @returns {Element} + */ +DocumentFragment.prototype.querySelector=function(selectors){return new Element();}; + +/** + * function querySelectorAll(selectors) + * http://www.w3.org/TR/2012/PR-selectors-api-20121213 + * @param {String} selectors + * @memberOf DocumentFragment + * @returns {NodeList} + */ +DocumentFragment.prototype.querySelectorAll=function(selectors){return new NodeList();}; + +/** + * function querySelector(selectors) + * http://www.w3.org/TR/2012/PR-selectors-api-20121213 + * @param {String} selectors + * @memberOf Element + * @returns {Element} + */ +Element.prototype.querySelector=function(selectors){return new Element();}; + +/** + * function querySelectorAll(selectors) + * http://www.w3.org/TR/2012/PR-selectors-api-20121213 + * @param {String} selectors + * @memberOf Element + * @returns {NodeList} + */ +Element.prototype.querySelectorAll=function(selectors){return new NodeList();}; + +/** + * Property state + * @type Object + * @memberOf History + */ +History.prototype.state=new Object(); + +/** + * function pushState(data,title,url) + * http://www.w3.org/TR/2012/CR-html5-20121217/browsers.html#history + * @param {Object} data + * @param {String} title + * @param {String} url - optional + * @memberOf History + */ +History.prototype.pushState=function(data,title,url){}; + +/** + * function replaceState(data,title,url) + * http://www.w3.org/TR/2012/CR-html5-20121217/browsers.html#history + * @param {Object} data + * @param {String} title + * @param {String} url - optional + * @memberOf History + */ +History.prototype.replaceState=function(data,title,url){}; + +/** + * Property sessionStorage + * http://www.w3.org/TR/2011/CR-webstorage-20111208 + * @type Storage + * @memberOf Window + */ +Window.prototype.sessionStorage=new Storage(); + +/** + * Property localStorage + * http://www.w3.org/TR/2011/CR-webstorage-20111208 + * @type Storage + * @memberOf Window + */ +Window.prototype.localStorage=new Storage(); + +/** + * Object Storage + * http://www.w3.org/TR/2011/CR-webstorage-20111208 + */ +function Storage(){}; +Storage.prototype=new Object(); + +/** + * Property length + * http://www.w3.org/TR/2011/CR-webstorage-20111208 + * @type Number + * @memberOf Storage + */ +Storage.prototype.length=new Number(); + +/** + * function key(index) + * http://www.w3.org/TR/2011/CR-webstorage-20111208 + * @param {Number} index + * @memberOf Storage + * @returns String + */ +Storage.prototype.key=function(index){return new String();}; + +/** + * function getItem(key) + * http://www.w3.org/TR/2011/CR-webstorage-20111208 + * @param {String} key + * @memberOf Storage + * @returns String + */ +Storage.prototype.getItem=function(key){return new String();}; + +/** + * function setItem(key,value) + * http://www.w3.org/TR/2011/CR-webstorage-20111208 + * @param {String} key + * @param {String} value + * @memberOf Storage + */ +Storage.prototype.setItem=function(key,value){}; + +/** + * function removeItem(key) + * http://www.w3.org/TR/2011/CR-webstorage-20111208 + * @param {String} key + * @memberOf Storage + */ +Storage.prototype.removeItem=function(key){}; + +/** + * function clear() + * http://www.w3.org/TR/2011/CR-webstorage-20111208 + * @memberOf Storage + */ +Storage.prototype.clear=function(){}; + +/** + * Object WebSocket + * http://www.w3.org/TR/2012/CR-websockets-20120920 + * @constructor + * @param {String} url + */ +function WebSocket(url){}; +WebSocket.prototype=new Object(); + +/** + * Constant WebSocket.CONNECTING=0 + * http://www.w3.org/TR/2012/CR-websockets-20120920 + * @constant + * @type Number + */ +WebSocket.prototype.CONNECTING=0; + +/** + * Constant WebSocket.OPEN=1 + * http://www.w3.org/TR/2012/CR-websockets-20120920 + * @constant + * @type Number + */ +WebSocket.prototype.OPEN=1; + +/** + * Constant WebSocket.CLOSING=2 + * http://www.w3.org/TR/2012/CR-websockets-20120920 + * @constant + * @type Number + */ +WebSocket.prototype.CLOSING=2; + +/** + * Constant WebSocket.CLOSED=3 + * http://www.w3.org/TR/2012/CR-websockets-20120920 + * @constant + * @type Number + */ +WebSocket.prototype.CLOSED=3; + +/** + * Property url + * http://www.w3.org/TR/2012/CR-websockets-20120920 + * @type String + * @memberOf WebSocket + */ +WebSocket.prototype.url=new String(); + +/** + * Property readyState + * http://www.w3.org/TR/2012/CR-websockets-20120920 + * @type Number + * @memberOf WebSocket + */ +WebSocket.prototype.readyState=new Number(); + +/** + * Property bufferedAmount + * http://www.w3.org/TR/2012/CR-websockets-20120920 + * @type Number + * @memberOf WebSocket + */ +WebSocket.prototype.bufferedAmount=new Number(); + +/** + * Property extensions + * http://www.w3.org/TR/2012/CR-websockets-20120920 + * @type String + * @memberOf WebSocket + */ +WebSocket.prototype.extensions=new String(); + +/** + * Property protocol + * http://www.w3.org/TR/2012/CR-websockets-20120920 + * @type String + * @memberOf WebSocket + */ +WebSocket.prototype.protocol=new String(); + +/** + * Property binaryType + * http://www.w3.org/TR/2012/CR-websockets-20120920 + * @type String + * @memberOf WebSocket + */ +WebSocket.prototype.binaryType=new String(); + +/** + * function close(code,reason) + * http://www.w3.org/TR/2012/CR-websockets-20120920 + * @param {Number} code - optional + * @param {String} reason - optional + * @memberOf WebSocket + */ +WebSocket.prototype.close=function(code,reason){}; + +/** + * function send(data) + * http://www.w3.org/TR/2012/CR-websockets-20120920 + * @param {Object} data - may be a String, Blob, ArrayBuffer, or ArrayBufferView + * @memberOf WebSocket + */ +WebSocket.prototype.send=function(data){}; + +/** + * Property geolocation + * http://www.w3.org/TR/2012/PR-geolocation-API-20120510 + * @type Geolocation + * @memberOf Navigator + */ +Navigator.prototype.geolocation=new Geolocation(); + +/** + * Object Geolocation + * http://www.w3.org/TR/2012/PR-geolocation-API-20120510 + */ +function Geolocation(){}; +Geolocation.prototype=new Object(); + +/** + * function getCurrentPosition(successCallback,errorCallback,options) + * http://www.w3.org/TR/2012/PR-geolocation-API-20120510/ + * @param {Function} successCallback (Position pos) + * @param {Function} errorCallback (PositionError error) - optional + * @param {PositionOptions} options - optional + * @memberOf Geolocation + */ +Geolocation.prototype.getCurrentPosition=function(successCallback,errorCallback,options){}; + +/** + * function watchPosition(successCallback,errorCallback,options) + * http://www.w3.org/TR/2012/PR-geolocation-API-20120510/ + * @param {Function} successCallback (Position pos) + * @param {Function} errorCallback (PositionError error) - optional + * @param {PositionOptions} options - optional + * @memberOf Geolocation + * @returns {Number} + */ +Geolocation.prototype.watchPosition=function(successCallback,errorCallback,options){return new Number();}; + +/** + * function clearWatch(watchId) + * http://www.w3.org/TR/2012/PR-geolocation-API-20120510 + * @param {Number} watchId + * @memberOf Geolocation + */ +Geolocation.prototype.clearWatch=function(watchId){}; + +/** + * Object Coordinates + * http://www.w3.org/TR/2012/PR-geolocation-API-20120510 + */ +function Coordinates(){}; +Coordinates.prototype=new Object(); + +/** + * Property latitude + * http://www.w3.org/TR/2012/PR-geolocation-API-20120510 + * @type Number + * @memberOf Coordinates + */ +Coordinates.prototype.latitude=new Number();; + +/** + * Property longitude + * http://www.w3.org/TR/2012/PR-geolocation-API-20120510 + * @type Number + * @memberOf Coordinates + */ +Coordinates.prototype.longitude=new Number();; + +/** + * Property altitude + * http://www.w3.org/TR/2012/PR-geolocation-API-20120510 + * @type Number + * @memberOf Coordinates + */ +Coordinates.prototype.altitude=new Number();; + +/** + * Property accuracy + * http://www.w3.org/TR/2012/PR-geolocation-API-20120510 + * @type Number + * @memberOf Coordinates + */ +Coordinates.prototype.accuracy=new Number();; + +/** + * Property altitudeAccuracy + * http://www.w3.org/TR/2012/PR-geolocation-API-20120510 + * @type Number + * @memberOf Coordinates + */ +Coordinates.prototype.altitudeAccuracy=new Number();; + +/** + * Property heading + * http://www.w3.org/TR/2012/PR-geolocation-API-20120510 + * @type Number + * @memberOf Coordinates + */ +Coordinates.prototype.heading=new Number();; + +/** + * Property speed + * http://www.w3.org/TR/2012/PR-geolocation-API-20120510 + * @type Number + * @memberOf Coordinates + */ +Coordinates.prototype.speed=new Number(); + +/** + * Object Position + * http://www.w3.org/TR/2012/PR-geolocation-API-20120510 + */ +function Position(){}; +Position.prototype=new Object(); + +/** + * Property coords + * http://www.w3.org/TR/2012/PR-geolocation-API-20120510 + * @type Coordinates + * @memberOf Position + */ +Position.prototype.coords=new Coordinates(); + +/** + * Property timestamp + * http://www.w3.org/TR/2012/PR-geolocation-API-20120510 + * @type Number + * @memberOf Position + */ +Position.prototype.timestamp=new Number; + +/** + * Object PositionError + * http://www.w3.org/TR/2012/PR-geolocation-API-20120510 + */ +function PositionError(){}; +PositionError.prototype=new Object(); + +/** + * Constant PositionError.PERMISSION_DENIED=1 + * http://www.w3.org/TR/2012/PR-geolocation-API-20120510 + * @constant + * @type Number + */ +PositionError.prototype.PERMISSION_DENIED=1; + +/** + * Constant PositionError.POSITION_UNAVAILABLE=2 + * http://www.w3.org/TR/2012/PR-geolocation-API-20120510 + * @constant + * @type Number + */ +PositionError.prototype.POSITION_UNAVAILABLE=2; + +/** + * Constant PositionError.TIMEOUT=3 + * http://www.w3.org/TR/2012/PR-geolocation-API-20120510 + * @constant + * @type Number + */ +PositionError.prototype.TIMEOUT=3; + +/** + * Property code + * http://www.w3.org/TR/2012/PR-geolocation-API-20120510 + * @type Number + * @memberOf PositionError + */ +PositionError.prototype.code=new Number(); + +/** + * Property message + * http://www.w3.org/TR/2012/PR-geolocation-API-20120510 + * @type String + * @memberOf PositionError + */ +PositionError.prototype.message=new String(); + +/** + * Object PositionOptions + * http://www.w3.org/TR/2012/PR-geolocation-API-20120510 + */ +function PositionOptions(){}; +PositionOptions.prototype=new Object(); + +/** + * Property enableHighAccuracy + * http://www.w3.org/TR/2012/PR-geolocation-API-20120510 + * @type Boolean + * @memberOf PositionOptions + */ +PositionOptions.prototype.enableHighAccuracy=new Boolean(); + +/** + * Property timeout + * http://www.w3.org/TR/2012/PR-geolocation-API-20120510 + * @type Number + * @memberOf PositionOptions + */ +PositionOptions.prototype.timeout=new Number(); + +/** + * Property maximumAge + * http://www.w3.org/TR/2012/PR-geolocation-API-20120510 + * @type Number + * @memberOf PositionOptions + */ +PositionOptions.prototype.maximumAge=new Number(); + +/** + * Object TimeRanges + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + */ +function TimeRanges(){}; +TimeRanges.prototype=new Object(); + +/** + * Property length + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @type Number + * @memberOf TimeRanges + */ +TimeRanges.prototype.length=new Number(); + +/** + * function start(index) + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @param {Number} index + * @memberOf TimeRanges + * @returns {Number} + */ +function start(index) {return new Number();}; + +/** + * function end(index) + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @param {Number} index + * @memberOf TimeRanges + * @returns {Number} + */ +function end(index) {return new Number();}; + +/** + * Object MediaError + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + */ +function MediaError(){}; +MediaError.prototype=new Object(); + +/** + * Constant MediaError.MEDIA_ERR_ABORTED=1 + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @constant + * @type Number + */ +MediaError.prototype.MEDIA_ERR_ABORTED=1; + +/** + * Constant MediaError.MEDIA_ERR_NETWORK=2 + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @constant + * @type Number + */ +MediaError.prototype.MEDIA_ERR_NETWORK=2; + +/** + * Constant MediaError.MEDIA_ERR_DECODED=3 + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @constant + * @type Number + */ +MediaError.prototype.MEDIA_ERR_DECODE=3; + +/** + * Constant MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED=4 + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @constant + * @type Number + */ +MediaError.prototype.MEDIA_ERR_SRC_NOT_SUPPORTED=4; + +/** + * Property code + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @type Number + * @memberOf MediaError + */ +MediaError.prototype.code=new Number(); + +/** + * Object HTMLMediaElement + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @augments HTMLElement + * @see HTMLElement + */ +function HTMLMediaElement(){}; +HTMLMediaElement.prototype = new HTMLElement(); + +/** + * Property src + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @type String + * @memberOf HTMLMediaElement + */ +HTMLMediaElement.prototype.src=new String(); + +/** + * Property currentSrc + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @type String + * @memberOf HTMLMediaElement + */ +HTMLMediaElement.prototype.currentSrc=new String(); + +/** + * Property crossOrigin + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @type String + * @memberOf HTMLMediaElement + */ +HTMLMediaElement.prototype.crossOrigin=new String(); + +/** + * Constant HTMLMediaElement.NETWORK_EMPTY=0 + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @constant + * @type Number + */ +HTMLMediaElement.prototype.NETWORK_EMPTY=0; + +/** + * Constant HTMLMediaElement.NETWORK_IDLE=1 + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @constant + * @type Number + */ +HTMLMediaElement.prototype.NETWORK_IDLE=1; + +/** + * Constant HTMLMediaElement.NETWORK_LOADING=2 + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @constant + * @type Number + */ +HTMLMediaElement.prototype.NETWORK_LOADING=2; + +/** + * Constant HTMLMediaElement.NETWORK_NO_SOURCE=3 + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @constant + * @type Number + */ +HTMLMediaElement.prototype.NETWORK_NO_SOURCE=3; + +/** + * Property networkState + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @type Number + * @memberOf HTMLMediaElement + */ +HTMLMediaElement.prototype.networkState=new Number(); + +/** + * Property preload + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @type String + * @memberOf HTMLMediaElement + */ +HTMLMediaElement.prototype.preload=new String(); + +/** + * Property buffered + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @type TimeRanges + * @memberOf HTMLMediaElement + */ +HTMLMediaElement.prototype.buffered=new TimeRanges(); + +/** + * function load() + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @memberOf HTMLMediaElement + */ +HTMLMediaElement.prototype.load=function(){}; + +/** + * function canPlayType(type) + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @param {String} type + * @memberOf HTMLMediaElement + * @returns {String} + */ +HTMLMediaElement.prototype.canPlayType=function(type){new String();}; + +/** + * Constant HTMLMediaElement.HAVE_NOTHING=0 + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @constant + * @type Number + */ +HTMLMediaElement.prototype.HAVE_NOTHING=0; + +/** + * Constant HTMLMediaElement.HAVE_METADATA=1 + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @constant + * @type Number + */ +HTMLMediaElement.prototype.HAVE_METADATA=1; + +/** + * Constant HTMLMediaElement.HAVE_CURRENT_DATA=2 + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @constant + * @type Number + */ +HTMLMediaElement.prototype.HAVE_CURRENT_DATA=2; + +/** + * Constant HTMLMediaElement.HAVE_FUTURE_DATA=3 + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @constant + * @type Number + */ +HTMLMediaElement.prototype.HAVE_FUTURE_DATA=3; + +/** + * Constant HTMLMediaElement.HAVE_ENOUGH_DATA=4 + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @constant + * @type Number + */ +HTMLMediaElement.prototype.HAVE_ENOUGH_DATA=4; + +/** + * Property readyState + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @type Number + * @memberOf HTMLMediaElement + */ +HTMLMediaElement.prototype.readyState=new Number(); + +/** + * Property seeking + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @type Boolean + * @memberOf HTMLMediaElement + */ +HTMLMediaElement.prototype.seeking=new Boolean(); + +/** + * Property currentTime + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @type Number + * @memberOf HTMLMediaElement + */ +HTMLMediaElement.prototype.currentTime=new Number(); + +/** + * Property initialTime + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @type Number + * @memberOf HTMLMediaElement + */ +HTMLMediaElement.prototype.initialTime=new Number(); + +/** + * Property duration + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @type Number + * @memberOf HTMLMediaElement + */ +HTMLMediaElement.prototype.duration=new Number(); + +/** + * Property startOffsetTime + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @type Date + * @memberOf HTMLMediaElement + */ +HTMLMediaElement.prototype.startOffsetTime=new Date(); + +/** + * Property paused + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @type Boolean + * @memberOf HTMLMediaElement + */ +HTMLMediaElement.prototype.paused=new Boolean(); + +/** + * Property defaultPlaybackRate + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @type Number + * @memberOf HTMLMediaElement + */ +HTMLMediaElement.prototype.defaultPlaybackRate=new Number(); + +/** + * Property playbackRate + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @type Number + * @memberOf HTMLMediaElement + */ +HTMLMediaElement.prototype.playbackRate=new Number(); + +/** + * Property played + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @type TimeRanges + * @memberOf HTMLMediaElement + */ +HTMLMediaElement.prototype.played=new TimeRanges(); + +/** + * Property seekable + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @type TimeRanges + * @memberOf HTMLMediaElement + */ +HTMLMediaElement.prototype.seekable=new TimeRanges(); + +/** + * Property ended + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @type Boolean + * @memberOf HTMLMediaElement + */ +HTMLMediaElement.prototype.ended=new Boolean(); + +/** + * Property autoplay + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @type Boolean + * @memberOf HTMLMediaElement + */ +HTMLMediaElement.prototype.autoplay=new Boolean(); + +/** + * Property loop + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @type Boolean + * @memberOf HTMLMediaElement + */ +HTMLMediaElement.prototype.loop=new Boolean(); + +/** + * function play() + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @memberOf HTMLMediaElement + */ +HTMLMediaElement.prototype.play=function(){}; + +/** + * function pause() + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @memberOf HTMLMediaElement + */ +HTMLMediaElement.prototype.pause=function(){}; + +/** + * Property controls + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @type Boolean + * @memberOf HTMLMediaElement + */ +HTMLMediaElement.prototype.controls=new Boolean(); + +/** + * Property volume + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @type Number + * @memberOf HTMLMediaElement + */ +HTMLMediaElement.prototype.volume=new Number(); + +/** + * Property muted + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @type Boolean + * @memberOf HTMLMediaElement + */ +HTMLMediaElement.prototype.muted=new Boolean(); + +/** + * Property defaultMuted + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @type Boolean + * @memberOf HTMLMediaElement + */ +HTMLMediaElement.prototype.defaultMuted=new Boolean(); + +/** + * Object HTMLAudioElement + * http://www.w3.org/TR/2012/WD-html5-20120329/the-audio-element.html + * @augments HTMLMediaElement + * @constructor + * @param {String} src + * @see HTMLMediaElement + */ +function HTMLAudioElement(src){}; +HTMLAudioElement.prototype = new HTMLMediaElement(); + +/** + * Object HTMLVideoElement + * http://www.w3.org/TR/2012/WD-html5-20120329/the-audio-element.html + * @augments HTMLMediaElement + * @see HTMLMediaElement + */ +function HTMLVideoElement(){}; +HTMLVideoElement.prototype = new HTMLMediaElement(); + +/** + * Property width + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @type Number + * @memberOf HTMLVideoElement + */ +HTMLVideoElement.prototype.width=new Number(); + +/** + * Property height + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @type Number + * @memberOf HTMLVideoElement + */ +HTMLVideoElement.prototype.height=new Number(); + +/** + * Property videoWidth + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @type Number + * @memberOf HTMLVideoElement + */ +HTMLVideoElement.prototype.videoWidth=new Number(); + +/** + * Property videoHeight + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @type Number + * @memberOf HTMLVideoElement + */ +HTMLVideoElement.prototype.videoHeight=new Number(); + +/** + * Property poster + * http://www.w3.org/TR/2012/WD-html5-20120329/media-elements.html + * @type String + * @memberOf HTMLVideoElement + */ +HTMLVideoElement.prototype.poster=new String(); + diff --git a/bundles/org.eclipse.wst.jsdt.core/libraries/system.js b/bundles/org.eclipse.wst.jsdt.core/libraries/system.js index 184cb12a..adcea3f6 100644 --- a/bundles/org.eclipse.wst.jsdt.core/libraries/system.js +++ b/bundles/org.eclipse.wst.jsdt.core/libraries/system.js @@ -914,59 +914,43 @@ Date.prototype.setUTCFullYear = function(year, month,date){}; */ Date.prototype.toUTCString = function(){return "";}; -/** - * Object Global - * @super Object - * @constructor - * @memberOf Global - * @since Standard ECMA-262 3rd. Edition - * @since Level 2 Document Object Model Core Definition. - */ -function Global(){}; -Global.prototype=new Object(); /** * Property NaN - * @memberOf Global * @since Standard ECMA-262 3rd. Edition * @since Level 2 Document Object Model Core Definition. */ -Global.prototype.NaN=0; +var NaN=0; /** * Property Infinity - * @memberOf Global * @since Standard ECMA-262 3rd. Edition * @since Level 2 Document Object Model Core Definition. */ -Global.prototype.Infinity=0; +var Infinity=0; /** * function eval(s) - * @memberOf Global * @param {String} s * @type Object * @returns {Object} * @since Standard ECMA-262 3rd. Edition * @since Level 2 Document Object Model Core Definition. */ -Global.prototype.eval=function(s){return new Object();}; +function eval(s){return new Object();}; //@GINO: Bug 197987 (Temp Fix) /** * Property debugger - * @memberOf Global * @description Debugger keyword */ -Global.prototype.debugger=null; +var debugger=null; /** * Property undefined - * @memberOf Global * @description undefined */ -Global.prototype.undefined=null; +var undefined=null; /** * function parseInt(s,radix) - * @memberOf Global * @param {String} s * @param {Number} radix * @type Number @@ -974,97 +958,88 @@ Global.prototype.undefined=null; * @since Standard ECMA-262 3rd. Edition * @since Level 2 Document Object Model Core Definition. */ -Global.prototype.parseInt=function(s,radix){return 0;}; +function parseInt(s,radix){return 0;}; /** * function parseFloat(s) - * @memberOf Global * @param {String} s * @type Number * @returns {Number} * @since Standard ECMA-262 3rd. Edition * @since Level 2 Document Object Model Core Definition. */ -Global.prototype.parseFloat=function(s){return 0;}; +function parseFloat(s){return 0;}; /** * function escape(s) - * @memberOf Global * @param {String} s * @type String * @returns {String} * @since Standard ECMA-262 3rd. Edition * @since Level 2 Document Object Model Core Definition. */ -Global.prototype.escape=function(s){return "";}; +function escape(s){return "";}; /** * function unescape(s) - * @memberOf Global * @param {String} s * @type String * @returns {String} * @since Standard ECMA-262 3rd. Edition * @since Level 2 Document Object Model Core Definition. */ -Global.prototype.unescape=function(s){return "";}; +function unescape(s){return "";}; /** * function isNaN(number) - * @memberOf Global * @param {String} number * @type Boolean * @returns {Boolean} * @since Standard ECMA-262 3rd. Edition * @since Level 2 Document Object Model Core Definition. */ -Global.prototype.isNaN=function(number){return false;}; +function isNaN(number){return false;}; /** * function isFinite(number) - * @memberOf Global * @param {String} number * @type Boolean * @returns {Boolean} * @since Standard ECMA-262 3rd. Edition * @since Level 2 Document Object Model Core Definition. */ -Global.prototype.isFinite=function(number){return false;}; +function isFinite(number){return false;}; /** * function decodeURI(encodedURI) - * @memberOf Global * @param {String} encodedURI * @type String * @returns {String} * @since Standard ECMA-262 3rd. Edition * @since Level 2 Document Object Model Core Definition. */ -Global.prototype.decodeURI=function(encodedURI){return "";}; +function decodeURI(encodedURI){return "";}; /** - * @memberOf Global * @param {String} uriComponent * @type String * @returns {String} * @since Standard ECMA-262 3rd. Edition * @since Level 2 Document Object Model Core Definition. */ -Global.prototype.decodeURIComponent=function(uriComponent){return "";}; +function decodeURIComponent(uriComponent){return "";}; /** * function encodeURIComponent(uriComponent) - * @memberOf Global * @param {String} uriComponent * @type String * @returns {String} * @since Standard ECMA-262 3rd. Edition * @since Level 2 Document Object Model Core Definition. */ -Global.prototype.encodeURIComponent=function(uriComponent){return "";}; +function encodeURIComponent(uriComponent){return "";}; /** * function encodeURIComponent(URI) - * @memberOf Global * @param {String} URI * @type String * @returns {String} * @since Standard ECMA-262 3rd. Edition * @since Level 2 Document Object Model Core Definition. */ -Global.prototype.encodeURI=function(URI){return "";}; +function encodeURI(URI){return "";}; /** * Object Math(\s) diff --git a/bundles/org.eclipse.wst.jsdt.core/libraries/xhr.js b/bundles/org.eclipse.wst.jsdt.core/libraries/xhr.js index 87c4b3ff..4d6c011d 100644 --- a/bundles/org.eclipse.wst.jsdt.core/libraries/xhr.js +++ b/bundles/org.eclipse.wst.jsdt.core/libraries/xhr.js @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. + * Copyright (c) 2009, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -21,9 +21,7 @@ Window.prototype.createRequest= function(){return new XMLHttpRequest();}; /** * Object XMLHttpRequest -* @super Global * @type constructor -* @memberOf Global */ XMLHttpRequest.prototype=new Object(); function XMLHttpRequest(){}; diff --git a/bundles/org.eclipse.wst.jsdt.core/plugin.properties b/bundles/org.eclipse.wst.jsdt.core/plugin.properties index 0d82aa59..23833b90 100644 --- a/bundles/org.eclipse.wst.jsdt.core/plugin.properties +++ b/bundles/org.eclipse.wst.jsdt.core/plugin.properties @@ -8,6 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_NONE providerName=Eclipse Web Tools Platform pluginName=JavaScript Development Tools Core javaScriptNatureName=JavaScript diff --git a/bundles/org.eclipse.wst.jsdt.core/plugin.xml b/bundles/org.eclipse.wst.jsdt.core/plugin.xml index 1e917464..d123f955 100644 --- a/bundles/org.eclipse.wst.jsdt.core/plugin.xml +++ b/bundles/org.eclipse.wst.jsdt.core/plugin.xml @@ -184,17 +184,18 @@ + - - diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/BufferChangedEvent.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/BufferChangedEvent.java index 207ba45c..839cbad2 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/BufferChangedEvent.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/BufferChangedEvent.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/CompletionProposal.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/CompletionProposal.java index 4b67b5a3..a62bbedd 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/CompletionProposal.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/CompletionProposal.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2004, 2011 IBM Corporation and others. + * Copyright (c) 2004, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -13,6 +13,7 @@ package org.eclipse.wst.jsdt.core; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.wst.jsdt.core.compiler.CharOperation; import org.eclipse.wst.jsdt.internal.codeassist.InternalCompletionProposal; +import org.eclipse.wst.jsdt.internal.core.util.QualificationHelpers; /** * Completion proposal. @@ -838,7 +839,7 @@ public final class CompletionProposal extends InternalCompletionProposal { CompletionProposal(int kind, int completionLocation) { if ((kind < CompletionProposal.FIRST_KIND) || (kind > CompletionProposal.LAST_KIND)) { - throw new IllegalArgumentException(); + throw new IllegalArgumentException(toString()); } if (this.completion == null || completionLocation < 0) { // Work around for bug 132558 (https://bugs.eclipse.org/bugs/show_bug.cgi?id=132558). @@ -1110,7 +1111,7 @@ public final class CompletionProposal extends InternalCompletionProposal { */ public void setReplaceRange(int startIndex, int endIndex) { if (startIndex < 0 || endIndex < startIndex) { - throw new IllegalArgumentException(); + throw new IllegalArgumentException(toString()); } this.replaceStart = startIndex; this.replaceEnd = endIndex; @@ -1370,204 +1371,40 @@ public final class CompletionProposal extends InternalCompletionProposal { return this.key; } -// /** -// * Returns the package name of the relevant -// * declaration in the context, or null if none. -// *

-// * This field is available for the following kinds of -// * completion proposals: -// *

    -// *
  • ANONYMOUS_CLASS_DECLARATION - the dot-based package name -// * of the type that is being subclassed or implemented
  • -// *
  • FIELD_REF - the dot-based package name -// * of the type that declares the field that is referenced
  • -// *
  • FUNCTION_REF - the dot-based package name -// * of the type that declares the method that is referenced
  • -// *
  • FUNCTION_DECLARATION - the dot-based package name -// * of the type that declares the method that is being -// * implemented or overridden
  • -// *
-// * For kinds of completion proposals, this method returns -// * null. Clients must not modify the array -// * returned. -// *

-// * -// * @return the dot-based package name, or -// * null if none -// * @see #getDeclarationSignature() -// * @see #getSignature() -// * -// */ -// public char[] getDeclarationPackageName() { -// return this.declarationPackageName; -// } -// -// /** -// * Returns the type name of the relevant -// * declaration in the context without the package fragment, -// * or null if none. -// *

-// * This field is available for the following kinds of -// * completion proposals: -// *

    -// *
  • ANONYMOUS_CLASS_DECLARATION - the dot-based type name -// * of the type that is being subclassed or implemented
  • -// *
  • FIELD_REF - the dot-based type name -// * of the type that declares the field that is referenced -// * or an anonymous type instantiation ("new X(){}") if it is an anonymous type
  • -// *
  • FUNCTION_REF - the dot-based type name -// * of the type that declares the method that is referenced -// * or an anonymous type instantiation ("new X(){}") if it is an anonymous type
  • -// *
  • FUNCTION_DECLARATION - the dot-based type name -// * of the type that declares the method that is being -// * implemented or overridden
  • -// *
-// * For kinds of completion proposals, this method returns -// * null. Clients must not modify the array -// * returned. -// *

-// * -// * @return the dot-based package name, or -// * null if none -// * @see #getDeclarationSignature() -// * @see #getSignature() -// * -// */ + /** + * Returns the type name of the relevant + * declaration in the context without the package fragment, + * or null if none. + *

+ * This field is available for the following kinds of + * completion proposals: + *

    + *
  • ANONYMOUS_CLASS_DECLARATION - the dot-based type name + * of the type that is being subclassed or implemented
  • + *
  • FIELD_REF - the dot-based type name + * of the type that declares the field that is referenced + * or an anonymous type instantiation ("new X(){}") if it is an anonymous type
  • + *
  • FUNCTION_REF - the dot-based type name + * of the type that declares the method that is referenced + * or an anonymous type instantiation ("new X(){}") if it is an anonymous type
  • + *
  • FUNCTION_DECLARATION - the dot-based type name + * of the type that declares the method that is being + * implemented or overridden
  • + *
+ * For kinds of completion proposals, this method returns + * null. Clients must not modify the array + * returned. + *

+ * + * @return the dot-based package name, or + * null if none + * @see #getDeclarationSignature() + * @see #getSignature() + * + */ public char[] getDeclarationTypeName() { return this.declarationTypeName; } -// -// /** -// * Returns the package name of the method or type -// * relevant in the context, or null if none. -// *

-// * This field is available for the following kinds of -// * completion proposals: -// *

    -// *
  • FIELD_REF - the dot-based package name -// * of the referenced field's type
  • -// *
  • LOCAL_VARIABLE_REF - the dot-based package name -// * of the referenced local variable's type
  • -// *
  • FUNCTION_REF - the dot-based package name -// * of the return type of the method that is referenced
  • -// *
  • FUNCTION_DECLARATION - the dot-based package name -// * of the return type of the method that is being implemented -// * or overridden
  • -// *
  • PACKAGE_REF - the dot-based package name -// * of the package that is referenced
  • -// *
  • TYPE_REF - the dot-based package name -// * of the type that is referenced
  • -// *
  • VARIABLE_DECLARATION - the dot-based package name -// * of the type of the variable being declared
  • -// *
-// * For kinds of completion proposals, this method returns -// * null. Clients must not modify the array -// * returned. -// *

-// * -// * @return the package name, or null if none -// * -// * @see #getDeclarationSignature() -// * @see #getSignature() -// * -// */ -// public char[] getPackageName() { -// return this.packageName; -// } -// -// /** -// * Returns the type name without the package fragment of the method or type -// * relevant in the context, or null if none. -// *

-// * This field is available for the following kinds of -// * completion proposals: -// *

    -// *
  • FIELD_REF - the dot-based type name -// * of the referenced field's type
  • -// *
  • LOCAL_VARIABLE_REF - the dot-based type name -// * of the referenced local variable's type
  • -// *
  • FUNCTION_REF - the dot-based type name -// * of the return type of the method that is referenced
  • -// *
  • FUNCTION_DECLARATION - the dot-based type name -// * of the return type of the method that is being implemented -// * or overridden
  • -// *
  • TYPE_REF - the dot-based type name -// * of the type that is referenced
  • -// *
  • VARIABLE_DECLARATION - the dot-based package name -// * of the type of the variable being declared
  • -// *
-// * For kinds of completion proposals, this method returns -// * null. Clients must not modify the array -// * returned. -// *

-// * -// * @return the package name, or null if none -// * -// * @see #getDeclarationSignature() -// * @see #getSignature() -// * -// */ -// public char[] getTypeName() { -// return this.typeName; -// } -// -// /** -// * Returns the parameter package names of the method -// * relevant in the context, or null if none. -// *

-// * This field is available for the following kinds of -// * completion proposals: -// *

    -// *
  • ANONYMOUS_CLASS_DECLARATION - parameter package names -// * of the constructor that is being invoked
  • -// *
  • FUNCTION_REF - parameter package names -// * of the method that is referenced
  • -// *
  • FUNCTION_DECLARATION - parameter package names -// * of the method that is being implemented or overridden
  • -// *
-// * For kinds of completion proposals, this method returns -// * null. Clients must not modify the array -// * returned. -// *

-// * -// * @return the package name, or null if none -// * -// * @see #getDeclarationSignature() -// * @see #getSignature() -// * -// */ -// public char[][] getParameterPackageNames() { -// return this.parameterPackageNames; -// } -// -// /** -// * Returns the parameter type names without the package fragment of -// * the method relevant in the context, or null if none. -// *

-// * This field is available for the following kinds of -// * completion proposals: -// *

    -// *
  • ANONYMOUS_CLASS_DECLARATION - parameter type names -// * of the constructor that is being invoked
  • -// *
  • FUNCTION_REF - parameter type names -// * of the method that is referenced
  • -// *
  • FUNCTION_DECLARATION - parameter type names -// * of the method that is being implemented or overridden
  • -// *
-// * For kinds of completion proposals, this method returns -// * null. Clients must not modify the array -// * returned. -// *

-// * -// * @return the package name, or null if none -// * -// * @see #getDeclarationSignature() -// * @see #getSignature() -// * -// */ -// public char[][] getParameterTypeNames() { -// return this.parameterTypeNames; -// } /** * Sets the signature of the function, method, field type, member type, @@ -1861,6 +1698,14 @@ public final class CompletionProposal extends InternalCompletionProposal { public char[][] getParameterTypeNames() { return this.parameterTypeNames; } + + /** + * @return The fully qualified type name returned by the proposed function or + * the declared type of the proposed variable or field + */ + public char[] getReturnType() { + return QualificationHelpers.createFullyQualifiedName(this.getReturnQualification(), this.getReturnSimpleName()); + } /** * Returns the accessibility of the proposal. diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/CompletionRequestor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/CompletionRequestor.java index 28d6e07a..9cfe7b54 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/CompletionRequestor.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/CompletionRequestor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2004, 2007 IBM Corporation and others. + * Copyright (c) 2004, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IBufferFactory.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IBufferFactory.java index 96e9d337..dd41b9dc 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IBufferFactory.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IBufferFactory.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IElementChangedListener.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IElementChangedListener.java index 2c2e4214..5e347be3 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IElementChangedListener.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IElementChangedListener.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IIncludePathEntry.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IIncludePathEntry.java index 326e4f8d..fde5de47 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IIncludePathEntry.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IIncludePathEntry.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJavaScriptProject.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJavaScriptProject.java index 7f363d7f..12ff94dc 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJavaScriptProject.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJavaScriptProject.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -257,7 +257,6 @@ public interface IJavaScriptProject extends IParent, IJavaScriptElement, IOpenab * @see IType#getFullyQualifiedName(char) */ IType findType(String fullyQualifiedName, WorkingCopyOwner owner) throws JavaScriptModelException; - /** * Returns all the types found following this project's include path with * the given fully qualified name. The fully qualified name is a diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJsGlobalScopeContainer.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJsGlobalScopeContainer.java index 2976cb1b..22837bf8 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJsGlobalScopeContainer.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IJsGlobalScopeContainer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -132,8 +132,7 @@ public interface IJsGlobalScopeContainer { */ IPath getPath(); - /** - * Allows mapping between HTML imports and a toolkit's actual page imports. Implementers + /* allows mapping between HTML imports and a toolkits actual page imports. Implementers * should ensure the validity of the imports before returning a value. */ String[] resolvedLibraryImport(String a); diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IProblemRequestor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IProblemRequestor.java index 09027526..41ca4c91 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IProblemRequestor.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IProblemRequestor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IType.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IType.java index 4cf7706f..6668a255 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IType.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/IType.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -33,6 +33,12 @@ import org.eclipse.core.runtime.IProgressMonitor; * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken * (repeatedly) as the API evolves. *

+ * + * + * Provisional API: This class/interface is part of an interim API that is still under development and expected to + * change significantly before reaching stability. It is being made available at this early stage to solicit feedback + * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken + * (repeatedly) as the API evolves. */ public interface IType extends IMember, IFunctionContainer { diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ITypeHierarchyChangedListener.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ITypeHierarchyChangedListener.java index a831f143..cab5ff41 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ITypeHierarchyChangedListener.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ITypeHierarchyChangedListener.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/JavaScriptConventions.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/JavaScriptConventions.java index 866eb375..c76800d3 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/JavaScriptConventions.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/JavaScriptConventions.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -360,9 +360,6 @@ public final class JavaScriptConventions { if (!status.isOK()) { return status; } - if (CharOperation.contains('$', scannedID)) { - return new Status(IStatus.WARNING, JavaScriptCore.PLUGIN_ID, -1, Messages.convention_type_dollarName, null); - } if ((scannedID.length > 0 && ScannerHelper.isLowerCase(scannedID[0]))) { return new Status(IStatus.WARNING, JavaScriptCore.PLUGIN_ID, -1, Messages.convention_type_lowercaseName, null); } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/JavaScriptCore.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/JavaScriptCore.java index 853a9a0a..53c5bb73 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/JavaScriptCore.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/JavaScriptCore.java @@ -2921,7 +2921,8 @@ public final class JavaScriptCore extends Plugin { * {@link #newContainerEntry(IPath, IAccessRule[], IIncludePathAttribute[], boolean) * newContainerEntry(containerPath, new IAccessRule[0], new IIncludePathAttribute[0], false)}. *

- * @param containerPath the path identifying the container + * @param containerPath the path identifying the container, it must be formed of at least two + * segments * @return a new container includepath entry * * @see JavaScriptCore#getJsGlobalScopeContainer(IPath, IJavaScriptProject) @@ -3196,7 +3197,7 @@ public final class JavaScriptCore extends Plugin { boolean isExported) { if (path == null) Assert.isTrue(false, "Library path cannot be null"); //$NON-NLS-1$ - if (!path.isAbsolute()) Assert.isTrue(false, "Path for IIncludePathEntry must be absolute " + path.toString()); //$NON-NLS-1$ + if (!path.isAbsolute()) Assert.isTrue(false, "Path for IIncludePathEntry must be absolute: " + path.toString()); //$NON-NLS-1$ if (sourceAttachmentPath != null) { if (sourceAttachmentPath.isEmpty()) { sourceAttachmentPath = null; // treat empty path as none diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/LibrarySuperType.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/LibrarySuperType.java index 67cc8e22..fba5ee7d 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/LibrarySuperType.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/LibrarySuperType.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2011 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -124,7 +124,7 @@ public class LibrarySuperType { if(init==null) { return cpEntry.toString(); } - return init.getDescription(); + return init.getDescription(cpEntry, javaProject); } Object parent = getParent(); if(!(parent instanceof LibrarySuperType)) return null; diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/Messages.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/Messages.java index cf0ff21e..b74bdac6 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/Messages.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/Messages.java @@ -1,3 +1,13 @@ +/******************************************************************************* + * Copyright (c) 2011 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ package org.eclipse.wst.jsdt.core; import java.util.MissingResourceException; diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/Signature.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/Signature.java index 07c2dbb1..42b54412 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/Signature.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/Signature.java @@ -142,7 +142,7 @@ public final class Signature { */ public static final int ARRAY_TYPE_SIGNATURE = 4; - private static final char[] VOID = "void".toCharArray(); //$NON-NLS-1$ + public static final char[] VOID = "void".toCharArray(); //$NON-NLS-1$ public static final char[] ANY = "any".toCharArray(); //$NON-NLS-1$ private Signature() { diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IAbstractVariableDeclaration.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IAbstractVariableDeclaration.java index ddc9b380..99a843ec 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IAbstractVariableDeclaration.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IAbstractVariableDeclaration.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2008 IBM Corporation and others. + * Copyright (c) 2005, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -13,16 +13,12 @@ package org.eclipse.wst.jsdt.core.ast; import org.eclipse.wst.jsdt.core.infer.InferredType; /** - * Abstract representation of a var. *

- * This interface is not intended to be implemented by clients. + * Abstract representation of a var. *

- * Provisional API: This class/interface is part of an interim API that is still under development and expected to - * change significantly before reaching stability. It is being made available at this early stage to solicit feedback - * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken - * (repeatedly) as the API evolves. + * + * @noimplement This interface is not intended to be implemented by clients. */ - public interface IAbstractVariableDeclaration extends IStatement{ /** * Set the inferred type of the var @@ -49,5 +45,21 @@ public interface IAbstractVariableDeclaration extends IStatement{ * @return jsdoc */ public IJsDoc getJsDoc(); + + /** + * @param isType + * true if this variable declaration is actually a + * reference to a type, rather then the instance of a type. + * false if this variable is a reference to an + * instance of a type rather then the type itself. + */ + public void setIsType(boolean isType); + /** + * @return true if this variable declaration is actually a + * reference to a type, rather then the instance of a type. + * false if this variable is a reference to an + * instance of a type rather then the type itself. + */ + public boolean isType(); } \ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IAssignment.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IAssignment.java index ee31a8d9..40843aba 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IAssignment.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IAssignment.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2010 IBM Corporation and others. + * Copyright (c) 2005, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -14,16 +14,12 @@ package org.eclipse.wst.jsdt.core.ast; import org.eclipse.wst.jsdt.core.infer.InferredType; /** - * Representation of an assignment expression - *

- * This interface is not intended to be implemented by clients. + *

+ * Representation of an assignment expression *

-* Provisional API: This class/interface is part of an interim API that is still under development and expected to - * change significantly before reaching stability. It is being made available at this early stage to solicit feedback - * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken - * (repeatedly) as the API evolves. + * + *@noimplement This interface is not intended to be implemented by clients. */ - public interface IAssignment extends IExpression { /** @@ -50,5 +46,21 @@ public interface IAssignment extends IExpression { * @return inferred type */ public InferredType getInferredType(); + + /** + * @param isType + * true if this assignment is actually a assigning + * a type, rather then the instance of a type. + * false if this assignment is a assigning an + * instance of a type rather then the type itself. + */ + public void setIsType(boolean isType); + /** + * @return true if this assignment is actually a assigning a + * type, rather then the instance of a type. false if + * this assignment is a assigning an instance of a type rather + * then the type itself. + */ + public boolean isType(); } \ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IFunctionCall.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IFunctionCall.java index 967f1e00..577a5660 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IFunctionCall.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IFunctionCall.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2008 IBM Corporation and others. + * Copyright (c) 2005, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IFunctionDeclaration.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IFunctionDeclaration.java index 9f90e27c..e78489b2 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IFunctionDeclaration.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IFunctionDeclaration.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2008 IBM Corporation and others. + * Copyright (c) 2005, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ILocalDeclaration.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ILocalDeclaration.java index 4a92fe61..b416b7d4 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ILocalDeclaration.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/ILocalDeclaration.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2010 IBM Corporation and others. + * Copyright (c) 2005, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -34,4 +34,6 @@ public interface ILocalDeclaration extends InvocationSite, IAbstractVariableDecl * @return initialization assignment expression or null */ public IAssignment getAssignment(); + public void setIsLocal(boolean isLocal); + public boolean isLocal(); } \ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IObjectLiteral.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IObjectLiteral.java index 711c582e..fb220752 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IObjectLiteral.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IObjectLiteral.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2008 IBM Corporation and others. + * Copyright (c) 2005, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IReturnStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IReturnStatement.java index 6dabd13b..a9b77f19 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IReturnStatement.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/ast/IReturnStatement.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2008 IBM Corporation and others. + * Copyright (c) 2005, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -11,20 +11,45 @@ package org.eclipse.wst.jsdt.core.ast; +import org.eclipse.wst.jsdt.core.infer.InferredType; + /** * - * Representation of a return statement. + * Representation of a return statement. *

- * This interface is not intended to be implemented by clients. + * @noimplement This interface is not intended to be implemented by clients. *

- * Provisional API: This class/interface is part of an interim API that is still under development and expected to - * change significantly before reaching stability. It is being made available at this early stage to solicit feedback - * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken - * (repeatedly) as the API evolves. */ public interface IReturnStatement extends IStatement { IExpression getExpression(); + + /** + * @param type + * {@link InferredType} returned by this return statement + */ + void setInferredType(InferredType type); + + /** + * @return {@link InferredType} returned by this return statement + */ + InferredType getInferredType(); + + /** + * @param isType + * true if this return statement is actually + * returning a type, rather then the instance of a type. + * false if this return statement is returning an + * instance of a type rather then the type itself. + */ + public void setIsType(boolean isType); + /** + * @return true if this return statement is actually + * returning a type, rather then the instance of a type. + * false if this return statement is returning an + * instance of a type rather then the type itself. + */ + public boolean isType(); } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/CharOperation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/CharOperation.java index 4dc1e2d7..90415ae1 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/CharOperation.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/CharOperation.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -1089,20 +1089,21 @@ public static final char[] concatWith(char[][] array, char separator, boolean ig int size = length - 1; int index = length; while (--index >= 0) { - if (array[index].length == 0 && ignoreEmptyElements) + if ((array[index] == null || array[index].length == 0) && ignoreEmptyElements) { size--; - else - size += array[index].length; + } else { + size += array[index] != null ? array[index].length : 0; + } } if (size <= 0) return CharOperation.NO_CHAR; char[] result = new char[size]; index = length; while (--index >= 0) { - length = array[index].length; + length = array[index] != null ? array[index].length : 0; if (length > 0 || (length == 0 && !ignoreEmptyElements)) { System.arraycopy( - array[index], + array[index] != null ? array[index] : NO_CHAR, 0, result, (size -= length), @@ -1150,6 +1151,33 @@ public static final boolean contains(char character, char[][] array) { return false; } + /** + *

+ * Determines if a list of character arrays contains the given character + * array + *

+ * + * @param needle + * search for this character array in the given list of + * character arrays + * @param list + * search for the given character array in this list of + * character arrays + * + * @return true if the given list of character arrays + * contains the given character array, false + * otherwise + */ + public static final boolean contains(char[] needle, char[][] list) { + boolean contains = false; + + for (int i = 0; list != null && i < list.length && !contains; ++i) { + contains = CharOperation.equals(list[i], needle); + } + + return contains; + } + /** * Answers true if the array contains an occurrence of character, false otherwise. * @@ -2346,7 +2374,7 @@ public static final boolean match( } /* check current name character */ if ((isCaseSensitive ? name[iName] : ScannerHelper.toLowerCase(name[iName])) - != patternChar + != (isCaseSensitive ? patternChar : ScannerHelper.toLowerCase(patternChar)) && patternChar != '?') { iPattern = segmentStart; // mismatch - restart current segment iName = ++prefixStart; diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/IScanner.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/IScanner.java index f53f2421..a54502ed 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/IScanner.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/IScanner.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/ITerminalSymbols.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/ITerminalSymbols.java index 364a7b40..4f4c91e3 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/ITerminalSymbols.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/ITerminalSymbols.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/libraries/LibraryLocation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/libraries/LibraryLocation.java index 0c8ad26e..7414959a 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/libraries/LibraryLocation.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/compiler/libraries/LibraryLocation.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ASTConverter.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ASTConverter.java index 89d623fb..4174e258 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ASTConverter.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ASTConverter.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -34,6 +34,7 @@ import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocFieldReference; import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocMessageSend; import org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration; import org.eclipse.wst.jsdt.internal.compiler.ast.MessageSend; +import org.eclipse.wst.jsdt.internal.compiler.ast.ObjectGetterSetterField; import org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds; import org.eclipse.wst.jsdt.internal.compiler.ast.ProgramElement; import org.eclipse.wst.jsdt.internal.compiler.ast.StringLiteralConcatenation; @@ -346,13 +347,14 @@ class ASTConverter { int start = methodDeclaration.sourceStart; int end; SimpleName methodName =null; - if (methodDeclaration.selector!=null) + char[] name = methodDeclaration.getName(); + if (name!=null) { methodName = new SimpleName(this.ast); - methodName.internalSetIdentifier(new String(methodDeclaration.selector)); + methodName.internalSetIdentifier(new String(name)); end = retrieveIdentifierEndPosition(start, methodDeclaration.sourceEnd); - methodName.setSourceRange(start, end - start + 1); + methodName.setSourceRange(start, end == -1 ? 0 : end - start + 1); methodDecl.setName(methodName); } else @@ -1038,7 +1040,12 @@ class ASTConverter { int fieldsLength = fields.length; for (int i = 0; i < fieldsLength; i++) { - ObjectLiteralField objectLiteralField =convert(fields[i]); + ObjectLiteralField objectLiteralField = null; + if(fields[i] instanceof ObjectGetterSetterField) { + objectLiteralField = convert((ObjectGetterSetterField)fields[i]); + } else { + objectLiteralField = convert(fields[i]); + } objectLiteral.fields().add(objectLiteralField); } } @@ -1060,6 +1067,19 @@ class ASTConverter { } return objectLiteralField; } + + public ObjectLiteralField convert(org.eclipse.wst.jsdt.internal.compiler.ast.ObjectGetterSetterField field) { + ObjectLiteralField objectLiteralField = new ObjectLiteralField(this.ast); + objectLiteralField.setSourceRange(field.sourceStart, field.sourceEnd - field.sourceStart + 1); + + // ignore get set properties +// objectLiteralField.setFieldName( convert(field.fieldName)); +// objectLiteralField.setInitializer( convert(field.initializer)); +// if (this.resolveBindings) { +// recordNodes(objectLiteralField, field); +// } + return objectLiteralField; + } public RegularExpressionLiteral convert(org.eclipse.wst.jsdt.internal.compiler.ast.RegExLiteral expression) { int length = expression.sourceEnd - expression.sourceStart + 1; @@ -3111,7 +3131,7 @@ class ASTConverter { } } AbstractMethodDeclaration abstractMethodDeclaration = (AbstractMethodDeclaration) this.ast.getBindingResolver().getCorrespondingNode(currentNode); - return abstractMethodDeclaration.scope; + return abstractMethodDeclaration.getScope(); } protected void recordName(Name name, org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode compilerNode) { diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/AnonymousClassDeclaration.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/AnonymousClassDeclaration.java index 06dcd076..762b024f 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/AnonymousClassDeclaration.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/AnonymousClassDeclaration.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ArrayAccess.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ArrayAccess.java index e231a287..4c71b069 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ArrayAccess.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ArrayAccess.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ArrayCreation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ArrayCreation.java index ccac6043..e075b845 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ArrayCreation.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ArrayCreation.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ArrayInitializer.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ArrayInitializer.java index c316b562..da7e9194 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ArrayInitializer.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ArrayInitializer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ArrayType.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ArrayType.java index 8cc02211..585bca87 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ArrayType.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ArrayType.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Assignment.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Assignment.java index 0f11f13a..0f974470 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Assignment.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Assignment.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Block.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Block.java index 07e07ef4..59d0abf4 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Block.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Block.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/BodyDeclaration.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/BodyDeclaration.java index d63349a2..617b07d3 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/BodyDeclaration.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/BodyDeclaration.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/BooleanLiteral.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/BooleanLiteral.java index 7cbe3f67..d8385db5 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/BooleanLiteral.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/BooleanLiteral.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/BreakStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/BreakStatement.java index 5f13cfe8..8c000d67 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/BreakStatement.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/BreakStatement.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/CatchClause.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/CatchClause.java index f88f289a..ef5ba074 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/CatchClause.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/CatchClause.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/CharacterLiteral.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/CharacterLiteral.java index 05822760..4073f203 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/CharacterLiteral.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/CharacterLiteral.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Comment.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Comment.java index a3eafa72..087b9bc9 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Comment.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Comment.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2004, 2008 IBM Corporation and others. + * Copyright (c) 2004, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ConditionalExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ConditionalExpression.java index 995ae432..3ac84bdb 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ConditionalExpression.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ConditionalExpression.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ContinueStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ContinueStatement.java index 43ff09f8..1d270bac 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ContinueStatement.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ContinueStatement.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/DefaultBindingResolver.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/DefaultBindingResolver.java index f023af3f..3ee916d2 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/DefaultBindingResolver.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/DefaultBindingResolver.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -475,30 +475,6 @@ class DefaultBindingResolver extends BindingResolver { this.astNodesToBlockScope.put(astNode, blockScope); } - /* - * @see BindingResolver#resolveBoxing(Expression) - */ - boolean resolveBoxing(Expression expression) { - org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode node = (org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode) this.newAstToOldAst.get(expression); - if (node != null && (node instanceof org.eclipse.wst.jsdt.internal.compiler.ast.Expression)) { - org.eclipse.wst.jsdt.internal.compiler.ast.Expression compilerExpression = (org.eclipse.wst.jsdt.internal.compiler.ast.Expression) node; - return (compilerExpression.implicitConversion & TypeIds.BOXING) != 0; - } - return false; - } - - /* - * @see BindingResolver#resolveUnboxing(Expression) - */ - boolean resolveUnboxing(Expression expression) { - org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode node = (org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode) this.newAstToOldAst.get(expression); - if (node != null && (node instanceof org.eclipse.wst.jsdt.internal.compiler.ast.Expression)) { - org.eclipse.wst.jsdt.internal.compiler.ast.Expression compilerExpression = (org.eclipse.wst.jsdt.internal.compiler.ast.Expression) node; - return (compilerExpression.implicitConversion & TypeIds.UNBOXING) != 0; - } - return false; - } - /* * @see BindingResolver#resolveConstantExpressionValue(Expression) */ @@ -712,7 +688,7 @@ class DefaultBindingResolver extends BindingResolver { Object oldNode = this.newAstToOldAst.get(method); if (oldNode instanceof AbstractMethodDeclaration) { AbstractMethodDeclaration methodDeclaration = (AbstractMethodDeclaration) oldNode; - IFunctionBinding methodBinding = this.getMethodBinding(methodDeclaration.binding); + IFunctionBinding methodBinding = this.getMethodBinding(methodDeclaration.getBinding()); if (methodBinding == null) { return null; } @@ -890,7 +866,7 @@ class DefaultBindingResolver extends BindingResolver { } } else if (node instanceof AbstractMethodDeclaration) { AbstractMethodDeclaration methodDeclaration = (AbstractMethodDeclaration) node; - IFunctionBinding method = this.getMethodBinding(methodDeclaration.binding); + IFunctionBinding method = this.getMethodBinding(methodDeclaration.getBinding()); if (method == null) return null; return method.getReturnType(); } else if (node instanceof org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration) { @@ -1109,7 +1085,7 @@ class DefaultBindingResolver extends BindingResolver { } } else if (node instanceof AbstractMethodDeclaration) { AbstractMethodDeclaration methodDeclaration = (AbstractMethodDeclaration) node; - IFunctionBinding methodBinding = this.getMethodBinding(methodDeclaration.binding); + IFunctionBinding methodBinding = this.getMethodBinding(methodDeclaration.getBinding()); if (methodBinding != null) { return methodBinding; } @@ -1444,6 +1420,7 @@ class DefaultBindingResolver extends BindingResolver { synchronized ITypeBinding resolveWellKnownType(String name) { if (this.scope == null) return null; try { + // possible called by flow info // if (("boolean".equals(name))//$NON-NLS-1$ // || ("char".equals(name))//$NON-NLS-1$ // || ("byte".equals(name))//$NON-NLS-1$ diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/DoStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/DoStatement.java index d9c3514d..5804532d 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/DoStatement.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/DoStatement.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/EmptyExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/EmptyExpression.java index 52222876..338709f9 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/EmptyExpression.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/EmptyExpression.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/EmptyStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/EmptyStatement.java index 5d3a7503..ffe4d35b 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/EmptyStatement.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/EmptyStatement.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/EnhancedForStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/EnhancedForStatement.java index 37944475..2b0de6ab 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/EnhancedForStatement.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/EnhancedForStatement.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/FieldAccess.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/FieldAccess.java index 6a01a4e1..030b69ac 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/FieldAccess.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/FieldAccess.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ForInStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ForInStatement.java index 8725f0dc..67063f7b 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ForInStatement.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ForInStatement.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ForStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ForStatement.java index 7b8c6c0c..083387a6 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ForStatement.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ForStatement.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/FunctionBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/FunctionBinding.java index fe6b7f2d..ad9f933e 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/FunctionBinding.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/FunctionBinding.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -23,6 +23,7 @@ import org.eclipse.wst.jsdt.core.Signature; import org.eclipse.wst.jsdt.core.compiler.CharOperation; import org.eclipse.wst.jsdt.internal.compiler.lookup.ExtraCompilerModifiers; import org.eclipse.wst.jsdt.internal.compiler.lookup.LookupEnvironment; +import org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding; import org.eclipse.wst.jsdt.internal.compiler.lookup.MethodVerifier; import org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding; import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding; @@ -192,40 +193,50 @@ class FunctionBinding implements IFunctionBinding { else return (JavaElement) declaringType.getFunction(getName(), parameters); } - else { - return null; - } - } else { + } + else { // case of method not in the created AST, or a binary method - org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding original = this.binding.original(); - String selector = original.isConstructor() ? declaringType.getElementName() : new String(original.selector); - boolean isBinary = declaringType.isBinary(); - ReferenceBinding enclosingType = original.declaringClass.enclosingType(); - boolean isInnerBinaryTypeConstructor = isBinary && original.isConstructor() && enclosingType != null; - TypeBinding[] parameters = original.parameters; - int length = parameters == null ? 0 : parameters.length; - int declaringIndex = isInnerBinaryTypeConstructor ? 1 : 0; - String[] parameterSignatures = new String[declaringIndex + length]; - if (isInnerBinaryTypeConstructor) - parameterSignatures[0] = new String(enclosingType.signature()).replace('/', '.'); - for (int i = 0; i < length; i++) { - parameterSignatures[declaringIndex + i] = new String(parameters[i].signature()).replace('/', '.'); - } - IFunction result = declaringType.getFunction(selector, parameterSignatures); - if (isBinary) - return (JavaElement) result; - IFunction[] methods = null; - try { - methods = declaringType.getFunctions(); - } catch (JavaScriptModelException e) { - // declaring type doesn't exist - return null; + MethodBinding original = this.binding.original(); + String selector = original.isConstructor() ? declaringType.getElementName() : (original.selector != null ? new String(original.selector) : null); + if (selector != null) { + boolean isBinary = declaringType!= null && declaringType.isBinary(); + ReferenceBinding enclosingType = original.declaringClass.enclosingType(); + boolean isInnerBinaryTypeConstructor = isBinary && original.isConstructor() && enclosingType != null; + TypeBinding[] parameters = original.parameters; + int length = parameters == null ? 0 : parameters.length; + int declaringIndex = isInnerBinaryTypeConstructor ? 1 : 0; + String[] parameterSignatures = new String[declaringIndex + length]; + if (isInnerBinaryTypeConstructor) + parameterSignatures[0] = new String(enclosingType.signature()).replace('/', '.'); + for (int i = 0; i < length; i++) { + parameterSignatures[declaringIndex + i] = new String(parameters[i].signature()).replace('/', '.'); + } + IFunction result = null; + if (declaringType != null) + result = declaringType.getFunction(selector, parameterSignatures); + else if (typeRoot != null) + result = typeRoot.getFunction(selector, parameterSignatures); + if (isBinary) + return (JavaElement) result; + IFunction[] methods = null; + try { + if (declaringType != null) + methods = declaringType.getFunctions(); + else if (typeRoot != null) + methods = typeRoot.getFunctions(); + } + catch (JavaScriptModelException e) { + // declaring type doesn't exist + return null; + } + IFunction[] candidates = Member.findMethods(result, methods); + if (candidates == null || candidates.length == 0) + return null; + return (JavaElement) candidates[0]; } - IFunction[] candidates = Member.findMethods(result, methods); - if (candidates == null || candidates.length == 0) - return null; - return (JavaElement) candidates[0]; } + + return null; } /** * @see IBinding#getKind() diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/IBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/IBinding.java index dfe1271e..141163d9 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/IBinding.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/IBinding.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/IExtendedModifier.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/IExtendedModifier.java index 504c9e13..fe870997 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/IExtendedModifier.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/IExtendedModifier.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2004, 2007 IBM Corporation and others. + * Copyright (c) 2004, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/IPackageBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/IPackageBinding.java index a11ed0e0..d6231350 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/IPackageBinding.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/IPackageBinding.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/IVariableBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/IVariableBinding.java index 8aacfc7b..2f6e76b3 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/IVariableBinding.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/IVariableBinding.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/IfStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/IfStatement.java index f5d84c9a..21ee68bb 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/IfStatement.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/IfStatement.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/InstanceofExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/InstanceofExpression.java index 3f90c240..08f91b80 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/InstanceofExpression.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/InstanceofExpression.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/JavaScriptUnitResolver.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/JavaScriptUnitResolver.java index 22ebd5eb..10f6e951 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/JavaScriptUnitResolver.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/JavaScriptUnitResolver.java @@ -33,8 +33,6 @@ import org.eclipse.wst.jsdt.internal.compiler.IProblemFactory; import org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.wst.jsdt.internal.compiler.env.AccessRestriction; -import org.eclipse.wst.jsdt.internal.compiler.env.IBinaryType; -import org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit; import org.eclipse.wst.jsdt.internal.compiler.env.INameEnvironment; import org.eclipse.wst.jsdt.internal.compiler.env.ISourceType; import org.eclipse.wst.jsdt.internal.compiler.impl.CompilerOptions; @@ -58,7 +56,6 @@ import org.eclipse.wst.jsdt.internal.core.SourceTypeElementInfo; import org.eclipse.wst.jsdt.internal.core.util.BindingKeyResolver; import org.eclipse.wst.jsdt.internal.core.util.CommentRecorderParser; import org.eclipse.wst.jsdt.internal.core.util.DOMFinder; -import org.eclipse.wst.jsdt.internal.oaametadata.LibraryAPIs; /** * @@ -146,53 +143,15 @@ class JavaScriptUnitResolver extends Compiler { this.hasCompilationAborted = false; this.monitor =monitor; } - - /** - *

Checks cancel state, runs parent operation, checks cancel state again.

- * - * @see org.eclipse.wst.jsdt.internal.compiler.Compiler#accept(org.eclipse.wst.jsdt.internal.compiler.env.IBinaryType, org.eclipse.wst.jsdt.internal.compiler.lookup.PackageBinding, org.eclipse.wst.jsdt.internal.compiler.env.AccessRestriction) - */ - public void accept(IBinaryType binaryType, PackageBinding packageBinding, AccessRestriction accessRestriction) { - this.checkCanceled(); - super.accept(binaryType, packageBinding, accessRestriction); - this.checkCanceled(); - } - - /** - *

Checks cancel state, runs parent operation, checks cancel state again.

- * - * @see org.eclipse.wst.jsdt.internal.compiler.Compiler#accept(org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit, org.eclipse.wst.jsdt.internal.compiler.env.AccessRestriction) - */ - public void accept(ICompilationUnit sourceUnit, AccessRestriction accessRestriction) { - this.checkCanceled(); - super.accept(sourceUnit, accessRestriction); - this.checkCanceled(); - } - - /** - *

Checks cancel state, runs parent operation, checks cancel state again.

- * - * @see org.eclipse.wst.jsdt.internal.compiler.Compiler#accept(org.eclipse.wst.jsdt.internal.oaametadata.LibraryAPIs) - */ - public void accept(LibraryAPIs libraryMetaData) { - this.checkCanceled(); - super.accept(libraryMetaData); - this.checkCanceled(); - } - /** - *

Checks cancel state, adds additional source types, checks cancel state again.

- * - * @see org.eclipse.wst.jsdt.internal.compiler.Compiler#accept(org.eclipse.wst.jsdt.internal.compiler.env.ISourceType[], org.eclipse.wst.jsdt.internal.compiler.lookup.PackageBinding, org.eclipse.wst.jsdt.internal.compiler.env.AccessRestriction) + /* + * Add additional source types */ public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding, AccessRestriction accessRestriction) { - this.checkCanceled(); // Need to reparse the entire source of the javaScript unit so as to get source positions // (case of processing a source that was not known by beginToCompile (e.g. when asking to createBinding)) SourceTypeElementInfo sourceType = (SourceTypeElementInfo) sourceTypes[0]; accept((org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit) sourceType.getHandle().getJavaScriptUnit(), accessRestriction); - - this.checkCanceled(); } /** @@ -711,8 +670,8 @@ class JavaScriptUnitResolver extends Compiler { final AbstractMethodDeclaration[] methods = type.methods; if (methods != null) { for (int i = 0, max = methods.length; i < max; i++){ - if (methods[i].binding != null && (methods[i].binding.modifiers & ExtraCompilerModifiers.AccUnresolved) != 0) { - methods[i].binding = null; + if (methods[i].hasBinding() && (methods[i].getBinding().modifiers & ExtraCompilerModifiers.AccUnresolved) != 0) { + methods[i].setBinding(null); } } } @@ -891,11 +850,7 @@ class JavaScriptUnitResolver extends Compiler { if (unit.scope != null) { // fault in fields & methods unit.scope.faultInTypes(); - if (unit.scope != null && verifyMethods) { - // http://dev.eclipse.org/bugs/show_bug.cgi?id=23117 - // verify inherited methods - unit.scope.verifyMethods(this.lookupEnvironment.methodVerifier()); - } + // type checking unit.resolve(); @@ -912,9 +867,6 @@ class JavaScriptUnitResolver extends Compiler { } catch (Error e) { this.handleInternalException(e, unit, null); throw e; // rethrow - } catch(OperationCanceledException e) { - this.reset(); - throw e; } catch (RuntimeException e) { this.handleInternalException(e, unit, null); throw e; // rethrow @@ -965,30 +917,11 @@ class JavaScriptUnitResolver extends Compiler { generateCode); } - /** - *

Reports the amount of work completed on this resolvers {@link IProgressMonitor} - * if it has one. The canceled state of monitor will also be checked.

- * - * @param work amount of work completed - * - * @see #checkCanceled() - */ private void worked(int work) { if (this.monitor != null) { - this.checkCanceled(); + if (this.monitor.isCanceled()) + throw new OperationCanceledException(); this.monitor.worked(work); } } - - /** - *

Checks if the {@link IProgressMonitor} for this resolver is canceled, - * if it is then an {@link OperationCanceledException} is thrown.

- * - * @throws OperationCanceledException - if this recievers monitor has been canceled - */ - private void checkCanceled() { - if(this.monitor != null && this.monitor.isCanceled()) { - throw new OperationCanceledException(); - } - } } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/LabeledStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/LabeledStatement.java index bf8df0f7..3bf948af 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/LabeledStatement.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/LabeledStatement.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/LineComment.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/LineComment.java index 4517bf57..5dffea04 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/LineComment.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/LineComment.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2004, 2007 IBM Corporation and others. + * Copyright (c) 2004, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ListExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ListExpression.java index fb667219..6f1d03de 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ListExpression.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ListExpression.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Modifier.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Modifier.java index 7ecb8d2d..b2d7cb68 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Modifier.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Modifier.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Name.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Name.java index 895b6f87..381c03cb 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Name.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/Name.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/NodeEventHandler.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/NodeEventHandler.java index 12a16db7..d7fd718a 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/NodeEventHandler.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/NodeEventHandler.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2004, 2007 IBM Corporation and others. + * Copyright (c) 2004, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/NullLiteral.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/NullLiteral.java index 9ed1a34a..41e7f6cc 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/NullLiteral.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/NullLiteral.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/NumberLiteral.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/NumberLiteral.java index 7c1c619f..5938ad6c 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/NumberLiteral.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/NumberLiteral.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ObjectLiteral.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ObjectLiteral.java index 8902ee10..5e874d69 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ObjectLiteral.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ObjectLiteral.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ObjectLiteralField.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ObjectLiteralField.java index 523abe2e..fd4408ff 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ObjectLiteralField.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ObjectLiteralField.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/PackageBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/PackageBinding.java index 204f89c1..b22bcb16 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/PackageBinding.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/PackageBinding.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ParenthesizedExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ParenthesizedExpression.java index 3fd3f65d..dcce8647 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ParenthesizedExpression.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ParenthesizedExpression.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/PostfixExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/PostfixExpression.java index 9af97a5d..b7e366c3 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/PostfixExpression.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/PostfixExpression.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/PrefixExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/PrefixExpression.java index b039fe46..a7f5dd14 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/PrefixExpression.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/PrefixExpression.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/PrimitiveType.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/PrimitiveType.java index 50c357b8..6ea45f14 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/PrimitiveType.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/PrimitiveType.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/QualifiedName.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/QualifiedName.java index 198bb3f4..10e95eb3 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/QualifiedName.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/QualifiedName.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/QualifiedType.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/QualifiedType.java index 65b558f9..c6dbe53e 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/QualifiedType.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/QualifiedType.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2003, 2007 IBM Corporation and others. + * Copyright (c) 2003, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/RecoveredVariableBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/RecoveredVariableBinding.java index cefea49e..30abdd67 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/RecoveredVariableBinding.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/RecoveredVariableBinding.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. + * Copyright (c) 2007, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/RegularExpressionLiteral.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/RegularExpressionLiteral.java index 50229503..064fd9d2 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/RegularExpressionLiteral.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/RegularExpressionLiteral.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ReturnStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ReturnStatement.java index c24da2c9..69442a1f 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ReturnStatement.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ReturnStatement.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SimpleType.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SimpleType.java index 52ba66f5..147bdfef 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SimpleType.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SimpleType.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SingleVariableDeclaration.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SingleVariableDeclaration.java index 3999e151..99e7eceb 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SingleVariableDeclaration.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SingleVariableDeclaration.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/StringLiteral.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/StringLiteral.java index d522075d..3e742047 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/StringLiteral.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/StringLiteral.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -223,7 +223,9 @@ public class StringLiteral extends Expression { public String getLiteralValue() { String s = getEscapedValue(); int len = s.length(); - if (len < 2 || s.charAt(0) != '\"' || s.charAt(len-1) != '\"' ) { + char zeroth = s.charAt(0); + char last = s.charAt(len - 1); + if (len < 2 || (zeroth != '\"' && zeroth != '\'') || (last != '\"' && last != '\'')) { throw new IllegalArgumentException(); } @@ -235,6 +237,7 @@ public class StringLiteral extends Expression { int tokenType = scanner.getNextToken(); switch(tokenType) { case TerminalTokens.TokenNameStringLiteral: + case TerminalTokens.TokenNameCharacterLiteral: return scanner.getCurrentStringLiteral(); default: throw new IllegalArgumentException(); diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SuperFieldAccess.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SuperFieldAccess.java index 4fab26f1..3a803672 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SuperFieldAccess.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SuperFieldAccess.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SwitchCase.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SwitchCase.java index ed758a93..2117d148 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SwitchCase.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SwitchCase.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SwitchStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SwitchStatement.java index c162410c..52f06e0c 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SwitchStatement.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/SwitchStatement.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/TagElement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/TagElement.java index 9eacf65c..7bc18304 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/TagElement.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/TagElement.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2004, 2008 IBM Corporation and others. + * Copyright (c) 2004, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ThisExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ThisExpression.java index 0d691e50..6ef64162 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ThisExpression.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ThisExpression.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ThrowStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ThrowStatement.java index 361d246f..719a4f3e 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ThrowStatement.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/ThrowStatement.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/TryStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/TryStatement.java index c37496a5..b3908171 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/TryStatement.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/TryStatement.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/TypeBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/TypeBinding.java index 4480c424..8dfb5453 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/TypeBinding.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/TypeBinding.java @@ -597,7 +597,7 @@ class TypeBinding implements ITypeBinding { } ReferenceBinding superclass = null; try { - superclass = ((ReferenceBinding)this.binding).superclass(); + superclass = ((ReferenceBinding)this.binding).getSuperBinding(); } catch (RuntimeException e) { /* in case a method cannot be resolvable due to missing jars on the includepath * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=57871 diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/TypeDeclarationStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/TypeDeclarationStatement.java index 670975d7..f4c5e21d 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/TypeDeclarationStatement.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/TypeDeclarationStatement.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/TypeLiteral.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/TypeLiteral.java index 1c51435e..3279ce7e 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/TypeLiteral.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/TypeLiteral.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/UndefinedLiteral.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/UndefinedLiteral.java index 4cffa4f1..a840d76c 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/UndefinedLiteral.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/UndefinedLiteral.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/VariableDeclaration.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/VariableDeclaration.java index 493d14ce..e7b3d935 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/VariableDeclaration.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/VariableDeclaration.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/VariableDeclarationExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/VariableDeclarationExpression.java index c45cec24..b32858bc 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/VariableDeclarationExpression.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/VariableDeclarationExpression.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/VariableDeclarationFragment.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/VariableDeclarationFragment.java index bd16a60c..6763a1e0 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/VariableDeclarationFragment.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/VariableDeclarationFragment.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/WhileStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/WhileStatement.java index cdbe4399..92c12704 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/WhileStatement.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/WhileStatement.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/WithStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/WithStatement.java index 18cc5533..5c063c32 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/WithStatement.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/WithStatement.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/rewrite/ListRewrite.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/rewrite/ListRewrite.java index 9cc4edfe..c9d48fa6 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/rewrite/ListRewrite.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/dom/rewrite/ListRewrite.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2004, 2007 IBM Corporation and others. + * Copyright (c) 2004, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/formatter/CodeFormatterApplication.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/formatter/CodeFormatterApplication.java index a17ce3a4..bdfea225 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/formatter/CodeFormatterApplication.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/formatter/CodeFormatterApplication.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2004 Ben Konrath + * Copyright (c) 2004, 2008 Ben Konrath * Copyright (c) 2006 Red Hat Incorporated * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/formatter/messages.properties b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/formatter/messages.properties index 8fab89e2..b4b78b29 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/formatter/messages.properties +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/formatter/messages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2006 Ben Konrath +# Copyright (c) 2006, 2011 Ben Konrath # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -9,6 +9,9 @@ # Ben Konrath - initial implementation # IBM Corporation - Code review and integration ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR + CommandLineStart=Starting format job ... CommandLineDone=Done. CommandLineConfigFile=Configuration Name: {0} diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/DefaultInferrenceProvider.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/DefaultInferrenceProvider.java index 5ff53306..7537c981 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/DefaultInferrenceProvider.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/DefaultInferrenceProvider.java @@ -24,14 +24,14 @@ public class DefaultInferrenceProvider implements InferrenceProvider { public static final String ID="org.eclipse.wst.jsdt.core.infer.DefaultInferrenceProvider"; public int applysTo(IInferenceFile scriptFile) { - char[] fileNameChars = scriptFile.getFileName(); - if (fileNameChars!=null) { - - String fileName = new String(fileNameChars); - if (fileName.indexOf("org.eclipse.wst.jsdt.core/libraries")>=0) { - return InferrenceProvider.ONLY_THIS; - } - } +// char[] fileNameChars = scriptFile.getFileName(); +// if (fileNameChars!=null) { +// +// String fileName = new String(fileNameChars); +// if (fileName.indexOf("org.eclipse.wst.jsdt.core/libraries")>=0) { +// return InferrenceProvider.ONLY_THIS; +// } +// } return InferrenceProvider.MAYBE_THIS; } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/IInferEngineExtension.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/IInferEngineExtension.java new file mode 100644 index 00000000..a2fc0482 --- /dev/null +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/IInferEngineExtension.java @@ -0,0 +1,21 @@ +/******************************************************************************* + * Copyright (c) 2013 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package org.eclipse.wst.jsdt.core.infer; + +import org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration; + +public interface IInferEngineExtension { + /** + * Set compilation unit for processing. + */ + void setCompilationUnit(CompilationUnitDeclaration parsedUnit, char[] contents); +} diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferEngine.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferEngine.java index 1d20231c..57d1fbd9 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferEngine.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferEngine.java @@ -1,2151 +1,3444 @@ -/******************************************************************************* - * Copyright (c) 2005, 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.jsdt.core.infer; - -import org.eclipse.wst.jsdt.core.ast.ASTVisitor; -import org.eclipse.wst.jsdt.core.ast.IASTNode; -import org.eclipse.wst.jsdt.core.ast.IAbstractFunctionDeclaration; -import org.eclipse.wst.jsdt.core.ast.IAbstractVariableDeclaration; -import org.eclipse.wst.jsdt.core.ast.IAllocationExpression; -import org.eclipse.wst.jsdt.core.ast.IArgument; -import org.eclipse.wst.jsdt.core.ast.IAssignment; -import org.eclipse.wst.jsdt.core.ast.IExpression; -import org.eclipse.wst.jsdt.core.ast.IFalseLiteral; -import org.eclipse.wst.jsdt.core.ast.IFieldReference; -import org.eclipse.wst.jsdt.core.ast.IFunctionCall; -import org.eclipse.wst.jsdt.core.ast.IFunctionDeclaration; -import org.eclipse.wst.jsdt.core.ast.IFunctionExpression; -import org.eclipse.wst.jsdt.core.ast.IJsDoc; -import org.eclipse.wst.jsdt.core.ast.ILocalDeclaration; -import org.eclipse.wst.jsdt.core.ast.INumberLiteral; -import org.eclipse.wst.jsdt.core.ast.IObjectLiteral; -import org.eclipse.wst.jsdt.core.ast.IObjectLiteralField; -import org.eclipse.wst.jsdt.core.ast.IProgramElement; -import org.eclipse.wst.jsdt.core.ast.IReturnStatement; -import org.eclipse.wst.jsdt.core.ast.IScriptFileDeclaration; -import org.eclipse.wst.jsdt.core.ast.ISingleNameReference; -import org.eclipse.wst.jsdt.core.ast.IStringLiteral; -import org.eclipse.wst.jsdt.core.ast.IThisReference; -import org.eclipse.wst.jsdt.core.ast.ITrueLiteral; -import org.eclipse.wst.jsdt.core.compiler.CharOperation; -import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode; -import org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration; -import org.eclipse.wst.jsdt.internal.compiler.ast.AllocationExpression; -import org.eclipse.wst.jsdt.internal.compiler.ast.Argument; -import org.eclipse.wst.jsdt.internal.compiler.ast.ArrayInitializer; -import org.eclipse.wst.jsdt.internal.compiler.ast.ArrayReference; -import org.eclipse.wst.jsdt.internal.compiler.ast.Assignment; -import org.eclipse.wst.jsdt.internal.compiler.ast.BinaryExpression; -import org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration; -import org.eclipse.wst.jsdt.internal.compiler.ast.Expression; -import org.eclipse.wst.jsdt.internal.compiler.ast.FieldReference; -import org.eclipse.wst.jsdt.internal.compiler.ast.FunctionExpression; -import org.eclipse.wst.jsdt.internal.compiler.ast.Javadoc; -import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocSingleNameReference; -import org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration; -import org.eclipse.wst.jsdt.internal.compiler.ast.MessageSend; -import org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration; -import org.eclipse.wst.jsdt.internal.compiler.ast.ObjectLiteral; -import org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds; -import org.eclipse.wst.jsdt.internal.compiler.ast.ProgramElement; -import org.eclipse.wst.jsdt.internal.compiler.ast.Reference; -import org.eclipse.wst.jsdt.internal.compiler.ast.SingleNameReference; -import org.eclipse.wst.jsdt.internal.compiler.ast.StringLiteral; -import org.eclipse.wst.jsdt.internal.compiler.ast.UnaryExpression; -import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeConstants; -import org.eclipse.wst.jsdt.internal.compiler.util.HashtableOfObject; -import org.eclipse.wst.jsdt.internal.compiler.util.Util; - -/** - * The default inference engine. - * - *

Clients may subclass this class but should expect some breakage by future releases.

- * - * Provisional API: This class/interface is part of an interim API that is still under development and expected to - * change significantly before reaching stability. It is being made available at this early stage to solicit feedback - * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken - * (repeatedly) as the API evolves. - */ -public class InferEngine extends ASTVisitor implements IInferEngine { - - InferOptions inferOptions; - CompilationUnitDeclaration compUnit; - Context [] contexts=new Context[100]; - int contextPtr=-1; - Context currentContext=new Context(); - protected int passNumber=1; - - boolean isTopLevelAnonymousFunction; - int anonymousCount=0; - - public InferrenceProvider inferenceProvider; - - public InferredType StringType=new InferredType(new char[]{'S','t','r','i','n','g'}); - public InferredType NumberType=new InferredType(new char[]{'N','u','m','b','e','r'}); - public InferredType BooleanType=new InferredType(new char[]{'B','o','o','l','e','a','n'}); - public InferredType FunctionType=new InferredType(InferredType.FUNCTION_NAME); - public InferredType ArrayType=new InferredType(InferredType.ARRAY_NAME); - public InferredType VoidType=new InferredType(new char[]{'v','o','i','d'}); - public InferredType ObjectType=new InferredType(InferredType.OBJECT_NAME); - public InferredType GlobalType=new InferredType(InferredType.GLOBAL_NAME); - - - public static HashtableOfObject WellKnownTypes=new HashtableOfObject(); - { - WellKnownTypes.put(InferredType.OBJECT_NAME,null); - WellKnownTypes.put(InferredType.ARRAY_NAME,null); - WellKnownTypes.put(new char[]{'S','t','r','i','n','g'},null); - WellKnownTypes.put(new char[]{'N','u','m','b','e','r'},null); - WellKnownTypes.put(new char[]{'B','o','o','l','e','a','n'},null); - WellKnownTypes.put(InferredType.FUNCTION_NAME,null); - WellKnownTypes.put(new char[]{'D','a','t','e'},null); - WellKnownTypes.put(new char[]{'M','a','t','h'},null); - WellKnownTypes.put(new char[]{'R','e','g','E','x','p'},null); - WellKnownTypes.put(new char[]{'E','r','r','o','r'},null); - } - - - - protected InferredType inferredGlobal=null; - - static final char[] CONSTRUCTOR_ID={'c','o','n','s','t','r','u','c','t','o','r'}; - - static class Context - { - InferredType currentType; - IFunctionDeclaration currentMethod; - - /** The current assignment.*/ - IAssignment currentAssignment; - - /** the current declaration */ - ILocalDeclaration currentLocalDeclaration; - boolean isJsDocClass; - - private HashtableOfObject definedMembers; - - /* - * Parent context to provide chaining when searching - * for members in scope. - */ - private Context parent = null; - - /* - * Root context - */ - Context(){} - - /* - * Nested context - */ - Context( Context parent ) - { - this.parent = parent; - - currentType = parent.currentType; - currentMethod = parent.currentMethod; - this.currentAssignment = parent.currentAssignment; - this.currentLocalDeclaration = parent.currentLocalDeclaration; - this.isJsDocClass=parent.isJsDocClass; - } - - public Object getMember( char [] key ){ - - Object value = null; - if( definedMembers != null ){ - value = definedMembers.get( key ); - } - - //chain lookup - if( value == null && parent != null ){ - value = parent.getMember( key ); - } - - return value; - } - - public void addMember( char [] key, Object member ){ - if(key == null) - return; - - if( definedMembers == null ){ - definedMembers = new HashtableOfObject(); - } - - definedMembers.put( key, member ); - } - - public void setCurrentType(InferredType type) - { - this.currentType=type; - Context parentContext=this.parent; - - while (parentContext!=null && parentContext.currentMethod==this.currentMethod) - { - parentContext.currentType=type; - parentContext=parentContext.parent; - } - } - - - } - - private static boolean REPORT_INFER_TIME = false; - - public InferEngine(InferOptions inferOptions) - { - this.inferOptions=inferOptions; - } - - public InferEngine() - { - this.inferOptions=new InferOptions(); - } - - - public void initialize() - { - this.contextPtr=-1; - this.currentContext=new Context(); - this.passNumber=1; - this.isTopLevelAnonymousFunction=false; - this.anonymousCount=0; - this.inferredGlobal=null; - } - - public void setCompilationUnit(CompilationUnitDeclaration scriptFileDeclaration) { - this.compUnit = scriptFileDeclaration; - buildDefinedMembers(scriptFileDeclaration.getStatements(),null); - } - - - public boolean visit(IFunctionCall functionCall) { - boolean visitChildren=handleFunctionCall(functionCall); - if (visitChildren) - { - if (this.contextPtr==-1 && functionCall.getReceiver() instanceof FunctionExpression) - this.isTopLevelAnonymousFunction=true; - } - return visitChildren; - } - - public boolean visit(ILocalDeclaration localDeclaration) { - //add as a member of the current context - currentContext.addMember( localDeclaration.getName(), localDeclaration ); - - //create a new context for the local declaration - pushContext(); - this.currentContext.currentLocalDeclaration = localDeclaration; - - if (localDeclaration.getJsDoc()!=null) - { - Javadoc javadoc = (Javadoc)localDeclaration.getJsDoc(); - createTypeIfNecessary(javadoc); - InferredAttribute attribute = null; - if (javadoc.memberOf!=null) - { - InferredType type = this.addType(javadoc.memberOf.getFullTypeName(),true); - int nameStart = localDeclaration.sourceStart(); - attribute = type.addAttribute(localDeclaration.getName(), localDeclaration, nameStart); - handleAttributeDeclaration(attribute, localDeclaration.getInitialization()); - if (localDeclaration.getInitialization()!=null) - attribute.initializationStart=localDeclaration.getInitialization().sourceStart(); - attribute.type=type; - } - - if (javadoc.returnType!=null) - { - InferredType type = this.addType(changePrimitiveToObject(javadoc.returnType.getFullTypeName())); - localDeclaration.setInferredType(type); - if (attribute!=null) - attribute.type=type; - } - } - - // visit the function in case it defines a type - if(localDeclaration.getInitialization() instanceof IFunctionExpression) { - boolean keepVisiting = handleFunctionExpressionLocalDeclaration(localDeclaration); - if(!keepVisiting) { - return false; - } - } - - if (localDeclaration.getInferredType()==null && localDeclaration.getInitialization()!=null) - { - if(localDeclaration.getInitialization() instanceof MessageSend) { - handleFunctionCall((IFunctionCall)localDeclaration.getInitialization(), (LocalDeclaration) localDeclaration); - } else { - localDeclaration.setInferredType(getTypeOf(localDeclaration.getInitialization())); - } - } - return true; - } - - /** - * @see org.eclipse.wst.jsdt.core.ast.ASTVisitor#endVisit(org.eclipse.wst.jsdt.core.ast.ILocalDeclaration) - */ - public void endVisit(ILocalDeclaration localDeclaration) { - popContext(); - } - - private void createTypeIfNecessary(Javadoc javadoc) { - if (javadoc.memberOf!=null) - { - char [][]namespace={}; - char[][] typeName = javadoc.memberOf.getTypeName(); - if (javadoc.namespace!=null) - { - namespace=javadoc.namespace.getTypeName(); - } - char [] name=CharOperation.concat( - CharOperation.concatWith(namespace, '.'), - CharOperation.concatWith(typeName, '.'), - '.'); - this.currentContext.currentType=addType(name); - if (javadoc.extendsType!=null) - { - char[] superName = CharOperation.concatWith(javadoc.extendsType.getTypeName(),'.'); - this.currentContext.currentType.superClass=addType(superName); - } - this.currentContext.isJsDocClass=true; - - } - - } - - public boolean visit(IAssignment assignment) { - pushContext(); - this.currentContext.currentAssignment = assignment; - IExpression assignmentExpression=assignment.getExpression(); - if (handlePotentialType(assignment)) - { - - } - else if (assignmentExpression instanceof FunctionExpression) - { - boolean keepVisiting= handleFunctionExpressionAssignment(assignment); - if (!keepVisiting) - return false; - } - else if (assignmentExpression instanceof SingleNameReference && this.currentContext.currentType !=null && - isThis(assignment.getLeftHandSide())) - { - ISingleNameReference snr=(ISingleNameReference)assignmentExpression; - Object object = this.currentContext.getMember( snr.getToken() ); - - - IFieldReference fieldReference=(IFieldReference)assignment.getLeftHandSide(); - char [] memberName = fieldReference.getToken(); - InferredMember member = null; - - int nameStart = fieldReference.sourceEnd() - memberName.length + 1; - - /* - * this.foo = bar //bar is a function - */ - if( object instanceof MethodDeclaration ){ - - MethodDeclaration method=(MethodDeclaration)object; - member = this.currentContext.currentType.addMethod(memberName, method, nameStart); - - } - /* - * this.foo = bar //assume that bar is not a function and create a new attribute in the current type - */ - else { - member = this.currentContext.currentType.addAttribute(memberName, assignment, nameStart); - handleAttributeDeclaration((InferredAttribute) member, assignment.getExpression()); - if (((InferredAttribute) member).type == null) - ((InferredAttribute)member).type = getTypeOf( assignmentExpression ); - } - - //setting location - if( member != null ){ - member.isStatic = false; //this is a not static member because it is being set on the this - } - } - - /* - * foo = {}; - */ - else if ( assignmentExpression instanceof IObjectLiteral && assignment.getLeftHandSide() instanceof ISingleNameReference ){ - IAbstractVariableDeclaration varDecl = getVariable( assignment.getLeftHandSide() ); - if(varDecl == null) { - IAssignment existing = getAssignment(assignment.getLeftHandSide()); - if(existing == null) { - //add as a member of the parent context (the current context is for the assignment) - currentContext.parent.addMember( getName(assignment.getLeftHandSide()), assignment ); - } - } - if( varDecl != null ){ - InferredType type = varDecl.getInferredType(); - - if( type == null ){ - //create an anonymous type based on the ObjectLiteral - type = getTypeOf( assignmentExpression ); - - varDecl.setInferredType(type); - - return true; - } - else - return false; // - } else { - IAssignment assignmentDecl = getAssignment(assignment.getLeftHandSide()); - if( assignmentDecl != null ){ - InferredType type = assignmentDecl.getInferredType(); - - if( type == null ){ - //create an anonymous type based on the ObjectLiteral - type = getTypeOf( assignmentExpression ); - - assignmentDecl.setInferredType(type); - - return true; - } - else - return false; // - } - } - } - /* - * foo.bar = {}; - * - */ - else if ( assignmentExpression instanceof IObjectLiteral && assignment.getLeftHandSide() instanceof FieldReference ){ - FieldReference fRef = (FieldReference)assignment.getLeftHandSide(); - - boolean isKnownName=fRef.receiver.isThis() && isKnownType(fRef.getToken()) && - (this.inferredGlobal!=null && this.inferredGlobal==this.currentContext.currentType); - - if (isKnownName || (this.inferOptions.useAssignments && passNumber == 2 )) - { - - - InferredType receiverType = getInferredType( fRef.receiver ); - - if (receiverType==null && this.passNumber==2) - receiverType=getInferredType2(fRef.receiver ); - - if( receiverType != null ){ - //check if there is an attribute already created - - InferredAttribute attr = receiverType.findAttribute( fRef.getToken() ); - - //ignore if the attribute exists and has a type - if( !(attr != null && attr.type != null) ){ - - int nameStart = (int)(fRef.nameSourcePosition>>>32); - - attr = receiverType.addAttribute(fRef.getToken(), assignment, nameStart); - handleAttributeDeclaration(attr, assignment.getExpression()); - attr.type = getTypeOf( assignmentExpression ); - - if (isKnownName && attr.type.isAnonymous) - { - InferredType existingType = compUnit.findInferredType( fRef.getToken() ) ; - if (existingType!=null) - attr.type=existingType; - else - { - compUnit.inferredTypesHash.removeKey(attr.type.name); - attr.type.name=fRef.getToken(); - compUnit.inferredTypesHash.put(attr.type.name, attr.type); - } - } - - - /* - * determine if static - * - * check if the receiver is a type - */ - char [] possibleTypeName = constructTypeName( fRef.receiver ); - - if( receiverType.allStatic || - (possibleTypeName != null && compUnit.findInferredType( possibleTypeName ) != null )) - attr.isStatic = true; - else - attr.isStatic = false; - - return false; //done with this - } - - } - } - } - else if ( assignmentExpression instanceof AllocationExpression && - ((AllocationExpression)assignmentExpression).member instanceof FunctionExpression){ - handleFunctionExpressionAssignment((Assignment)assignment); - } - else if ( assignmentExpression instanceof Assignment && - ((Assignment)assignmentExpression).expression instanceof FunctionExpression){ - handleFunctionExpressionAssignment((Assignment)assignment); - } - else - { - /* - * foo.bar = ? //? is not {} and not a function - */ - if (this.inferOptions.useAssignments) - { - if( assignment.getLeftHandSide() instanceof FieldReference || assignment.getLeftHandSide() instanceof ArrayReference){ - - Reference ref = (Reference) assignment.getLeftHandSide(); - Expression receiver = null; - char[] attName = null; - int nameStart = 0; - if(ref instanceof FieldReference) { - receiver = ((FieldReference)ref).receiver; - attName = ((FieldReference)ref).token; - nameStart=(int)(((FieldReference)ref).nameSourcePosition>>>32); - } else if(ref instanceof ArrayReference) { - if(((ArrayReference)ref).position instanceof StringLiteral) { - receiver = ((ArrayReference)ref).receiver; - attName = ((StringLiteral)((ArrayReference)ref).position).source(); - nameStart = ((StringLiteral)((ArrayReference)ref).position).sourceStart + 1; - } - } - - InferredType receiverType = getInferredType( receiver ); - if (receiverType==null) - { - IFunctionDeclaration function = getDefinedFunction(receiver); - if (function!=null) - { - char [] typeName = constructTypeName(receiver); - if (typeName!=null) - receiverType=addType(typeName); - } - } - if (receiverType==null && this.passNumber==2) - receiverType=getInferredType2(receiver ); - - if( receiverType != null && attName != null){ - //check if there is an attribute already created - - InferredMethod method=null; - InferredAttribute attr = receiverType.findAttribute( attName ); - if (attr==null) - method = receiverType.findMethod(attName, null); - - //ignore if the attribute exists and has a type - if( (method==null && attr==null) || (method==null && attr != null && attr.type == null) ){ - - -// attr.type = - IFunctionDeclaration definedFunction=null; - InferredType exprType = getTypeOf( assignmentExpression ); - if (exprType==null) - definedFunction = getDefinedFunction(assignmentExpression ); - - if (definedFunction!=null) - { - method = receiverType.addMethod(attName, definedFunction, nameStart); - method.isStatic=receiverType.allStatic; - } - else - { - int nameStart_ = nameStart; - - attr = receiverType.addAttribute(attName, assignment, nameStart_); - handleAttributeDeclaration(attr, assignmentExpression); - attr.type=exprType; - /* - * determine if static - * - * check if the receiver is a type - */ - char [] possibleTypeName = constructTypeName( receiver ); - - if( receiverType.allStatic|| - (possibleTypeName != null && compUnit.findInferredType( possibleTypeName ) != null )) - attr.isStatic = true; - else - attr.isStatic = false; - } - return false; //done with this - } - - - } - } - } - } - return true; // do nothing by default, keep traversing - } - - protected InferredType getInferredType2(IExpression fieldReceiver) - { - InferredType receiverType=null; - IAbstractVariableDeclaration var=getVariable(fieldReceiver); - if (var!=null) - { - receiverType=createAnonymousType(var); - } - else - { - if (this.inferredGlobal!=null && fieldReceiver instanceof ISingleNameReference) - { - char []name=((ISingleNameReference)fieldReceiver).getToken(); - InferredAttribute attr=this.inferredGlobal.findAttribute(name); - if (attr!=null) - receiverType=attr.type; - } - - } - return receiverType; - } - - private InferredType createAnonymousType(IAbstractVariableDeclaration var) { - - InferredType currentType = var.getInferredType(); - - if (currentType==null || !currentType.isAnonymous) - { - InferredType type=createAnonymousType(var.getName(), currentType); - var.setInferredType(type); - } - return var.getInferredType(); - } - - private InferredType createAnonymousType(IAssignment assignment) { - - InferredType currentType = assignment.getInferredType(); - - if (currentType==null || !currentType.isAnonymous) - { - InferredType type=createAnonymousType(getName(assignment.getLeftHandSide()), currentType); - assignment.setInferredType(type); - } - return assignment.getInferredType(); - } - - protected InferredType createAnonymousType(char[] possibleTypeName, InferredType currentType) { - char []name; - if (this.isKnownType(possibleTypeName)) - { - name=possibleTypeName; - } - else - { - char[] cs = String.valueOf(this.anonymousCount++).toCharArray(); - name = CharOperation.concat(ANONYMOUS_PREFIX,possibleTypeName,cs); - } - InferredType type = addType(name,true); - type.isAnonymous=true; - if (currentType!=null) - type.superClass=currentType; - return type; - } - /* - * Creates an anonymous type based in the location in the document. This information is used - * to avoid creating duplicates because of the 2-pass nature of this engine. - */ - private InferredType createAnonymousType( IObjectLiteral objLit ) { - - if (objLit.getInferredType()!=null) - return objLit.getInferredType(); - char []name = createAnonymousTypeName(objLit); - - InferredType anonType = addType(name,true); - anonType.isAnonymous=true; - anonType.isObjectLiteral=true; - anonType.superClass = ObjectType; - - anonType.sourceStart = objLit.sourceStart(); - anonType.sourceEnd = objLit.sourceEnd(); - - populateType( anonType, objLit , false); - - return anonType; - } - - - /** - *

Creates an anonymous type name for the given {@link IASTNode}

- * - * @param node create the anonymous type name off the location of this node - * @return an anonymous type name based off the given nodes location - */ - protected static char[] createAnonymousTypeName(IASTNode node) { - char [] loc = (String.valueOf( node.sourceStart() ) + '_' + String.valueOf( node.sourceEnd() )).toCharArray(); - return CharOperation.concat( ANONYMOUS_PREFIX, ANONYMOUS_CLASS_ID, loc ); - } - - /** - * handle the inferrencing for an assigment whose right hand side is a function expression - * @param the assignment AST node - * @return true if handled - */ - protected boolean handleFunctionExpressionAssignment(IAssignment assignment) - { - IFunctionExpression functionExpression=null; - if (assignment.getExpression() instanceof IFunctionExpression) - functionExpression=(IFunctionExpression)assignment.getExpression(); - else if (assignment.getExpression() instanceof IAllocationExpression) - functionExpression=(IFunctionExpression)((IAllocationExpression)assignment.getExpression()).getMember(); - else if (assignment.getExpression() instanceof IAssignment) - functionExpression=(FunctionExpression)((IAssignment)assignment.getExpression()).getExpression(); - MethodDeclaration methodDeclaration = functionExpression.getMethodDeclaration(); - - char [] possibleTypeName = constructTypeName( assignment.getLeftHandSide() ); - - InferredType type = null; - if( possibleTypeName != null ) - { - type = compUnit.findInferredType( possibleTypeName ); - if (type==null && isPossibleClassName(possibleTypeName)) - { - type=addType(possibleTypeName,true); - } - if (type==null && methodDeclaration.getJsDoc()!=null && ((Javadoc)methodDeclaration.getJsDoc()).isConstructor) - { - type=addType(possibleTypeName,true); - handleJSDocConstructor(type, methodDeclaration, assignment.sourceStart()); - } - } - - if (type!=null) // isConstructor - { - if (this.inferOptions.useInitMethod) - { - this.currentContext.currentType=type; - type.isDefinition=true; - int nameStart = assignment.getLeftHandSide().sourceStart(); - type.addConstructorMethod(type.name, methodDeclaration, nameStart); - type.updatePositions(nameStart, assignment.getExpression().sourceEnd()); - } - - } - else // could be method - { - if (assignment.getLeftHandSide() instanceof FieldReference || assignment.getLeftHandSide() instanceof ArrayReference) - { - Reference ref = (Reference) assignment.getLeftHandSide(); - Expression receiver = null; - char[] methodName = null; - int nameStart = 0; - if(ref instanceof FieldReference) { - receiver = ((FieldReference)ref).receiver; - methodName = ((FieldReference)ref).token; - nameStart=(int)(((FieldReference)ref).nameSourcePosition>>>32); - } else if(ref instanceof ArrayReference) { - if(((ArrayReference)ref).position instanceof StringLiteral) { - receiver = ((ArrayReference)ref).receiver; - methodName = ((StringLiteral)((ArrayReference)ref).position).source(); - nameStart = ((StringLiteral)((ArrayReference)ref).position).sourceStart + 1; - } - } - - InferredType receiverType = getInferredType( receiver ); - - if( receiverType != null && methodName != null){ - - //check if there is a member method already created - InferredMethod method = receiverType.findMethod( methodName, methodDeclaration ); - - if( method == null ){ - //create member method if it does not exist - - method = receiverType.addMethod(methodName, methodDeclaration, nameStart); - receiverType.updatePositions(assignment.sourceStart(), assignment.sourceEnd()); // @GINO: not sure if necessary - receiverType.isDefinition=true; - - /* - * determine if static - * - * check if the receiver is a type - */ - char [] possibleInTypeName = constructTypeName( receiver ); - - if( receiverType.allStatic || - (possibleInTypeName != null && compUnit.findInferredType( possibleInTypeName ) != null) ) - method.isStatic = true; - else - method.isStatic = false; - - return true; //keep visiting to get return type - } - else - return false; //no need to visit again - - } - else if (this.passNumber==2 && methodName != null) // create anonymous class - { - receiverType = getInferredType2(receiver); - if (receiverType!=null) - { - InferredMethod method = receiverType.addMethod(methodName, methodDeclaration, nameStart); - method.isStatic=receiverType.isAnonymous; - receiverType.updatePositions(assignment.sourceStart(), assignment.sourceEnd()); - } - } - } - else if (assignment.getLeftHandSide() instanceof SingleNameReference) - { - if(methodDeclaration.selector == null) { - methodDeclaration.potentialName = ((SingleNameReference)assignment.getLeftHandSide()).token; - } - } - } - return true; - } - - /** - *

Handle a local declaration who's right hand side is a function.

- *

Use case:

foo.bar.Test = function() { this.num = 42; }
- * - * @param localDeclaration {@link ILocalDeclaration} to attempt to infer a type from - * @return true if keep visiting, false otherwise. - */ - private boolean handleFunctionExpressionLocalDeclaration(ILocalDeclaration localDeclaration) { - boolean keepVisiting = true; - IFunctionExpression functionExpression=null; - IExpression expression = localDeclaration.getInitialization(); - if (expression instanceof IFunctionExpression) { - functionExpression=(IFunctionExpression)expression; - } else if (expression instanceof IAllocationExpression) { - functionExpression=(IFunctionExpression)((IAllocationExpression)expression).getMember(); - } else if (expression instanceof IAssignment) { - functionExpression=(FunctionExpression)((IAssignment)expression).getExpression(); - } - - MethodDeclaration methodDeclaration = functionExpression.getMethodDeclaration(); - char [] possibleTypeName = localDeclaration.getName(); - - InferredType type = null; - if( possibleTypeName != null ) { - type = compUnit.findInferredType( possibleTypeName ); - if (type == null && isPossibleClassName(possibleTypeName)) { - type = addType(possibleTypeName,true); - } - if (type == null && methodDeclaration.getJsDoc()!= null && - ((Javadoc)methodDeclaration.getJsDoc()).isConstructor) { - - type = addType(possibleTypeName,true); - handleJSDocConstructor(type, methodDeclaration, localDeclaration.sourceStart()); - } - } - - if (type!=null) { // isConstructor - if (this.inferOptions.useInitMethod) { - this.currentContext.currentType=type; - type.isDefinition=true; - int nameStart = localDeclaration.sourceStart(); - type.addConstructorMethod(type.name, methodDeclaration, nameStart); - type.updatePositions(nameStart, localDeclaration.getInitialization().sourceEnd()); - } - - keepVisiting = false; - } - return keepVisiting; - } - - /** - * @param assignment - * @return whether a type was not created for this assignment - */ - protected boolean handlePotentialType(IAssignment assignment) { - - IExpression lhs = assignment.getLeftHandSide(); - if (lhs instanceof FieldReference) { - FieldReference fieldReference = (FieldReference) lhs; - - /* - * foo.prototype = ? - */ - if (fieldReference.isPrototype()) - { - /* - * When encountering a prototype, we are going to assume that the - * receiver is a type. - * - * If the type had not been inferred, it will be added at this point - */ - InferredType newType = null; - char [] possibleTypeName = constructTypeName( fieldReference.getReceiver() ); - if( possibleTypeName != null ) - newType = compUnit.findInferredType( possibleTypeName ); - else - return true; //no type created - - - //create the new type if not found - if( newType == null ){ - newType = addType( possibleTypeName ,true); - } - newType.isDefinition=true; - -// char[] typeName = getTypeName(fieldReference.receiver); -// Object object = currentContext.definedMembers.get(typeName); -// -// if (object instanceof Argument) -// return false; - - newType.updatePositions(assignment.sourceStart(), assignment.sourceEnd()); - - /* - * foo.prototype = new ... - */ - if (assignment.getExpression() instanceof IAllocationExpression) - { - //setting the super type - IAllocationExpression allocationExpression =(IAllocationExpression)assignment.getExpression(); - - InferredType superType = null; - char [] possibleSuperTypeName = constructTypeName( allocationExpression.getMember() ); - if( possibleSuperTypeName != null ){ - superType = compUnit.findInferredType( possibleSuperTypeName ); - - if( superType == null ) - superType = addType( possibleSuperTypeName ); - - //check if it is set already because it might be set by jsdocs - if( newType.superClass == null ) - newType.superClass = superType; - } - - return true; - } - /* - * foo.prototype = {...} - */ - else if( assignment.getExpression() instanceof IObjectLiteral ){ - //rather than creating an anonymous type, is better just to set the members directly - //on newType - populateType( newType, (IObjectLiteral)assignment.getExpression(),false ); - - //check if it is set already because it might be set by jsdocs - if( newType.superClass == null ) - newType.superClass = ObjectType; - - return true; - } - } - /* - * foo.prototype.bar = ? - */ - else if ( fieldReference.receiver.isPrototype() ) - { - - FieldReference prototype = (FieldReference) fieldReference.receiver; - - InferredType newType = null; - char[] possibleTypeName = constructTypeName( prototype.receiver ); - if( possibleTypeName != null ) - newType = compUnit.findInferredType( possibleTypeName ); - else - return true; //no type created - - //create the new type if not found - if( newType == null ){ - newType = addType( possibleTypeName ); - } - newType.isDefinition = true; - -// char[] typeName = getTypeName(prototype.receiver); -// Object receiverDef = currentContext.definedMembers.get(typeName); -// if (receiverDef instanceof Argument) -// return false; -// InferredType newType = addType(typeName); -// newType.isDefinition=true; - - newType.updatePositions(assignment.sourceStart(), assignment.sourceEnd()); - - //prevent Object literal based anonymous types from being created more than once - if( passNumber == 1 && assignment.getExpression() instanceof IObjectLiteral ){ - return false; - } - - char[] memberName = fieldReference.token; - int nameStart= (int)(fieldReference.nameSourcePosition >>> 32); - - InferredType typeOf = (assignment.getJsDoc() != null && assignment.getJsDoc() instanceof Javadoc && ((Javadoc) assignment.getJsDoc()).returnType != null) ? this.addType(changePrimitiveToObject(((Javadoc) assignment.getJsDoc()).returnType.getFullTypeName())) : getTypeOf(assignment.getExpression()); - IFunctionDeclaration methodDecl=null; - - if (typeOf==null || typeOf==FunctionType) - methodDecl=getDefinedFunction(assignment.getExpression()); - - if (methodDecl!=null) - { - InferredMember method = newType.addMethod(memberName, methodDecl, nameStart); - } - // http://bugs.eclipse.org/269053 - constructor property not supported in JSDT - else /*if (!CharOperation.equals(CONSTRUCTOR_ID, memberName))*/ - { - InferredAttribute attribute = newType.addAttribute(memberName, assignment, nameStart); - handleAttributeDeclaration(attribute, assignment.getExpression()); - attribute.initializationStart=assignment.getExpression().sourceStart(); - if (attribute.type==null) - attribute.type=typeOf; - } - return true; - } else if(fieldReference.receiver instanceof IThisReference) { - InferredType newType = null; - - IFunctionDeclaration parentMethod = this.currentContext.currentMethod; - IAssignment parentAssignment; - ILocalDeclaration parentLocalDeclaration; - char[] newTypeName = null; - /* if there is a current assignment and LHS is a function and that function - * is the current method then use the RHS as the type name - * else if there is a current local declaration and the LHS is a function and - * that function is the current method then use the RHS as the type name - * else if the parent method has a name use that as the type name - */ - if(this.currentContext.parent != null && - (parentAssignment = this.currentContext.parent.currentAssignment) != null && - parentAssignment.getExpression() instanceof IFunctionExpression && - ((IFunctionExpression)parentAssignment.getExpression()).getMethodDeclaration() == parentMethod) { - - newTypeName = Util.getTypeName(parentAssignment.getLeftHandSide()); - } else if(this.currentContext.parent != null && - (parentLocalDeclaration = this.currentContext.parent.currentLocalDeclaration) != null && - parentLocalDeclaration.getInitialization() instanceof IFunctionExpression && - ((IFunctionExpression)parentLocalDeclaration.getInitialization()).getMethodDeclaration() == parentMethod) { - - newTypeName = parentLocalDeclaration.getName(); - - }else if( parentMethod != null && parentMethod.getName() != null ) { - newTypeName = parentMethod.getName(); - } - - //if calculated new type name, use it to create a new type - if(newTypeName != null) { - newType = compUnit.findInferredType(newTypeName); - //create the new type if not found - if(newType == null) { - newType = addType(newTypeName); - } - } else { - return false; //no type to create - } - - newType.isDefinition = true; - - newType.updatePositions(assignment.sourceStart(), assignment.sourceEnd()); - - //prevent Object literal based anonymous types from being created more than once - if( passNumber == 1 && assignment.getExpression() instanceof IObjectLiteral ){ - return false; - } - - char[] memberName = fieldReference.token; - int nameStart= (int)(fieldReference.nameSourcePosition >>> 32); - - InferredType typeOf = getTypeOf(assignment.getExpression()); - IFunctionDeclaration methodDecl=null; - - if (typeOf==null || typeOf==FunctionType) - methodDecl=getDefinedFunction(assignment.getExpression()); - - if (methodDecl!=null) - { - InferredMember method = newType.addMethod(memberName, methodDecl, nameStart); - if (methodDecl.getInferredType() == null && assignment.getJsDoc() != null && ((Javadoc) assignment.getJsDoc()).returnType != null) { - if (((Javadoc) assignment.getJsDoc()).returnType.getFullTypeName() != null) - methodDecl.setInferredType(addType(((Javadoc) assignment.getJsDoc()).returnType.getFullTypeName())); - } - } - // http://bugs.eclipse.org/269053 - constructor property not supported in JSDT - else /*if (!CharOperation.equals(CONSTRUCTOR_ID, memberName))*/ - { - InferredAttribute attribute = newType.addAttribute(memberName, assignment, nameStart); - if (attribute.type == null && assignment.getJsDoc() != null && ((Javadoc) assignment.getJsDoc()).returnType != null) { - if (((Javadoc) assignment.getJsDoc()).returnType.getFullTypeName() != null) - attribute.type = addType(((Javadoc) assignment.getJsDoc()).returnType.getFullTypeName()); - } - handleAttributeDeclaration(attribute, assignment.getExpression()); - attribute.initializationStart=assignment.getExpression().sourceStart(); - if (attribute.type==null) - attribute.type=typeOf; - } - return true; - } - } - return false; - } - - /** - * Get the function referenced by the expression - * - * @param expression AST node - * @return the function or null - */ - protected IFunctionDeclaration getDefinedFunction(IExpression expression) - { - if (expression instanceof SingleNameReference) - { - Object object = this.currentContext.getMember( ((SingleNameReference)expression).token ); - if (object instanceof AbstractMethodDeclaration) - return (MethodDeclaration)object; - } else if (expression instanceof FunctionExpression) - return ((FunctionExpression)expression).methodDeclaration; - else if (expression instanceof FieldReference) - { - FieldReference fieldReference=(FieldReference)expression; - InferredType receiverType = getInferredType( fieldReference.receiver ); - if (receiverType==null && passNumber==2) - receiverType=getInferredType2( fieldReference.receiver ); - if (receiverType!=null) - { - InferredMethod method = receiverType.findMethod(fieldReference.token, null); - if (method!=null) - return method.getFunctionDeclaration(); - } - - } - - return null; - - } - - protected InferredType getTypeOf(IExpression expression) { - if (expression instanceof IStringLiteral) { - return StringType; - } - else if (expression instanceof INumberLiteral) { - return NumberType; - } - else if (expression instanceof IAllocationExpression) - { - IAllocationExpression allocationExpression=(IAllocationExpression)expression; - - InferredType type = null; - char [] possibleTypeName = constructTypeName( allocationExpression.getMember() ); - if( possibleTypeName != null ){ - type = compUnit.findInferredType( possibleTypeName ); - - if( type == null ) - type = addType( possibleTypeName ); - - return type; - } - } - else if (expression instanceof ISingleNameReference) - { - IAbstractVariableDeclaration varDecl = getVariable( expression ); - if( varDecl != null ) - return varDecl.getInferredType(); - - if (this.inferredGlobal!=null) - { - InferredAttribute attribute = this.inferredGlobal.findAttribute(((ISingleNameReference)expression).getToken() ); - if (attribute!=null) - return attribute.type; - } - - } - else if (expression instanceof FieldReference) - { - FieldReference fieldReference=(FieldReference)expression; - if (fieldReference.receiver.isThis() && currentContext.currentType!=null) - { - InferredAttribute attribute = currentContext.currentType.findAttribute(fieldReference.getToken()); - if (attribute!=null) - return attribute.type; - } - } - else if (expression instanceof ArrayInitializer) - { - ArrayInitializer arrayInitializer = (ArrayInitializer)expression; - boolean typeSet=false; - InferredType memberType=null; - if (arrayInitializer.expressions!=null) - for (int i = 0; i < arrayInitializer.expressions.length; i++) { - InferredType thisType = getTypeOf(arrayInitializer.expressions[i]); - if (thisType!=null) - { - if (!thisType.equals(memberType)) - if (!typeSet) - memberType=thisType; - else - memberType=null; - typeSet=true; - - } - } - if (memberType!=null) - { - InferredType type = new InferredType(InferredType.ARRAY_NAME); - type.referenceClass=memberType; - return type; - } - else - return ArrayType; - } else if (expression instanceof ITrueLiteral || expression instanceof IFalseLiteral) { - return BooleanType; - } - else if ( expression instanceof IObjectLiteral ){ - - //create an annonymous type based on the ObjectLiteral - InferredType type = createAnonymousType( (IObjectLiteral)expression); - - //set the start and end - type.sourceStart = expression.sourceStart(); - type.sourceEnd = expression.sourceEnd(); - - return type; - - - } else if ( expression instanceof IThisReference ){ - return this.currentContext.currentType; - } - else if (expression instanceof Assignment) - return getTypeOf(((Assignment)expression).getExpression()); - else if (expression instanceof FunctionExpression) - return FunctionType; - else if(expression instanceof UnaryExpression) { - return getTypeOf(((UnaryExpression)expression).expression); - } else if(expression instanceof BinaryExpression) { - BinaryExpression bExpression = (BinaryExpression) expression; - int operator = (bExpression.bits & ASTNode.OperatorMASK) >> ASTNode.OperatorSHIFT; - switch(operator) { - case OperatorIds.MULTIPLY : - case OperatorIds.DIVIDE : - case OperatorIds.REMAINDER : - case OperatorIds.MINUS: - case OperatorIds.LEFT_SHIFT: - case OperatorIds.RIGHT_SHIFT: - return NumberType; - case OperatorIds.PLUS: - InferredType leftType = getTypeOf(bExpression.left); - InferredType rightType = getTypeOf(bExpression.right); - if(leftType != null && leftType.equals(StringType)) - return StringType; - if(rightType != null && rightType.equals(StringType)) - return StringType; - if(leftType == null || rightType == null) - return null; - if(leftType.equals(StringType) || rightType.equals(StringType)) { - return StringType; - } else if(leftType.equals(NumberType) && rightType.equals(NumberType)) { - return NumberType; - } - return null; - case OperatorIds.EQUAL_EQUAL: - case OperatorIds.EQUAL_EQUAL_EQUAL: - case OperatorIds.NOT_EQUAL: - case OperatorIds.NOT_EQUAL_EQUAL: - case OperatorIds.GREATER: - case OperatorIds.GREATER_EQUAL: - case OperatorIds.LESS: - case OperatorIds.LESS_EQUAL: - case OperatorIds.INSTANCEOF: - case OperatorIds.IN: - case OperatorIds.AND_AND: - case OperatorIds.OR_OR: - return BooleanType; - default: - return null; - } - } - - return null; - } - - protected void populateType(InferredType type, IObjectLiteral objLit, boolean isStatic) { - if (objLit.getInferredType()==null) { - objLit.setInferredType(type); - if (objLit.getFields() != null) { - for (int i = 0; i < objLit.getFields().length; i++) { - IObjectLiteralField field = objLit.getFields()[i]; - - char[] name = null; - int nameStart = -1; - - if (field.getFieldName() instanceof SingleNameReference) { - SingleNameReference singleNameReference = (SingleNameReference) field.getFieldName(); - name = singleNameReference.token; - nameStart = singleNameReference.sourceStart; - } else if (field.getFieldName() instanceof IStringLiteral) { - IStringLiteral stringLiteral = (IStringLiteral) field.getFieldName(); - name = stringLiteral.source(); - nameStart = stringLiteral.sourceStart(); - } else - continue; //not supporting this case right now - - Javadoc javaDoc = (Javadoc)field.getJsDoc(); - InferredType returnType=null; - if (javaDoc!=null) - { - if (javaDoc.memberOf!=null) - { - char[] typeName = javaDoc.memberOf.getFullTypeName(); - convertAnonymousTypeToNamed(type,typeName); - type.isDefinition=true; - } - else if (this.currentContext.isJsDocClass && javaDoc.property!=null) - { - if (type.isAnonymous ) - { - InferredType previousType = this.currentContext.currentType; - if (previousType!=null) - { - copyAnonymousTypeToNamed(type,previousType); - objLit.setInferredType(type = this.currentContext.currentType = previousType); - } - - } - } - if (javaDoc.returnType!=null) - { - returnType=this.addType(changePrimitiveToObject(javaDoc.returnType.getFullTypeName())); - } - } - - //need to build the members of the annonymous inferred type - if (field.getInitializer() instanceof IFunctionExpression) { - IFunctionExpression functionExpression = (IFunctionExpression) field.getInitializer(); - InferredMember method = type.addMethod(name, - functionExpression.getMethodDeclaration(), nameStart); - method.isStatic=isStatic; - if (javaDoc!=null) - { - functionExpression.getMethodDeclaration().modifiers=javaDoc.modifiers; - } - handleFunctionDeclarationArguments(functionExpression.getMethodDeclaration(),javaDoc); - if (returnType!=null && functionExpression.getMethodDeclaration().getInferredType() == null) - { - functionExpression.getMethodDeclaration().setInferredType(returnType); - } - - - } else //attribute - { - InferredAttribute attribute = type.findAttribute(name); - if (attribute == null) { - attribute = type.addAttribute(name, field.getInitializer(), nameStart); - handleAttributeDeclaration(attribute, field.getInitializer()); - attribute.isStatic=isStatic; - //@GINO: recursion might not be the best idea - if (returnType!=null) { - attribute.type = returnType; - // apply (force) type onto OL initializer - if (field.getInitializer() instanceof ObjectLiteral) { - ((ObjectLiteral) field.getInitializer()).setInferredType(returnType); - } - } - else - attribute.type = getTypeOf(field.getInitializer()); - } - } - } - } - } - } - - public void endVisit(IAssignment assignment) { - popContext(); - } - - protected boolean handleAttributeDeclaration(InferredAttribute attribute, IExpression initializer) { - return true; - } - - protected boolean handleFunctionCall(IFunctionCall messageSend) { - return handleFunctionCall(messageSend, null); - } - - protected boolean handleFunctionCall(IFunctionCall messageSend, LocalDeclaration assignmentExpression) { - return true; - } - - public void endVisit(IReturnStatement returnStatement) { - -// if (currentContext.currentMethod!=null) -// { -// if (returnStatement.getExpression()!=null) -// { -// -// InferredType type = getTypeOf(returnStatement.getExpression()); -// -// if (currentContext.currentMethod.inferredType==VoidType) -// currentContext.currentMethod.inferredType=type; -// else if (type==null || !type.equals(currentContext.currentMethod.inferredType)) -// currentContext.currentMethod.inferredType=null; -// } -// } - - } - - - public boolean visit(IReturnStatement returnStatement) { - - if (currentContext.currentMethod!=null) - { - if (returnStatement.getExpression()!=null) - { - - InferredType type = null; - IExpression expression = returnStatement.getExpression(); - if (expression instanceof IObjectLiteral) - { - type = createAnonymousType( (ObjectLiteral)expression); - - //set the start and end - type.sourceStart = expression.sourceStart(); - type.sourceEnd = expression.sourceEnd(); - } - else - type=getTypeOf(expression); - - if (currentContext.currentMethod.getInferredType()==VoidType) { - currentContext.currentMethod.setInferredType(type); - } else { - /* If the return statement inferred type is null or - * the existing inferred return type and the statement return type are not equal and - * the return type is either not well known or is well known and the return type names are the same - * - * This logic is to cover the scenario where the return type is a known type but is from a - * different instance of the InferEngine - */ - boolean shouldSetToAny = !((MethodDeclaration)currentContext.currentMethod).isInferredJsDocType(); - if(type != null && shouldSetToAny) { - //get the name of the current methods inferred return type - String currentMethodInferredType = null; - if( this.currentContext.currentMethod.getInferredType() != null && this.currentContext.currentMethod.getInferredType().name != null) { - currentMethodInferredType = new String(this.currentContext.currentMethod.getInferredType().name); - } - - boolean returnTypesEqual = type.equals(currentContext.currentMethod.getInferredType()); - boolean returnTypeNamesEqual = (new String(type.name)).equals(currentMethodInferredType); - boolean returnTypeIsWellKnown = WellKnownTypes.containsKey(type.name); - - shouldSetToAny = !returnTypesEqual && (!returnTypeIsWellKnown || !(returnTypeIsWellKnown && returnTypeNamesEqual)); - } - - if(shouldSetToAny) { - currentContext.currentMethod.setInferredType(null); - } - } - } - } - return false; - } - - - public void endVisit(IFunctionDeclaration methodDeclaration) { - popContext(); - } - - public boolean visit(IFunctionDeclaration methodDeclaration) { - pushContext(); - if (this.isTopLevelAnonymousFunction && this.currentContext.currentType==null) - { - this.currentContext.currentType=addType(InferredType.GLOBAL_NAME,true); - this.inferredGlobal=this.currentContext.currentType; - } - - this.isTopLevelAnonymousFunction=false; - char[] methodName = methodDeclaration.getName(); - //if declaration didn't have name get name from inferred method if there is one - if(methodName == null && methodDeclaration.getInferredMethod() != null) { - methodName = methodDeclaration.getInferredMethod().name; - } - - if (passNumber==1) - { - buildDefinedMembers((ProgramElement[])methodDeclaration.getStatements(),(Argument[])methodDeclaration.getArguments()); - if (methodDeclaration.getJsDoc()!=null) - { - InferredMethod method=null; - Javadoc javadoc = (Javadoc)methodDeclaration.getJsDoc(); - createTypeIfNecessary(javadoc); - if (javadoc.isConstructor) - { - InferredType type; - if (!this.currentContext.isJsDocClass && methodName!=null) - type = this.addType(methodName); - else - type=this.currentContext.currentType; - if (type!=null) - handleJSDocConstructor(type, methodDeclaration, methodDeclaration.sourceStart()); - } - else if (javadoc.memberOf!=null) - { - InferredType type = this.addType(javadoc.memberOf.getFullTypeName(),true); - char [] name=methodName; - int nameStart = methodDeclaration.sourceStart(); - if (name!=null) - method=type.addMethod(methodName, methodDeclaration, nameStart); - } - else if (javadoc.methodDef!=null && this.currentContext.isJsDocClass) - { - InferredType type=this.currentContext.currentType; - char[][] methName = javadoc.methodDef.getTypeName(); - int nameStart = ((MethodDeclaration)methodDeclaration).sourceStart; - if (methName.length==1) - method=type.addMethod(methName[0], methodDeclaration, nameStart); - else - { - method=type.addMethod(methName[methName.length-1], methodDeclaration, nameStart); - method.isStatic=true; - } - - } - - if (javadoc.returnType!=null) - { - InferredType type = this.addType(changePrimitiveToObject(javadoc.returnType.getFullTypeName())); - methodDeclaration.setInferredType(type); - ((MethodDeclaration)methodDeclaration).bits |= ASTNode.IsInferredJsDocType; - } - - } - handleFunctionDeclarationArguments((MethodDeclaration)methodDeclaration,(Javadoc)methodDeclaration.getJsDoc()); - } - // check if this is a constructor - if (passNumber==2) - { - - if (methodName!=null) { - InferredType type = compUnit - .findInferredType(methodName); - if (type != null) { - this.currentContext.currentType = type; - type.isDefinition = true; - int nameStart = methodDeclaration.sourceStart(); - type.addConstructorMethod(methodName, methodDeclaration, nameStart); - } - } - } - this.currentContext.currentMethod=(MethodDeclaration)methodDeclaration; - if (methodDeclaration.getInferredMethod()!=null && methodDeclaration.getInferredMethod().inType!=null) - this.currentContext.currentType=methodDeclaration.getInferredMethod().inType; - if (methodDeclaration.getInferredType()==null) - methodDeclaration.setInferredType(VoidType); - return true; - } - - protected void handleJSDocConstructor(InferredType type,IFunctionDeclaration methodDeclaration, int nameStart) { - Javadoc javadoc = (Javadoc)methodDeclaration.getJsDoc(); - type.isDefinition=true; - type.addConstructorMethod(type.name, methodDeclaration, nameStart); - - if (javadoc.extendsType!=null) - { - InferredType superType=this.addType(javadoc.extendsType.getFullTypeName()); - type.superClass=superType; - } - - } - - protected void handleFunctionDeclarationArguments(IFunctionDeclaration methodDeclaration, IJsDoc jsdoc) { - if (jsdoc==null || !(jsdoc instanceof Javadoc)) - return; - Javadoc javadoc = (Javadoc) jsdoc; - - IArgument[] arguments = methodDeclaration.getArguments(); - if (arguments!=null) - for (int i = 0; i < arguments.length; i++) { - if (arguments[i].getInferredType() != null) - continue; - - JavadocSingleNameReference param = javadoc.findParam(arguments[i].getName()); - if (param!=null) - { - if (param.types!=null) - { - char []name={}; - for (int j = 0; j < param.types.length; j++) { - //char []typeName=param.types[j].getFullTypeName(); - //make sure we are using the type version of Boolean, even if the user entered boolean as the JSdoc type. - char []typeName=changePrimitiveToObject(param.types[j].getFullTypeName()); - if (j==0) - name=typeName; - else - { - name=CharOperation.append(name, '|'); - name=CharOperation.concat(name, typeName); - } - } - InferredType paramType=this.addType(name); - arguments[i].setInferredType(paramType); - } - } - /** - * http://code.google.com/p/jsdoc-toolkit/wiki/InlineDocs - **/ - else if (arguments[i].getJsDoc() != null) { - if (((Javadoc) arguments[i].getJsDoc()).returnType != null) { - arguments[i].setInferredType(this.addType(((Javadoc) arguments[i].getJsDoc()).returnType.getFullTypeName())); - } - } - else if(arguments[i].getComment() != null) { - char[] comment = CharOperation.trim(arguments[i].getComment()); - boolean validForName = true; - for (int j = 0; j < comment.length && validForName; j++) { - validForName &= !CharOperation.isWhitespace(comment[j]) && (Character.isJavaIdentifierPart(comment[j]) || comment[j] == '.'); - } - if (validForName) { - arguments[i].setInferredType(this.addType(comment)); - } - } - } - } - - - - public boolean visit( - IAllocationExpression allocationExpression) { - - InferredType type = null; - char [] possibleTypeName = constructTypeName( allocationExpression.getMember() ); - if( possibleTypeName != null ){ - type = compUnit.findInferredType( possibleTypeName ); - - if( type == null ) - type = addType( possibleTypeName ); //creating type - } - return true; - } - - - public void endVisit(IObjectLiteralField field) { -// if (field.getJsDoc()!=null) -// { -// Javadoc javaDoc = (Javadoc)field.getJsDoc(); -// InferredType inClass=this.currentContext.currentType; -// char [] name=null; -// int nameStart=-1; -// InferredType returnType=null; -//// boolean isFunction=field.initializer instanceof FunctionExpression; -// if (field.getFieldName() instanceof SingleNameReference) -// { -// SingleNameReference singleNameReference=(SingleNameReference)field.getFieldName(); -// name=singleNameReference.token; -// nameStart=singleNameReference.sourceStart; -// } -// if (javaDoc.memberOf!=null) -// { -// char[] typeName = javaDoc.memberOf.getFullTypeName(); -// convertAnonymousTypeToNamed(inClass,typeName); -// inClass.isDefinition=true; -// } -// else if (this.currentContext.isJsDocClass && javaDoc.property!=null) -// { -// if (this.currentContext.currentType.isAnonymous && this.currentContext.parent!=null) -// { -// InferredType previousType = this.currentContext.parent.currentType; -// if (previousType!=null) -// { -// copyAnonymousTypeToNamed(inClass,previousType); -// this.currentContext.currentType=previousType; -// } -// -// } -// } -// if (javaDoc.returnType!=null) -// { -// returnType=this.addType(javaDoc.returnType.getFullTypeName()); -// } -// -// if (inClass!=null && name!=null) -// { -// if (field.getInitializer() instanceof FunctionExpression) { -// FunctionExpression functionExpression = (FunctionExpression) field.getInitializer(); -// InferredMember method = inClass.addMethod(name, functionExpression.methodDeclaration,false); -// method.nameStart=nameStart; -// functionExpression.methodDeclaration.modifiers=javaDoc.modifiers; -// if (returnType!=null) -// { -// functionExpression.methodDeclaration.inferredType=returnType; -// } -//// else -//// method.inferredType=functionExpression.methodDeclaration.inferredType; -// } -// else //attribute -// { -// InferredAttribute attribute = inClass.addAttribute(name, field.getFieldName()); -// attribute.nameStart=field.getFieldName().sourceStart(); -// if (returnType!=null) -// attribute.type=returnType; -// } -// } -// -// } -// //no jsdoc -// else{ -// -// if( field.getInitializer() instanceof ObjectLiteral ){ -// -// } -// -// -// } - } - - private void copyAnonymousTypeToNamed(InferredType inClass, - InferredType toType) { - if (toType==null)return; - - compUnit.inferredTypesHash.removeKey(inClass.name); - if (inClass.methods!=null) - { - toType.methods.addAll(inClass.methods); -// else -// toType.methods=inClass.methods; - - } - if (inClass.attributes!=null) - { - for (int i = 0; i < inClass.numberAttributes; i++) { - toType.addAttribute(inClass.attributes[i]); - } - } - - - } - - private void convertAnonymousTypeToNamed(InferredType inClass, char[] typeName) { - if (inClass.isAnonymous) - { - inClass.isAnonymous=false; - compUnit.inferredTypesHash.removeKey(inClass.name); - inClass.name=typeName; - compUnit.inferredTypesHash.put(typeName,inClass); - - } - - } - - protected boolean isMatch(IExpression expr,char[] [] names, int index) - { - char [] matchName=names[index]; - if (expr instanceof SingleNameReference) { - SingleNameReference snr = (SingleNameReference) expr; - return CharOperation.equals(snr.token, matchName); - } - else if (expr instanceof FieldReference && names.length>1 && index>0) { - FieldReference fieldReference = (FieldReference) expr; - if (CharOperation.equals(fieldReference.token, matchName)) - return isMatch(fieldReference.receiver, names, index-1); - - } - return false; - } - - protected boolean isFunction(IFunctionCall messageSend,String string) { - String []names=string.split("\\."); //$NON-NLS-1$ - char [] functionName=names[names.length-1].toCharArray(); - if (!CharOperation.equals(functionName, messageSend.getSelector())) - return false; - - char [][]namesChars=new char[names.length][]; - for (int i = 0; i < namesChars.length; i++) { - namesChars[i]=names[i].toCharArray(); - } - if (names.length>1) - return isMatch(messageSend.getReceiver(), namesChars, namesChars.length-2); - return true; - } - - protected boolean isFunction(IFunctionCall messageSend,char [][]names) { - char [] functionName=names[names.length-1]; - if (!CharOperation.equals(functionName, messageSend.getSelector())) - return false; - - if (names.length>1) - return isMatch(messageSend.getReceiver(), names, names.length-2); - return true; - } - - - public void doInfer() - { - try { - long time0 = 0; - if (REPORT_INFER_TIME) { - time0 = System.currentTimeMillis(); - } - - compUnit.traverse(this ); - passNumber=2; - compUnit.traverse(this ); - for (int i = 0; i < compUnit.numberInferredTypes; i++) { - if (compUnit.inferredTypes[i].sourceStart<0) - compUnit.inferredTypes[i].sourceStart=0; - } - - if (REPORT_INFER_TIME) { - long time = System.currentTimeMillis() - time0; - System.err.println(getClass().getName() + " inferred " + new String(compUnit.getFileName()) + " in " + time + "ms"); - } - this.compUnit=null; - - } catch (RuntimeException e) { - org.eclipse.wst.jsdt.internal.core.util.Util.log(e, "error during type inferencing"); - } -} - - protected InferredType addType(char[] className) { - return addType(className,false); - } - - /** - * Create a new inferred type with the given name - * - * @param className the name of the inferred type - * @param isDefinition true if this unit defines the type - * @return new Inferred type - */ - protected InferredType addType(char[] className, boolean isDefinition) { - InferredType type = compUnit.addType(className, isDefinition, this.inferenceProvider.getID()); - - return type; - } - - protected final void pushContext() - { - Context newContext = new Context( currentContext ); - contexts[++contextPtr] = currentContext; - currentContext = newContext; - - } - - protected final void popContext() - { - currentContext = contexts[contextPtr]; - contexts[contextPtr--] = null; - } - - protected final boolean isInNamedMethod() - { - return this.currentContext.currentMethod!=null && this.currentContext.currentMethod.getName()!=null; - } - - - /** - * Finds a Var Declaration on the context from the name represented with the expression - * - * Currently, only SNR are supported - */ - protected IAbstractVariableDeclaration getVariable(IExpression expression) - { - char [] name=null; - - if (expression instanceof ISingleNameReference) - name = ((ISingleNameReference) expression).getToken(); - else if (expression instanceof IFieldReference) - name = ((IFieldReference) expression).getToken(); - if (name!=null) - { - Object var = this.currentContext.getMember( name ); - if (var instanceof IAbstractVariableDeclaration) - return (IAbstractVariableDeclaration)var; - - } - return null; - - } - - /** - * Finds a assignment on the context from the name represented with the expression - * - * Currently, only SNR are supported - */ - protected IAssignment getAssignment(IExpression expression) - { - char [] name=null; - - if (expression instanceof ISingleNameReference) - name = ((ISingleNameReference) expression).getToken(); - else if (expression instanceof IFieldReference) - name = ((IFieldReference) expression).getToken(); - if (name!=null) - { - Object assignment = this.currentContext.getMember( name ); - if (assignment instanceof IAssignment) - return (IAssignment)assignment; - - } - return null; - - } - - /** - * Finds a Function Declaration on the context from the name represented with the expression - * - * Currently, only SNR are supported - */ - protected IAbstractFunctionDeclaration getFunction(IExpression expression) - { - char [] name=null; - - if (expression instanceof ISingleNameReference) - name = ((ISingleNameReference) expression).getToken(); - else if (expression instanceof IFieldReference) - name = ((IFieldReference) expression).getToken(); - if (name!=null) - { - Object method = this.currentContext.getMember( name ); - if (method instanceof IAbstractFunctionDeclaration) - return (IAbstractFunctionDeclaration)method; - - } - return null; - } - - private void buildDefinedMembers(IProgramElement[] statements, IArgument[] arguments) { - - if (arguments!=null) - { - for (int i = 0; i < arguments.length; i++) { - this.currentContext.addMember( arguments[i].getName(), arguments[i] ); - } - } - if (statements!=null) - { - for (int i = 0; i < statements.length; i++) { - if (statements[i] instanceof ILocalDeclaration) { - ILocalDeclaration local = (ILocalDeclaration) statements[i]; - this.currentContext.addMember( local.getName(), local ); - } - else if (statements[i] instanceof IAbstractFunctionDeclaration) { - IAbstractFunctionDeclaration method = (IAbstractFunctionDeclaration) statements[i]; - if (method.getName()!=null) - this.currentContext.addMember( method.getName(), method ); - } - } - } - } - - private static boolean isThis(IExpression expression) - { - if (expression instanceof FieldReference && ((FieldReference)expression).receiver.isThis()) - return true; - return false; - } - - /* - * This method is used to determined the inferred type of a LHS Expression. - * - * It could return null. - * - * a.b.c - */ - private InferredType getInferredType( Expression expression ){ - - InferredType type = null; - - /* - * this - */ - if( expression instanceof IThisReference ){ - if (this.passNumber==2 && this.currentContext.currentType==null) - { - char [] possibleTypeName={'g','l','o','b','a','l'}; - if (this.currentContext.currentMethod!=null) - possibleTypeName=this.currentContext.currentMethod.getName(); - this.currentContext.setCurrentType(createAnonymousType(possibleTypeName, null)); - } - - type = this.currentContext.currentType; - } - /* - * foo (could be a Type name or a reference to a variable) - */ - else if( expression instanceof SingleNameReference ){ - char [] possibleTypeName = constructTypeName( expression ); - - if( possibleTypeName != null ){ - //search the defined types in the context - type = compUnit.findInferredType( possibleTypeName ); - - if (type==null) - { - if (WellKnownTypes.containsKey(possibleTypeName)) - { - type = addType(possibleTypeName,true); - } - else if (/*this.passNumber==2 && */this.isKnownType(possibleTypeName)) - { - type = addType(possibleTypeName,true); -// if (type!=null) -// { -// AbstractVariableDeclaration varDecl = getVariable( (expression) ); -// -// if( varDecl != null ){ -// varDecl.inferredType=type; -// } -// -// } - } - - } - - - /* - * There is no match for a type with the name, check if the name refers to - * var decl and return its type - */ - if( type == null ){ - - IAbstractVariableDeclaration varDecl = getVariable( expression ); - - if( varDecl != null ){ - type = varDecl.getInferredType(); //could be null - if (type!=null && !type.isAnonymous) { - if(varDecl.getInitialization() instanceof IAllocationExpression && !type.isFunction()) { - type = createAnonymousType(varDecl); - } else { - InferredType superType = type; - type = addType(varDecl.getName(), true); - type.superClass = superType; - } - type.updatePositions(varDecl.sourceStart(), varDecl.sourceEnd()); - } - - } else { - IAssignment assignment = getAssignment(expression); - if(assignment != null) { - type = assignment.getInferredType(); //could be null - if (type!=null && !type.isAnonymous) { - if(assignment.getExpression() instanceof IAllocationExpression && !type.isFunction()) { - type = createAnonymousType(assignment); - } else { - InferredType superType = type; - type = addType(getName(assignment.getLeftHandSide()), true); - type.superClass = superType; - } - type.updatePositions(assignment.sourceStart(), assignment.sourceEnd()); - } - } - } - - } - } - } - /* - * foo.bar.xxx... - */ - else if( expression instanceof FieldReference ){ - char[] possibleTypeName = constructTypeName(expression); - - if (possibleTypeName != null) - // search the defined types in the context - type = compUnit.findInferredType(possibleTypeName); - - if (type==null && isPossibleClassName(possibleTypeName)) - { - type = addType(possibleTypeName,true); - } - - /* - * Continue the search by trying to resolve further down the name - * because this token of the field reference could be a member of a - * type or instance of a type - */ - if (type == null) { - FieldReference fRef = (FieldReference) expression; - - // this - InferredType parentType = getInferredType(fRef.receiver); - - if (parentType != null) { - // check the members and return type - InferredAttribute typeAttribute = parentType - .findAttribute(fRef.token); - - if (typeAttribute != null) { - type = typeAttribute.type; - if (type != null && !type.isAnonymous) { - if (possibleTypeName==null) - possibleTypeName=typeAttribute.name; - type = createAnonymousType(possibleTypeName, type); - typeAttribute.type = type; - } - } - } - } - - } - - return type; - } - - - - protected boolean isKnownType(char[] possibleTypeName) { - return false; - } - - /* - * For SNR it returns the name - * For FR it construct a Qualified name separated by '.' - * - * If at any point it hits a portion of the Field reference that is - * not supported (such as a function call, a prototype, or this ) - */ - protected final char [] constructTypeName( IExpression expression ){ - - return Util.getTypeName( expression ); - } - - public boolean visit(IObjectLiteral literal) { - if (this.passNumber==1 && literal.getInferredType()==null) - createAnonymousType((ObjectLiteral)literal); - pushContext(); - this.currentContext.currentType=literal.getInferredType(); - return true; - } - - public void endVisit(IObjectLiteral literal) { - popContext(); - } - - - /** - * Overriden by client who wish to update the infer options - * - * @param options - */ - public void initializeOptions(InferOptions options) { - } - - protected boolean isPossibleClassName(char[]name) - { - return false; - } - - /** - * Get the Script file this inferrence is being done on - * - * @return - */ - public IScriptFileDeclaration getScriptFileDeclaration() - { - return this.compUnit; - } - - public InferredType findDefinedType(char [] className) - { - return compUnit.findInferredType(className); - } - - protected char[] changePrimitiveToObject(char[] name) { - //Changes the first character of the name of the primitive types to uppercase. This will allow future reference to the object wrapper instead of the primitive type. - if(CharOperation.equals(name, TypeConstants.BOOLEAN, false)) //$NON-NLS-1$ - return BooleanType.getName(); - return name; - } - - private char[] getName(IExpression expression) { - if (expression instanceof ISingleNameReference) - return ((ISingleNameReference) expression).getToken(); - else if (expression instanceof IFieldReference) - return ((IFieldReference) expression).getToken(); - return null; - } - -} +/******************************************************************************* + * Copyright (c) 2005, 2013 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.wst.jsdt.core.infer; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +import org.eclipse.wst.jsdt.core.ast.ASTVisitor; +import org.eclipse.wst.jsdt.core.ast.IASTNode; +import org.eclipse.wst.jsdt.core.ast.IAbstractFunctionDeclaration; +import org.eclipse.wst.jsdt.core.ast.IAbstractVariableDeclaration; +import org.eclipse.wst.jsdt.core.ast.IAllocationExpression; +import org.eclipse.wst.jsdt.core.ast.IArgument; +import org.eclipse.wst.jsdt.core.ast.IAssignment; +import org.eclipse.wst.jsdt.core.ast.IBinaryExpression; +import org.eclipse.wst.jsdt.core.ast.IExpression; +import org.eclipse.wst.jsdt.core.ast.IFalseLiteral; +import org.eclipse.wst.jsdt.core.ast.IFieldReference; +import org.eclipse.wst.jsdt.core.ast.IFunctionCall; +import org.eclipse.wst.jsdt.core.ast.IFunctionDeclaration; +import org.eclipse.wst.jsdt.core.ast.IFunctionExpression; +import org.eclipse.wst.jsdt.core.ast.IJsDoc; +import org.eclipse.wst.jsdt.core.ast.ILocalDeclaration; +import org.eclipse.wst.jsdt.core.ast.INumberLiteral; +import org.eclipse.wst.jsdt.core.ast.IObjectLiteral; +import org.eclipse.wst.jsdt.core.ast.IObjectLiteralField; +import org.eclipse.wst.jsdt.core.ast.IProgramElement; +import org.eclipse.wst.jsdt.core.ast.IReference; +import org.eclipse.wst.jsdt.core.ast.IReturnStatement; +import org.eclipse.wst.jsdt.core.ast.IScriptFileDeclaration; +import org.eclipse.wst.jsdt.core.ast.ISingleNameReference; +import org.eclipse.wst.jsdt.core.ast.IStringLiteral; +import org.eclipse.wst.jsdt.core.ast.IThisReference; +import org.eclipse.wst.jsdt.core.ast.ITrueLiteral; +import org.eclipse.wst.jsdt.core.compiler.CharOperation; +import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode; +import org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration; +import org.eclipse.wst.jsdt.internal.compiler.ast.AllocationExpression; +import org.eclipse.wst.jsdt.internal.compiler.ast.ArrayInitializer; +import org.eclipse.wst.jsdt.internal.compiler.ast.ArrayReference; +import org.eclipse.wst.jsdt.internal.compiler.ast.Assignment; +import org.eclipse.wst.jsdt.internal.compiler.ast.BinaryExpression; +import org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration; +import org.eclipse.wst.jsdt.internal.compiler.ast.Expression; +import org.eclipse.wst.jsdt.internal.compiler.ast.FieldReference; +import org.eclipse.wst.jsdt.internal.compiler.ast.FunctionExpression; +import org.eclipse.wst.jsdt.internal.compiler.ast.Javadoc; +import org.eclipse.wst.jsdt.internal.compiler.ast.JavadocSingleNameReference; +import org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration; +import org.eclipse.wst.jsdt.internal.compiler.ast.MessageSend; +import org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration; +import org.eclipse.wst.jsdt.internal.compiler.ast.ObjectLiteral; +import org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds; +import org.eclipse.wst.jsdt.internal.compiler.ast.Reference; +import org.eclipse.wst.jsdt.internal.compiler.ast.SingleNameReference; +import org.eclipse.wst.jsdt.internal.compiler.ast.StringLiteral; +import org.eclipse.wst.jsdt.internal.compiler.ast.ThisReference; +import org.eclipse.wst.jsdt.internal.compiler.ast.UnaryExpression; +import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeConstants; +import org.eclipse.wst.jsdt.internal.compiler.util.HashtableOfObject; +import org.eclipse.wst.jsdt.internal.compiler.util.Util; +import org.eclipse.wst.jsdt.internal.core.search.indexing.IIndexConstants; + +/** + * The default inference engine. + * + *

+ * Clients may subclass this class but should expect some breakage by future releases. + *

+ * + * Provisional API: This class/interface is part of an interim API that is still under development + * and expected to + * change significantly before reaching stability. It is being made available at this early stage to + * solicit feedback + * from pioneering adopters on the understanding that any code that uses this API will almost + * certainly be broken + * (repeatedly) as the API evolves. + */ +public class InferEngine extends ASTVisitor implements IInferEngine { + + /** + *

+ * String type that is initialized on first use and added to the compilation unit. + *

+ */ + private InferredType fStringType; + + /** + *

+ * Number type that is initialized on first use and added to the compilation unit. + *

+ */ + private InferredType fNumberType; + + /** + *

+ * Boolean type that is initialized on first use and added to the compilation unit. + *

+ */ + private InferredType fBooleanType; + + /** + *

+ * Function type that is initialized on first use and added to the compilation unit. + *

+ */ + private InferredType fFunctionType; + + /** + *

+ * Array type that is initialized on first use and added to the compilation unit. + *

+ */ + private InferredType fArrayType; + + /** + *

+ * Void type that is initialized on first use and added to the compilation unit. + *

+ */ + private InferredType fVoidType; + + /** + *

+ * Object type that is initialized on first use and added to the compilation unit. + *

+ */ + private InferredType fObjectType; + + InferOptions inferOptions; + CompilationUnitDeclaration compUnit; + Context[] contexts = new Context[100]; + int contextPtr = -1; + Context currentContext = new Context(); + protected int passNumber = 1; + + boolean isTopLevelAnonymousFunction; + int anonymousCount = 0; + + public static boolean DEBUG = false; + + public InferrenceProvider inferenceProvider; + + /** + * @deprecated use {@link #getStringType()} + */ + public InferredType StringType = new InferredType(TypeConstants.JAVA_LANG_STRING[0]); + + /** + * @deprecated use {@link #getNumberType()} + */ + public InferredType NumberType = new InferredType(TypeConstants.NUMBER[0]); + + /** + * @deprecated use {@link #getBooleanType()} + */ + public InferredType BooleanType = new InferredType(TypeConstants.BOOLEAN_OBJECT[0]); + + /** + * @deprecated use {@link #getFunctionType()} + */ + public InferredType FunctionType = new InferredType(TypeConstants.FUNCTION[0]); + + /** + * @deprecated use {@link #getArrayType()} + */ + public InferredType ArrayType = new InferredType(TypeConstants.ARRAY[0]); + + /** + * @deprecated use {@link #getVoidType()} + */ + public InferredType VoidType = new InferredType(TypeConstants.VOID); + + /** + * @deprecated use {@link #getObjectType()} + */ + public InferredType ObjectType = new InferredType(TypeConstants.OBJECT); + + /** + * @deprecated - no longer used + */ + public InferredType GlobalType = new InferredType(InferredType.GLOBAL_NAME); + + public static HashtableOfObject WellKnownTypes = new HashtableOfObject(); + { + WellKnownTypes.put(TypeConstants.OBJECT, null); + WellKnownTypes.put(TypeConstants.ARRAY[0], null); + WellKnownTypes.put(TypeConstants.JAVA_LANG_STRING[0], null); + WellKnownTypes.put(TypeConstants.NUMBER[0], null); + WellKnownTypes.put(TypeConstants.BOOLEAN_OBJECT[0], null); + WellKnownTypes.put(TypeConstants.FUNCTION[0], null); + WellKnownTypes.put(new char[] { 'D', 'a', 't', 'e' }, null); + WellKnownTypes.put(new char[] { 'M', 'a', 't', 'h' }, null); + WellKnownTypes.put(new char[] { 'R', 'e', 'g', 'E', 'x', 'p' }, null); + WellKnownTypes.put(new char[] { 'E', 'r', 'r', 'o', 'r' }, null); + } + + protected InferredType inferredGlobal = null; + + /** + * @deprecated Will be removed + */ + static final char[] CONSTRUCTOR_ID = { 'c', 'o', 'n', 's', 't', 'r', 'u', 'c', 't', 'o', 'r' }; + + /** + *

+ * Use to keep track of the current context of the infer engine. + *

+ */ + static class Context { + InferredType currentType; + IFunctionDeclaration currentMethod; + + /** The current assignment. */ + IAssignment currentAssignment; + + /** the current declaration */ + ILocalDeclaration currentLocalDeclaration; + + /** The current return */ + IReturnStatement currentReturn; + + boolean isJsDocClass; + + private HashtableOfObject definedMembers; + + /* Parent context to provide chaining when searching + * for members in scope. */ + private Context parent = null; + + /* Root context */ + Context() { + } + + /* Nested context */ + Context(Context parent) { + this.parent = parent; + + currentType = parent.currentType; + currentMethod = parent.currentMethod; + this.currentAssignment = parent.currentAssignment; + this.currentLocalDeclaration = parent.currentLocalDeclaration; + this.currentReturn = parent.currentReturn; + this.isJsDocClass = parent.isJsDocClass; + } + + public Object getMember(char[] key) { + Object value = null; + if(definedMembers != null) { + value = definedMembers.get(key); + } + + // chain lookup + if(value == null && parent != null) { + value = parent.getMember(key); + } + + return value; + } + + public void addMember(char[] key, Object member) { + if(key == null) + return; + + if(definedMembers == null) { + definedMembers = new HashtableOfObject(); + } + + definedMembers.put(key, member); + } + + public void setCurrentType(InferredType type) { + this.currentType = type; + Context parentContext = this.parent; + + while(parentContext != null && parentContext.currentMethod == this.currentMethod) { + parentContext.currentType = type; + parentContext = parentContext.parent; + } + } + } + + private static boolean REPORT_INFER_TIME = false; + + /** + *

+ * Constructor that uses default {@link InferOptions}. + *

+ */ + public InferEngine() { + this(new InferOptions()); + } + + /** + *

+ * Constructor using given {@link InferOptions}. + *

+ * + * @param inferOptions + * to create this infer engine with + */ + public InferEngine(InferOptions inferOptions) { + this.inferOptions = inferOptions; + } + + public void initialize() { + this.contextPtr = -1; + this.currentContext = new Context(); + this.passNumber = 1; + this.isTopLevelAnonymousFunction = false; + this.anonymousCount = 0; + this.inferredGlobal = null; + } + + public void setCompilationUnit(CompilationUnitDeclaration scriptFileDeclaration) { + this.compUnit = scriptFileDeclaration; + buildDefinedMembers(scriptFileDeclaration.getStatements(), null); + } + + public boolean visit(IFunctionCall functionCall) { + boolean visitChildren = handleFunctionCall(functionCall); + if(visitChildren) { + if(functionCall.getReceiver() instanceof FunctionExpression) { + if (this.contextPtr == -1) { + this.isTopLevelAnonymousFunction = true; + } + if (functionCall instanceof MessageSend && ((MessageSend) functionCall).getArguments() != null) { + MethodDeclaration methodDeclaration = ((FunctionExpression) functionCall.getReceiver()).getMethodDeclaration(); + if (methodDeclaration != null && methodDeclaration.getArguments() != null) { + IArgument[] declaredArguments = methodDeclaration.getArguments(); + IExpression[] sentArguments = ((MessageSend) functionCall).getArguments(); + for (int i = 0; i < declaredArguments.length; i++) { + if (i >= sentArguments.length) { + continue; + } + handleFunctionDeclarationArgument(declaredArguments[i], sentArguments[i]); + } + } + } + } + } + return visitChildren; + } + + protected void handleFunctionDeclarationArgument(IArgument declaredArgument, IExpression sentArgument) { + // set the declared argument's type to be the matching parameter type + if (!declaredArgument.isType() && declaredArgument.getInferredType() == null) { + if (sentArgument instanceof SingleNameReference) { + InferredType inferredType = getInferredType(sentArgument); + if (inferredType == null) { + char[] parameterName = getName(sentArgument); + if (parameterName!= null && isGlobal(parameterName)) { + inferredType = createAnonymousGlobalType(parameterName); + } + } + declaredArgument.setInferredType(inferredType); + } + else if (sentArgument instanceof ThisReference) { + //check if "this" refers to the global object + if (this.isTopLevelAnonymousFunction) { + char[] parameterName = declaredArgument.getName(); + if (parameterName != null) { + InferredType inferredType = createAnonymousGlobalType(parameterName); + declaredArgument.setInferredType(inferredType); + } + } + } + } + } + + public boolean visit(ILocalDeclaration localDeclaration) { + // add as a member of the current context + currentContext.addMember(localDeclaration.getName(), localDeclaration); + + // create a new context for the local declaration + pushContext(); + this.currentContext.currentLocalDeclaration = localDeclaration; + + if(this.passNumber == 1 && localDeclaration instanceof LocalDeclaration && this.currentContext.currentMethod == null) { + ((LocalDeclaration)localDeclaration).setIsLocal(false); + } + + if(localDeclaration.getJsDoc() != null) { + Javadoc javadoc = (Javadoc) localDeclaration.getJsDoc(); + createTypeIfNecessary(javadoc); + InferredAttribute attribute = null; + if(javadoc.memberOf != null) { + InferredType type = this.addType(javadoc.memberOf.getFullTypeName(), true); + int nameStart = localDeclaration.sourceStart(); + attribute = type.addAttribute(localDeclaration.getName(), localDeclaration, nameStart); + handleAttributeDeclaration(attribute, localDeclaration.getInitialization()); + if(localDeclaration.getInitialization() != null) { + attribute.initializationStart = localDeclaration.getInitialization().sourceStart(); + attribute.type = getTypeOf(localDeclaration.getInitialization()); + } + attribute.inType = type; + } + + if(javadoc.returnType != null) { + InferredType type = this.addType(changePrimitiveToObject(javadoc.returnType.getFullTypeName())); + localDeclaration.setInferredType(type); + if(attribute != null) + attribute.type = type; + } + } + + // visit the function in case it defines a type + if(localDeclaration.getInitialization() instanceof IFunctionExpression) { + boolean keepVisiting = handleFunctionExpressionLocalDeclaration(localDeclaration); + if(!keepVisiting) { + return false; + } + } + + //if initialization set, attempt to set the inferred type + if(localDeclaration.getInitialization() != null) { + if(localDeclaration.getInitialization() instanceof MessageSend) { + handleFunctionCall((IFunctionCall) localDeclaration.getInitialization(), + (LocalDeclaration) localDeclaration); + if(((MessageSend)localDeclaration.getInitialization()).receiver instanceof IFunctionExpression && this.passNumber == 2) { + if(((FunctionExpression)((MessageSend)localDeclaration.getInitialization()).receiver).methodDeclaration != null) { + localDeclaration.setInferredType(((FunctionExpression)((MessageSend)localDeclaration.getInitialization()).receiver).methodDeclaration.inferredType); + } + } + } else { + if (this.isExpressionAType(localDeclaration.getInitialization())) { + localDeclaration.setIsType(true); + } + InferredType type = this.getTypeForVariableInitialization(localDeclaration.getName(), localDeclaration.getInitialization()); + if (localDeclaration.getInferredType() == null || (type != null && type.isAnonymous)) + localDeclaration.setInferredType(type); + } + } + + return true; + } + + /** + * @see org.eclipse.wst.jsdt.core.ast.ASTVisitor#endVisit(org.eclipse.wst.jsdt.core.ast.ILocalDeclaration) + */ + public void endVisit(ILocalDeclaration localDeclaration) { + popContext(); + } + + private void createTypeIfNecessary(Javadoc javadoc) { + if(javadoc.memberOf != null) { + char[][] namespace = {}; + char[][] typeName = javadoc.memberOf.getTypeName(); + if(javadoc.namespace != null) { + namespace = javadoc.namespace.getTypeName(); + } + char[] name = + CharOperation.concat(CharOperation.concatWith(namespace, '.'), CharOperation.concatWith(typeName, + '.'), '.'); + this.currentContext.currentType = addType(name); + if(javadoc.extendsType != null) { + char[] superName = CharOperation.concatWith(javadoc.extendsType.getTypeName(), '.'); + this.currentContext.currentType.setSuperType(addType(superName)); + } + this.currentContext.isJsDocClass = true; + + } + + } + + public boolean visit(IAssignment assignment) { + //if assigning to single name add assignment to context if there is not an existing var declaration + IAbstractVariableDeclaration existingVarDecl = null; + IAssignment existingAssignmentDecl = null; + if(assignment.getLeftHandSide() instanceof ISingleNameReference) { + existingVarDecl = this.getVariable(assignment.getLeftHandSide()); + if(existingVarDecl == null) { + existingAssignmentDecl = this.getAssignment(assignment.getLeftHandSide()); + if(existingAssignmentDecl == null) { + currentContext.addMember(this.getName(assignment.getLeftHandSide()), assignment); + } + } + } + + pushContext(); + this.currentContext.currentAssignment = assignment; + + //set the function that contains this assignment + if(this.passNumber == 1 && assignment instanceof Assignment && this.currentContext.currentMethod != null) { + ((Assignment)assignment).setContainingFunction(this.currentContext.currentMethod); + } + + IExpression assignmentExpression = assignment.getExpression(); + if(handlePotentialType(assignment)) { + + } else if(assignmentExpression instanceof FunctionExpression) { + boolean keepVisiting = handleFunctionExpressionAssignment(assignment); + + //set the type on the existing var declaration if it does not already have one set + if(assignment.getInferredType() != null && existingVarDecl != null && existingVarDecl.getInferredType() == null) { + existingVarDecl.setInferredType(assignment.getInferredType()); + } + + if(!keepVisiting) { + return false; + } + } else if(assignmentExpression instanceof SingleNameReference && this.currentContext.currentType != null + && isThis(assignment.getLeftHandSide())) { + + ISingleNameReference snr = (ISingleNameReference) assignmentExpression; + Object object = this.currentContext.getMember(snr.getToken()); + + IFieldReference fieldReference = (IFieldReference) assignment.getLeftHandSide(); + char[] memberName = fieldReference.getToken(); + InferredMember member = null; + + int nameStart = fieldReference.sourceEnd() - memberName.length + 1; + + /* this.foo = bar //bar is a function */ + if(object instanceof MethodDeclaration) { + + MethodDeclaration method = (MethodDeclaration) object; + member = this.currentContext.currentType.addMethod(memberName, method, nameStart); + + } + /* this.foo = bar //assume that bar is not a function and create a new attribute in the + * current type */ + else { + member = this.currentContext.currentType.addAttribute(memberName, assignment, nameStart); + handleAttributeDeclaration((InferredAttribute) member, assignment.getExpression()); + if(((InferredAttribute) member).type == null) + ((InferredAttribute) member).type = getTypeOf(assignmentExpression); + } + + // setting location + if(member != null) { + // this is a not static member because it is being set on the this + member.isStatic = false; + } + } + + // foo = ??; + else if(assignment.getLeftHandSide() instanceof ISingleNameReference) { + char[] variableName = this.getName(assignment); + + /* if there is an existing variable declaration + * else there is not */ + InferredType existingType = null; + + if(existingVarDecl != null) { + existingType = existingVarDecl.getInferredType(); + } else if(existingAssignmentDecl != null) { + existingType = existingAssignmentDecl.getInferredType(); + } + + /* if existing variable declaration does not already have an inferred type + * + * else it does and the new assignment type is different then the currently + * assigned type */ + InferredType type = null; + if(existingType == null) { + type = this.getTypeForVariableInitialization(variableName, assignmentExpression); + + if(this.isExpressionAType(assignmentExpression)) { + assignment.setIsType(true); + } + } else { + InferredType newAssignmentType = this.getTypeOf(assignmentExpression); + if(newAssignmentType != null && existingType != newAssignmentType) { + /* if the existing type is not anonymous, not global and + * existing var is not an argument then create a new + * global anonymous type to mix everything together in + * + * else just use the existing type */ + InferredType newCombinedType = null; + if(!existingType.isAnonymous && !existingType.isGlobal() && !(existingVarDecl instanceof IArgument)) { + if(existingVarDecl instanceof LocalDeclaration && ((LocalDeclaration)existingVarDecl).isLocal()) { + newCombinedType = this.createAnonymousType(existingVarDecl, null); + } else { + newCombinedType = this.createAnonymousGlobalType(variableName); + } + newCombinedType.setIsDefinition(true); + + /* add the original type of the variable declaration to the new combined type + * + * if the existing type is indexed then add it later + * else it is not must add it now */ + if(existingType.isIndexed()) { + newCombinedType.addMixin(existingType.getName()); + } else { + newCombinedType.mixin(existingType); + } + } else { + newCombinedType = existingType; + } + + /* add the type of the new assignment to the combined type + * + * if the existing type is indexed then add it later + * else it is not must add it now */ + if(newAssignmentType.isIndexed()) { + newCombinedType.addMixin(newAssignmentType.getName()); + } else { + newCombinedType.mixin(newAssignmentType); + } + + type = newCombinedType; + } + } + + /* use the new type to set the inferred type on this assignment and + * any existing variable declaration or assignment */ + if(type != null) { + assignment.setInferredType(type); + + if(existingVarDecl != null) { + existingVarDecl.setInferredType(type); + } + + if(existingAssignmentDecl != null) { + existingAssignmentDecl.setInferredType(type); + } + } + + return true; + } + else if(assignmentExpression instanceof AllocationExpression + && ((AllocationExpression) assignmentExpression).member instanceof FunctionExpression) { + + handleFunctionExpressionAssignment(assignment); + } else if(assignmentExpression instanceof Assignment + && ((Assignment) assignmentExpression).expression instanceof FunctionExpression) { + + handleFunctionExpressionAssignment(assignment); + } + else if(this.inferOptions.useAssignments) { + IExpression lhs = assignment.getLeftHandSide(); + + // if foo.bar = ? where ? is not {} and not a function + if(lhs instanceof FieldReference || lhs instanceof ArrayReference) { + + Reference lhsRef = (Reference) lhs; + Expression receiver = null; + char[] attName = null; + int nameStart = 0; + if(lhsRef instanceof FieldReference) { + receiver = ((FieldReference) lhsRef).receiver; + attName = ((FieldReference) lhsRef).token; + nameStart = (int) (((FieldReference) lhsRef).nameSourcePosition >>> 32); + } else if(lhsRef instanceof ArrayReference) { + if(((ArrayReference) lhsRef).position instanceof StringLiteral) { + receiver = ((ArrayReference) lhsRef).receiver; + attName = ((StringLiteral) ((ArrayReference) lhsRef).position).source(); + nameStart = ((StringLiteral) ((ArrayReference) lhsRef).position).sourceStart + 1; + } + } + + //attempt to get receiver type + InferredType receiverType = this.getInferredType(receiver); + + //if not found type yet check if receiver is function + if(receiverType == null) { + IFunctionDeclaration function = getDefinedFunction(receiver); + if(function != null) { + char[] typeName = constructTypeName(receiver); + if(typeName != null) { + receiverType = addType(typeName); + } + } + } + + //all else fails on pass two will possibly create a receiver type + if(receiverType == null && this.passNumber == 2) { + receiverType = this.getReceiverType(receiver, true); + } + + if(receiver != null && receiverType != null && attName != null && attName.length > 0) { + /* if the receiver type is not anonymous and is the expression is not a type then + * create a new anonymous sub type to do the assignment to */ + if(!receiverType.isAnonymous && !this.isExpressionAType(receiver)) { + receiverType = this.createTypeToAssignTo(receiver, receiverType); + this.setTypeOf(receiver, receiverType); + } + + // in the case where the supertype of the reciever is a function, make sure we store the actual function + // for later use + if(receiverType != null && receiverType.getSuperType() != null && receiverType.getSuperType().isFunction()) { + IAbstractVariableDeclaration varDecl = this.getVariable(receiver); + if(varDecl != null) { + IExpression expression = varDecl.getInitialization(); + if(expression != null && expression instanceof IFunctionExpression) { + receiverType.setCorrespondingFunction(((IFunctionExpression)expression).getMethodDeclaration()); + } + } + } + + /* if receiver is instance of type so create new type to assign to + * + * else if receiver is a type then will just assign directly to it, + * and if not anonymous then its a static assignment that type statically */ + boolean isStatic = false; + if(!this.isExpressionAType(receiver)) { + receiverType = this.createTypeToAssignTo(receiver, receiverType); + } else if(!receiverType.isAnonymous && !receiver.isThis()) { + isStatic = true; + } + + // check if there is an attribute or function already created + InferredMethod method = null; + InferredAttribute attr = receiverType.findAttribute(attName); + if(attr == null) { + method = receiverType.findMethod(attName, null); + } else if (this.passNumber == 2) { + handleAttributeDeclaration(attr); + } + + // ignore if the attribute exists and has a type + if((method == null && attr == null) || (method == null && attr != null && attr.type == null)) { + //if type already set on assignment, use that + InferredType rhsType = assignment.getInferredType(); + + // If the RHS is a type then create a type on the LHS + boolean isType = false; + if(rhsType != null && assignment.getInferredType() != null && assignment.isType() && + this.isExpressionAType(receiver) && !receiverType.isAnonymous) { + + isType = true; + + //create new type name + char[] newTypeName = receiverType.getName(); + newTypeName = CharOperation.concat(newTypeName, attName, '.'); + + /* if the RHS type is anonymous just rename it to use the LHS name + * else create new type on the LHS and add it as a synonym of the RHS type */ + if(rhsType.isAnonymous && !rhsType.isGlobal()) { + this.convertAnonymousTypeToNamed(rhsType, newTypeName); + rhsType.setIsDefinition(true); + rhsType.setNameStart(assignment.sourceStart()); + } + else if(!CharOperation.equals(newTypeName, rhsType.getName())){ + InferredType newType = this.addType(newTypeName, true); + rhsType.addSynonym(newType); + } + } + + //if type not found type yet, check if RHS refers to a function definition + IFunctionDeclaration definedFunction = null; + if(rhsType == null) { + definedFunction = this.getDefinedFunction(assignmentExpression); + } + + /* if RHS is a function, add a function to the receiver type + * else add new attribute to receiver type */ + if(definedFunction != null) { + method = receiverType.addMethod(attName, definedFunction, nameStart); + receiverType.setIsDefinition(true); + method.isStatic = isStatic; + } else { + //create the attribute + int nameStart_ = nameStart; + attr = receiverType.addAttribute(attName, assignment, nameStart_); + receiverType.setIsDefinition(true); + this.handleAttributeDeclaration(attr, assignmentExpression); + + //if still not RHS type then get one + if(rhsType == null) { + /* if LHS is global "this" + * else just an attribute on a type */ + if(receiver instanceof IThisReference && + this.currentContext.currentType == this.getInferredGlobal(false)) { + + rhsType = this.getTypeForVariableInitialization(attName, assignmentExpression); + } else { + rhsType = this.getTypeOf(assignmentExpression); + if(receiverType != null && rhsType != null && receiverType.isGlobal() && rhsType.isAnonymous) { + char[] globalAttName = createAnonymousGlobalTypeName(attName); + convertAnonymousTypeToNamed(rhsType, globalAttName); + } + // if the attribute is also a function, add the function using the corresponding function stored earlier + if(rhsType != null && rhsType.getSuperType() != null && rhsType.getSuperType().isFunction() && rhsType.getCorrespondingFunction() != null) { + method = receiverType.addMethod(attName, rhsType.getCorrespondingFunction(), nameStart); + method.isStatic = isStatic; + } + } + } + + //determine if static + char[] possibleTypeName = constructTypeName(receiver); + attr.isStatic = isStatic || (possibleTypeName != null && compUnit.findInferredType(possibleTypeName) != null); + + //assign the type to the attribute + if(attr.type == null || rhsType != null) { + attr.type = rhsType; + attr.setIsType(isType); + } + + //if determined RHS type set it as the inferred type for the assignment + if(rhsType != null) { + assignment.setInferredType(rhsType); + } + } + } else if(method == null && attr != null && attr.type != null && attr.type.getSuperType() != null && attr.type.getSuperType().isFunction() && attr.type.getCorrespondingFunction() != null) { + // if the attribute is also a function, add the function using the cooresponding function stored earlier + method = receiverType.addMethod(attName, attr.type.getCorrespondingFunction(), nameStart); + receiverType.setIsDefinition(true); + method.isStatic = isStatic; + } + } + } + // if foo = ? where ? is not {} and not a function + else { + // no inferred type already set, use the type of the RHS expression + if(assignment.getInferredType() == null) { + InferredType rhsType = this.getTypeOf(assignment.getExpression()); + assignment.setInferredType(rhsType); + } + } + + //only create global type for LHS if LHS's root is global + if(this.isRootGlobal(lhs)) { + // construct the LHS and RHS type names + char[] lhsName = constructTypeName(assignment.getLeftHandSide()); + char[] rhsName = constructTypeName(assignment.getExpression()); + + //if RHS type exists then create LHS type and add it as synonym of the RHS type + if(lhsName != null && lhsName.length > 0 && rhsName != null && rhsName.length > 0) { + InferredType rhsType = this.findDefinedType(rhsName); + + if(rhsType != null) { + InferredType lhsType = this.addType(lhsName, true); + lhsType.setNameStart(lhs.sourceStart()); + + lhsType.addSynonym(rhsType); + } + } + } + } + return true; // do nothing by default, keep traversing + } + + protected InferredType createAnonymousType(char[] possibleTypeName, InferredType currentType) { + char[] name; + if(this.isKnownType(possibleTypeName)) { + name = possibleTypeName; + } else { + char[] cs = String.valueOf(this.anonymousCount++).toCharArray(); + name = CharOperation.concat(ANONYMOUS_PREFIX, possibleTypeName, cs); + } + InferredType type = addType(name, true); + type.isAnonymous = true; + type.setIsGlobal(false); + if(currentType != null) { + type.setSuperType(currentType); + } + + return type; + } + + /** + *

+ * Creates an anonymous type for a given node with an optional parent type. + *

+ * + * @param forNode + * the node to create the anonymous type for, the text range of + * this node will be used to create the anonymous type name + * @param parrentType + * optional parent type of the new anonymous type + * + * @return a new anonymous type + */ + protected InferredType createAnonymousType(IASTNode forNode, InferredType parrentType) { + char[] name = createAnonymousTypeName(forNode); + InferredType type = addType(name, true); + type.isAnonymous = true; + type.setIsGlobal(false); + if(parrentType != null) { + type.setSuperType(parrentType); + } + return type; + } + + /** + * @deprecated - here for compatibility + */ + private InferredType createAnonymousType(IAbstractVariableDeclaration var) { + + InferredType currentType = var.getInferredType(); + + if (currentType==null || !currentType.isAnonymous) + { + InferredType type=createAnonymousType(var, currentType); + var.setInferredType(type); + } + return var.getInferredType(); + } + + /* Creates an anonymous type based in the location in the document. This information is used + * to avoid creating duplicates because of the 2-pass nature of this engine. */ + private InferredType createAnonymousType(IObjectLiteral objLit) { + InferredType anonType = objLit.getInferredType(); + if(anonType == null) { + + char[] name = createAnonymousTypeName(objLit); + anonType = addType(name, true); + anonType.isAnonymous = true; + anonType.isObjectLiteral = true; + anonType.setSuperType(this.getObjectType()); + anonType.setIsGlobal(false); + + anonType.sourceStart = objLit.sourceStart(); + anonType.sourceEnd = objLit.sourceEnd(); + } + + populateType(anonType, objLit, false); + + return anonType; + } + + /** + *

+ * Creates a global anonymous type. + *

+ * + * @param varName + * name of the global variable to create the global anonymous type for + * + * @return a global anonymous type created from for the given global variable name + */ + protected InferredType createAnonymousGlobalType(char[] varName) { + char[] name = createAnonymousGlobalTypeName(varName); + InferredType globalType = this.compUnit.findInferredType(name); + + if(globalType == null) { + globalType = this.addType(name, false); + globalType.isAnonymous = true; + globalType.isObjectLiteral = true; + globalType.setSuperType(this.getObjectType()); + globalType.setIsGlobal(true); + } + + return globalType; + } + + /** + *

+ * Creates an anonymous type name for the given {@link IASTNode} + *

+ * + * @param node + * create the anonymous type name off the location of this node + * @return an anonymous type name based off the given nodes location + */ + protected static char[] createAnonymousTypeName(IASTNode node) { + char[] loc = (String.valueOf(node.sourceStart()) + '_' + String.valueOf(node.sourceEnd())).toCharArray(); + return CharOperation.concat(ANONYMOUS_PREFIX, ANONYMOUS_CLASS_ID, loc); + } + + /** + *

+ * Creates an anonymous type name from the given variable name. + *

+ * + * @param varName + * to use when creating the anonymous type name + * @return + */ + public static char[] createAnonymousGlobalTypeName(char[] varName) { + return CharOperation.concat(CharOperation.concat(ANONYMOUS_PREFIX, ANONYMOUS_CLASS_ID), varName, '_'); + } + + /** + * handle the inferencing for an assignment whose right hand side is a function expression + * + * @param the + * assignment AST node + * @return true if handled + */ + protected boolean handleFunctionExpressionAssignment(IAssignment assignment) { + IFunctionExpression functionExpression = null; + if(assignment.getExpression() instanceof IFunctionExpression) { + functionExpression = (IFunctionExpression) assignment.getExpression(); + } else if(assignment.getExpression() instanceof IAllocationExpression) { + functionExpression = (IFunctionExpression) ((IAllocationExpression) assignment.getExpression()).getMember(); + } else if(assignment.getExpression() instanceof IAssignment) { + functionExpression = (FunctionExpression) ((IAssignment) assignment.getExpression()).getExpression(); + } + + if (functionExpression == null) { + return false; + } + + MethodDeclaration methodDeclaration = functionExpression.getMethodDeclaration(); + + char[] possibleTypeName = constructTypeName(assignment.getLeftHandSide()); + + InferredType type = null; + if(possibleTypeName != null) { + type = compUnit.findInferredType(possibleTypeName); + if(type == null && isPossibleClassName(possibleTypeName)) { + type = addType(possibleTypeName, true); + } + if(type == null && methodDeclaration.getJsDoc() != null + && ((Javadoc) methodDeclaration.getJsDoc()).isConstructor) { + type = addType(possibleTypeName, true); + handleJSDocConstructor(type, methodDeclaration, assignment.sourceStart()); + } + } + + // isConstructor + if(type != null) { + if(this.inferOptions.useInitMethod) { + this.currentContext.currentType = type; + int nameStart = assignment.getLeftHandSide().sourceStart(); + int expressionEnd = assignment.getExpression().sourceEnd(); + handleConstructor(type, methodDeclaration, nameStart, expressionEnd); + + // want to be sure to set the type of the assignment and local declaration if there is one + assignment.setInferredType(type); + if(this.currentContext.currentLocalDeclaration != null && CharOperation.equals(this.currentContext.currentLocalDeclaration.getName(), getName(assignment))) { + this.currentContext.currentLocalDeclaration.setInferredType(type); + } + + // constructor is actually an anonymous function assigned to a single name + methodDeclaration.setIsAnonymous(true); + } + } else {// could be method + if(assignment.getLeftHandSide() instanceof FieldReference + || assignment.getLeftHandSide() instanceof ArrayReference) { + + Reference ref = (Reference) assignment.getLeftHandSide(); + Expression receiver = null; + char[] methodName = null; + int nameStart = 0; + if(ref instanceof FieldReference) { + receiver = ((FieldReference) ref).receiver; + methodName = ((FieldReference) ref).token; + nameStart = (int) (((FieldReference) ref).nameSourcePosition >>> 32); + } else if(ref instanceof ArrayReference) { + if(((ArrayReference) ref).position instanceof StringLiteral) { + receiver = ((ArrayReference) ref).receiver; + methodName = ((StringLiteral) ((ArrayReference) ref).position).source(); + nameStart = ((StringLiteral) ((ArrayReference) ref).position).sourceStart + 1; + } + } + + //if no receiver then done + if(receiver == null) { + return false; + } + + InferredType receiverType = getInferredType(receiver); + if(receiverType == null && passNumber == 2) { + receiverType = this.getReceiverType(receiver, true); + } + + if(receiverType != null && methodName != null) { + if(!receiver.isThis()) { + receiverType = this.createTypeToAssignTo(receiver, receiverType); + } + + // check if there is a member method already created + InferredMethod method = receiverType.findMethod(methodName, methodDeclaration); + + if(method == null) { + // create member method if it does not exist + method = receiverType.addMethod(methodName, methodDeclaration, nameStart); + receiverType.setIsDefinition(true); + + /* determine if static + * check if the receiver is a type */ + char[] possibleInTypeName = constructTypeName(receiver); + method.isStatic = (possibleInTypeName != null && compUnit.findInferredType(possibleInTypeName) != null); + + return true; // keep visiting to get return type + } else if(this.passNumber == 2) { + return false; // no need to visit again + } + + } else if(this.passNumber == 2 && methodName != null) { // create anonymous class + receiverType = this.getReceiverType(receiver, false); + if(receiverType != null) { + InferredMethod method = receiverType.addMethod(methodName, methodDeclaration, nameStart); + method.isStatic = !receiverType.isObjectLiteral; + receiverType.updatePositions(assignment.sourceStart(), assignment.sourceEnd()); + } + } + } else if(assignment.getLeftHandSide() instanceof SingleNameReference && this.passNumber == 2) { + // set the inferred type + assignment.setInferredType(getTypeOf(assignment.getExpression())); + + methodDeclaration.setIsAnonymous(true); + methodDeclaration.setSelector(((SingleNameReference) assignment.getLeftHandSide()).token); + methodDeclaration.sourceStart = (((SingleNameReference) assignment.getLeftHandSide()).sourceStart()); + } + } + return true; + } + + /** + *

+ * Handle a local declaration who's right hand side is a function. + *

+ *

+ * Use case: + *

+ * + *
+	 * foo.bar.Test = function() { this.num = 42; }
+	 * 
+ * + * @param localDeclaration + * {@link ILocalDeclaration} to attempt to infer a type from + * @return true if keep visiting, false otherwise. + */ + private boolean handleFunctionExpressionLocalDeclaration(ILocalDeclaration localDeclaration) { + boolean keepVisiting = true; + IFunctionExpression functionExpression = null; + IExpression expression = localDeclaration.getInitialization(); + if(expression instanceof IFunctionExpression) { + functionExpression = (IFunctionExpression) expression; + } else if(expression instanceof IAllocationExpression) { + functionExpression = (IFunctionExpression) ((IAllocationExpression) expression).getMember(); + } else if(expression instanceof IAssignment) { + functionExpression = (FunctionExpression) ((IAssignment) expression).getExpression(); + } + + if (functionExpression == null) { + return false; + } + + MethodDeclaration methodDeclaration = functionExpression.getMethodDeclaration(); + char[] possibleTypeName = localDeclaration.getName(); + + InferredType type = null; + if(possibleTypeName != null) { + type = compUnit.findInferredType(possibleTypeName); + if(type == null && isPossibleClassName(possibleTypeName)) { + type = addType(possibleTypeName, true); + } + if(type == null && methodDeclaration.getJsDoc() != null + && ((Javadoc) methodDeclaration.getJsDoc()).isConstructor) { + + type = addType(possibleTypeName, true); + handleJSDocConstructor(type, methodDeclaration, localDeclaration.sourceStart()); + } + } + + if(type != null) { // isConstructor + if(this.inferOptions.useInitMethod) { + this.currentContext.currentType = type; + type.setIsDefinition(true); + int nameStart = localDeclaration.sourceStart(); + type.addConstructorMethod(type.name, methodDeclaration, nameStart); + type.updatePositions(nameStart, localDeclaration.getInitialization().sourceEnd()); + + //set the type for the local declaration to be the new type + localDeclaration.setInferredType(type); + localDeclaration.setIsType(true); + } + + keepVisiting = false; + } + return keepVisiting; + } + + /** + * @param assignment + * @return whether a type was not created for this assignment + */ + protected boolean handlePotentialType(IAssignment assignment) { + + IExpression lhs = assignment.getLeftHandSide(); + if(lhs instanceof FieldReference) { + FieldReference fieldReference = (FieldReference) lhs; + + /* foo.prototype = ? */ + if(fieldReference.isPrototype()) { + /* When encountering a prototype, we are going to assume that the + * receiver is a type. + * + * If the type had not been inferred, it will be added at this point */ + InferredType newType = null; + char[] possibleTypeName = constructTypeName(fieldReference.getReceiver()); + if(possibleTypeName != null) + newType = compUnit.findInferredType(possibleTypeName); + else + return true; // no type created + + // create the new type if not found + if(newType == null) { + // if we have the function, check if it has a return type, if so, don't consider it a new type + IAbstractFunctionDeclaration theFunction = this.getFunction(fieldReference.getReceiver()); + IAbstractVariableDeclaration theVariable = null; + if(theFunction == null) + theVariable = this.getVariable(fieldReference.getReceiver()); + if(theFunction != null) { + if(theFunction.getInferredType() != null && !theFunction.getInferredType().isVoid()) { + return false; + } + } else if (theVariable != null) { + if(theVariable.getInitialization() != null && theVariable.getInitialization() instanceof IFunctionExpression) { + if(((IFunctionExpression)theVariable.getInitialization()).getMethodDeclaration().getInferredType() != null && + !((IFunctionExpression)theVariable.getInitialization()).getMethodDeclaration().getInferredType().isVoid()) { + return false; + } + } + } + newType = addType(possibleTypeName, true); + } + newType.setIsDefinition(true); + newType.updatePositions(assignment.sourceStart(), assignment.sourceEnd()); + + /* foo.prototype = new ... */ + if(assignment.getExpression() instanceof IAllocationExpression) { + // setting the super type + IAllocationExpression allocationExpression = (IAllocationExpression) assignment.getExpression(); + + InferredType superType = null; + char[] possibleSuperTypeName = constructTypeName(allocationExpression.getMember()); + if(possibleSuperTypeName != null) { + superType = compUnit.findInferredType(possibleSuperTypeName); + + if(superType == null) + superType = addType(possibleSuperTypeName); + + // check if it is set already because it might be set by jsdocs + if(newType.getSuperType() == null) + newType.setSuperType(superType); + } + + return true; + } + /* foo.prototype = {...} */ + else if(assignment.getExpression() instanceof IObjectLiteral) { + // rather than creating an anonymous type, is better just to set the members + // directly + // on newType + populateType(newType, (IObjectLiteral) assignment.getExpression(), false); + + // check if it is set already because it might be set by jsdocs + if(newType.getSuperType() == null) + newType.setSuperType(this.getObjectType()); + + return true; + } + /* foo.prototype = foo.someField; */ + else if(assignment.getExpression() instanceof FieldReference) { + InferredType superType = getTypeOf(assignment.getExpression()); + if(newType.getSuperType() == null && superType != null) { + newType.setSuperType(superType); + } + return true; + } + /* foo.prototype = somevar; */ + else if(assignment.getExpression() instanceof SingleNameReference) { + InferredType superType = getTypeOf(assignment.getExpression()); + if (newType.getSuperType() == null && superType != null) { + newType.setSuperType(superType); + } + return true; + } + } + /* foo.prototype.bar = ? */ + else if(fieldReference.receiver.isPrototype() ) { + + FieldReference prototype = (FieldReference) fieldReference.receiver; + + //if prototype receiver is a type, get its type + InferredType assignedToType = null; + if(this.isExpressionAType(prototype.receiver)) { + assignedToType = this.getTypeOf(prototype.receiver); + } + + //if not found assigned to type and can create possible name, then create a type + if(assignedToType == null) { + char[] possibleTypeName = constructTypeName(prototype.receiver); + + if(possibleTypeName != null) { + assignedToType = addType(possibleTypeName); + assignedToType.updatePositions(assignment.sourceStart(), assignment.sourceEnd()); + assignedToType.setIsDefinition(true); + } else { + return true; // can not create type, keep visiting + } + } + + // prevent Object literal based anonymous types from being created more than once + if(passNumber == 1 && assignment.getExpression() instanceof IObjectLiteral) { + return false; + } + + char[] memberName = fieldReference.token; + int nameStart = (int) (fieldReference.nameSourcePosition >>> 32); + + InferredType typeOf = + (assignment.getJsDoc() != null && assignment.getJsDoc() instanceof Javadoc && ((Javadoc) assignment.getJsDoc()).returnType != null) ? this.addType(changePrimitiveToObject(((Javadoc) assignment.getJsDoc()).returnType.getFullTypeName())) + : getTypeOf(assignment.getExpression()); + IFunctionDeclaration methodDecl = null; + + if(typeOf == null || typeOf == this.getFunctionType()) + methodDecl = getDefinedFunction(assignment.getExpression()); + + if(methodDecl != null) { + assignedToType.addMethod(memberName, methodDecl, nameStart); + } else { + InferredAttribute attribute = assignedToType.addAttribute(memberName, assignment, nameStart); + handleAttributeDeclaration(attribute, assignment.getExpression()); + attribute.initializationStart = assignment.getExpression().sourceStart(); + if(attribute.type == null) + attribute.type = typeOf; + } + return true; + } + /* this.foo = ? */ + else if(fieldReference.receiver instanceof IThisReference) { + InferredType newType = null; + + IFunctionDeclaration parentMethod = this.currentContext.currentMethod; + IAssignment parentAssignment = this.currentContext.parent.currentAssignment; + ILocalDeclaration parentLocalDeclaration = this.currentContext.parent.currentLocalDeclaration; + char[] newTypeName = null; + int typeStart = 0; + int typeEnd = 0; + /* if there is a current assignment and LHS is a function and that function + * is the current method then use the RHS as the type name + * + * else if there is a current local declaration and the LHS is a function and + * that function is the current method then use the RHS as the type name + * + * else if the parent method is not in a type and has a name use that as the type + * name */ + if(this.currentContext.parent != null + && parentAssignment != null + && parentAssignment.getExpression() instanceof IFunctionExpression + && ((IFunctionExpression) parentAssignment.getExpression()).getMethodDeclaration() == parentMethod) { + // see if we're adding a field through the prototype + if (parentAssignment.getLeftHandSide().getASTType() == IASTNode.FIELD_REFERENCE + && ((Expression) ((IFieldReference) parentAssignment.getLeftHandSide()).getReceiver()).isPrototype()) { + newTypeName = Util.getTypeName(((IFieldReference) ((IFieldReference) parentAssignment.getLeftHandSide()).getReceiver()).getReceiver()); + } + else { + newTypeName = Util.getTypeName(parentAssignment.getLeftHandSide()); + } + typeStart = parentAssignment.sourceStart(); + typeEnd = parentAssignment.sourceEnd(); + } else if(this.currentContext.parent != null + && parentLocalDeclaration != null + && parentLocalDeclaration.getInitialization() instanceof IFunctionExpression + && ((IFunctionExpression) parentLocalDeclaration.getInitialization()).getMethodDeclaration() == parentMethod) { + + newTypeName = parentLocalDeclaration.getName(); + typeStart = parentLocalDeclaration.sourceStart(); + typeEnd = parentLocalDeclaration.sourceEnd(); + } else if(parentMethod != null + && parentMethod.getName() != null + && (parentMethod.getInferredMethod() == null || parentMethod.getInferredMethod().inType == null)) { + + newTypeName = parentMethod.getName(); + typeStart = parentMethod.sourceStart(); + typeEnd = parentMethod.sourceEnd(); + } + + // if calculated new type name, use it to create a new type + if(newTypeName != null) { + newType = compUnit.findInferredType(newTypeName); + // create the new type if not found + if(newType == null) { + newType = addType(newTypeName); + } + } else { + return false; // no type to create + } + + newType.setIsDefinition(true); + newType.updatePositions(typeStart, typeEnd); + + //if there is a parent assignment then set the inferred type and that it is a type + if(parentAssignment != null) { + parentAssignment.setInferredType(newType); + parentAssignment.setIsType(true); + } + + //if there is a parent declaration then set the inferred type and that it is a type + if(parentLocalDeclaration != null) { + parentLocalDeclaration.setInferredType(newType); + parentLocalDeclaration.setIsType(true); + } + + // prevent Object literal based anonymous types from being created more than once + if(passNumber == 1 && assignment.getExpression() instanceof IObjectLiteral) { + return false; + } + + char[] memberName = fieldReference.token; + int nameStart = (int) (fieldReference.nameSourcePosition >>> 32); + + InferredType typeOf = getTypeOf(assignment.getExpression()); + IFunctionDeclaration methodDecl = null; + + if(typeOf == null || typeOf == this.getFunctionType()) { + methodDecl = getDefinedFunction(assignment.getExpression()); + } + + if(methodDecl != null) { + newType.addMethod(memberName, methodDecl, nameStart); + if(methodDecl.getInferredType() == null && assignment.getJsDoc() != null + && ((Javadoc) assignment.getJsDoc()).returnType != null) { + if(((Javadoc) assignment.getJsDoc()).returnType.getFullTypeName() != null) + methodDecl.setInferredType(addType(((Javadoc) assignment.getJsDoc()).returnType.getFullTypeName())); + } + } else { + InferredAttribute attribute = newType.addAttribute(memberName, assignment, nameStart); + if(attribute.type == null && assignment.getJsDoc() != null + && ((Javadoc) assignment.getJsDoc()).returnType != null) { + if(((Javadoc) assignment.getJsDoc()).returnType.getFullTypeName() != null) + attribute.type = addType(((Javadoc) assignment.getJsDoc()).returnType.getFullTypeName()); + } + handleAttributeDeclaration(attribute, assignment.getExpression()); + attribute.initializationStart = assignment.getExpression().sourceStart(); + if(attribute.type == null) + attribute.type = typeOf; + } + return true; + } + } + return false; + } + + /** + * Get the function referenced by the expression + * + * @param expression + * AST node + * @return the function or null + */ + protected IFunctionDeclaration getDefinedFunction(IExpression expression) { + if(expression instanceof SingleNameReference) { + Object object = this.currentContext.getMember(((SingleNameReference) expression).token); + if(object instanceof AbstractMethodDeclaration) { + return (MethodDeclaration) object; + } + } else if(expression instanceof FunctionExpression) { + return ((FunctionExpression) expression).methodDeclaration; + } else if(expression instanceof FieldReference) { + FieldReference fieldReference = (FieldReference) expression; + InferredType receiverType = getInferredType(fieldReference.receiver); + if(receiverType == null && passNumber == 2) { + receiverType = this.getReceiverType(fieldReference.receiver, false); + } + if(receiverType != null) { + InferredMethod method = receiverType.findMethod(fieldReference.token, null); + if(method != null) { + return method.getFunctionDeclaration(); + } + } + + } + + return null; + + } + + /** + *

+ * Sets the inferred type of the given expression to the given type. Any existing inferred type + * is overridden. If the given expression is not supported by this method then it is a no op. + *

+ * + *

+ * Currently supports: + *

    + *
  • {@link ISingleNameReference}
  • + *
  • {@link FieldReference} - if it can resolve everything it needs to
  • + *
  • {@link IObjectLiteral}
  • + *
  • {@link IThisReference}
  • + *
+ *

+ * + * @param expression + * to set the inferred type for + * @param type + * inferred type to set on the given expression + */ + protected void setTypeOf(IExpression expression, InferredType type) { + if(expression instanceof ISingleNameReference) { + //set on variable declaration if there is one + IAbstractVariableDeclaration varDecl = getVariable(expression); + if(varDecl != null) { + varDecl.setInferredType(type); + } + + //set on global field if there is one + if(this.inferredGlobal != null) { + InferredAttribute attribute = + this.inferredGlobal.findAttribute(((ISingleNameReference) expression).getToken()); + if(attribute != null) { + attribute.type = type; + } + } + + //set on assignment if there is one + IAssignment varAssignment = this.getAssignment(expression); + if(varAssignment != null) { + varAssignment.setInferredType(type); + } + } else if(expression instanceof FieldReference) { + FieldReference fieldReference = (FieldReference) expression; + InferredType parentType = this.getTypeOf(fieldReference.getReceiver()); + if(parentType != null) { + InferredAttribute attr = parentType.findAttribute(fieldReference.token); + if(attr != null) { + attr.type = type; + } + } + } else if(expression instanceof IObjectLiteral) { + ((IObjectLiteral) expression).setInferredType(type); + } else if(expression instanceof IThisReference) { + this.currentContext.currentType = type; + } + } + + protected InferredType getTypeOf(IExpression expression) { + if(expression instanceof IStringLiteral) { + return this.getStringType(); + } else if(expression instanceof INumberLiteral) { + return this.getNumberType(); + } else if(expression instanceof IAllocationExpression) { + IAllocationExpression allocationExpression = (IAllocationExpression) expression; + IExpression member = allocationExpression.getMember(); + InferredType type = null; + + //check for type with the same name as the allocation member + char[] possibleTypeName = constructTypeName(member); + if(possibleTypeName != null) { + type = compUnit.findInferredType(possibleTypeName); + + } + + /* if no existing type with the same name as the allocation member + * attempt to get the type of the member */ + if(type == null) { + type = this.getTypeOf(member); + } + + /* if no type with same name as member, and member does not have a type, + * create a new type with the same name as the member */ + if((type == null || type == getFunctionType()) && possibleTypeName != null && possibleTypeName.length > 0) { + type = this.addType(possibleTypeName, false); + } + + return type; + } else if(expression instanceof ISingleNameReference) { + //check for variable declaration to get type from + IAbstractVariableDeclaration varDecl = this.getVariable(expression); + if(varDecl != null) { + return varDecl.getInferredType(); + } + + //check global type to get type from + if(this.inferredGlobal != null) { + InferredAttribute attribute = + this.inferredGlobal.findAttribute(((ISingleNameReference) expression).getToken()); + if(attribute != null) { + return attribute.type; + } + } + + //check for an assignment to get the type from + IAssignment assign = this.getAssignment(expression); + if(assign != null) { + InferredType type = assign.getInferredType(); + if(type != null) { + return type; + } + } + + /* check if expression is a function and if there is a type with the same name, + * if so then the given expression is a reference to that type */ + IAbstractFunctionDeclaration funcDecl = this.getFunction(expression); + if(funcDecl != null) { + InferredType type = this.findDefinedType(funcDecl.getName()); + if(type != null) { + return type; + } + } + + //search for type with that name + char[] possibleTypeName = this.constructTypeName(expression); + if(possibleTypeName != null) { + InferredType type = compUnit.findInferredType(possibleTypeName); + if(type != null) { + return type; + } + } + + //search for anonymous global type based of SNR + char[] possibleGlobalTypeName = createAnonymousGlobalTypeName(((SingleNameReference)expression).token); + if(possibleGlobalTypeName != null) { + InferredType type = compUnit.findInferredType(possibleGlobalTypeName); + if(type != null) { + return type; + } + } + if(funcDecl != null) { + return getFunctionType(); + } + } else if(expression instanceof FieldReference) { + FieldReference fieldReference = (FieldReference) expression; + /* if this reference and in current type + * else not */ + if(fieldReference.receiver.isThis() && currentContext.currentType != null) { + InferredAttribute attribute = currentContext.currentType.findAttribute(fieldReference.getToken()); + if(attribute != null) { + return attribute.type; + } + } else { + //get the receiver type then get the type of an existing field or function + InferredType recieverType = this.getReceiverType(((FieldReference) expression).getReceiver(), false); + if(recieverType != null) { + char[] fieldName = ((FieldReference) expression).getToken(); + InferredAttribute attr = recieverType.findAttribute(fieldName); + if(attr != null) { + return attr.type; + } else if(recieverType.findMethod(fieldName, null) != null){ + return this.getFunctionType(); + } + } + } + + char[] typeName = constructTypeName(expression); + if(typeName != null && typeName.length > 0) { + InferredType type = this.findDefinedType(typeName); + if(type != null) { + return type; + } + } + } else if(expression instanceof IReturnStatement) { + return ((IReturnStatement) expression).getInferredType(); + } else if(expression instanceof ArrayInitializer) { + ArrayInitializer arrayInitializer = (ArrayInitializer) expression; + boolean typeSet = false; + InferredType memberType = null; + if(arrayInitializer.expressions != null) + for(int i = 0; i < arrayInitializer.expressions.length; i++) { + InferredType thisType = getTypeOf(arrayInitializer.expressions[i]); + if(thisType != null) { + if(!thisType.equals(memberType)) + if(!typeSet) { + memberType = thisType; + } else { + memberType = null; + } + typeSet = true; + + } + } + if(memberType != null) { + InferredType type = new InferredType(InferredType.ARRAY_NAME); + type.referenceClass = memberType; + return type; + } else { + return this.getArrayType(); + } + } else if(expression instanceof ITrueLiteral || expression instanceof IFalseLiteral) { + return this.getBooleanType(); + } else if(expression instanceof IObjectLiteral) { + + // create an anonymous type based on the ObjectLiteral + InferredType type = createAnonymousType((IObjectLiteral) expression); + + // set the start and end + type.sourceStart = expression.sourceStart(); + type.sourceEnd = expression.sourceEnd(); + + return type; + } else if(expression instanceof IThisReference) { + return this.currentContext.currentType != null ? this.currentContext.currentType : getInferredGlobal(true); + } else if(expression instanceof Assignment) + return getTypeOf(((Assignment) expression).getExpression()); + else if(expression instanceof FunctionExpression) + return this.getFunctionType(); + else if(expression instanceof UnaryExpression) { + return getTypeOf(((UnaryExpression) expression).expression); + } else if(expression instanceof BinaryExpression) { + BinaryExpression bExpression = (BinaryExpression) expression; + int operator = (bExpression.bits & ASTNode.OperatorMASK) >> ASTNode.OperatorSHIFT; + switch(operator) { + case OperatorIds.MULTIPLY: + case OperatorIds.DIVIDE: + case OperatorIds.REMAINDER: + case OperatorIds.MINUS: + case OperatorIds.LEFT_SHIFT: + case OperatorIds.RIGHT_SHIFT: + return this.getNumberType(); + case OperatorIds.PLUS: { + InferredType leftType = getTypeOf(bExpression.left); + InferredType rightType = getTypeOf(bExpression.right); + if(leftType != null && leftType.equals(this.getStringType())) { + return this.getStringType(); + } + if(rightType != null && rightType.equals(this.getStringType())) { + return this.getStringType(); + } + if(leftType == null || rightType == null) { + return null; + } + if(leftType.equals(this.getStringType()) || rightType.equals(this.getStringType())) { + return this.getStringType(); + } else if(leftType.equals(this.getNumberType()) && rightType.equals(this.getNumberType())) { + return this.getNumberType(); + } + return null; + } + case OperatorIds.AND_AND: + case OperatorIds.OR_OR: { + /* if the case: + * foo = foo || "" + * return foo || "" + * foo = foo && "" + * return foo || "" + * else a normal || binary case */ + if((this.currentContext.currentAssignment != null && expressionContains(this.currentContext.currentAssignment.getExpression(), bExpression)) || + (this.currentContext.currentLocalDeclaration != null && expressionContains(this.currentContext.currentLocalDeclaration.getInitialization(), bExpression)) || + (this.currentContext.currentReturn != null && expressionContains(this.currentContext.currentReturn.getExpression(), bExpression))) { + + InferredType leftType = this.getTypeOf(bExpression.left); + InferredType rightType = this.getTypeOf(bExpression.right); + + /* if both the left and right type are the same then just return the left one + * else merge the two types into one type + */ + if(leftType == rightType) { + return leftType; + } else if(leftType != null && rightType != null) { + InferredType newCombinedType = this.createAnonymousType(expression, null); + + /* add the left type to the combined type + * + * if the left type is indexed then add it later + * else it is not must add it now */ + if(leftType.isIndexed()) { + newCombinedType.addMixin(leftType.getName()); + } else { + newCombinedType.mixin(leftType); + } + + /* add the right type to the combined type + * + * if the right type is indexed then add it later + * else it is not must add it now */ + if(rightType.isIndexed()) { + newCombinedType.addMixin(rightType.getName()); + } else { + newCombinedType.mixin(rightType); + } + + return newCombinedType; + } else if(leftType != null) { + return leftType; + } else if(rightType != null) { + return rightType; + } + } + + return this.getBooleanType(); + } + case OperatorIds.EQUAL_EQUAL: + case OperatorIds.EQUAL_EQUAL_EQUAL: + case OperatorIds.NOT_EQUAL: + case OperatorIds.NOT_EQUAL_EQUAL: + case OperatorIds.GREATER: + case OperatorIds.GREATER_EQUAL: + case OperatorIds.LESS: + case OperatorIds.LESS_EQUAL: + case OperatorIds.INSTANCEOF: + case OperatorIds.IN: + return this.getBooleanType(); + default: + return null; + } + } else if(expression instanceof MessageSend) { + if(((MessageSend)expression).receiver instanceof IFunctionExpression) { + if(((FunctionExpression)((MessageSend)expression).receiver).methodDeclaration != null) { + return ((FunctionExpression)((MessageSend)expression).receiver).methodDeclaration.inferredType; + } + } else if(((MessageSend)expression).selector != null) { + // if the method call has no receiver, see if we can look it up + // in the current context. If found, the inferredType(return type) of + // that function is the value we are looking for. + Object method = this.currentContext.getMember(((MessageSend)expression).selector); + if(method instanceof MethodDeclaration) { + return ((MethodDeclaration) method).inferredType; + } + } + } + + return null; + } + + protected void populateType(InferredType type, IObjectLiteral objLit, boolean isStatic) { + if(objLit.getInferredType() == null) { + objLit.setInferredType(type); + if(objLit.getFields() != null) { + for(int i = 0; i < objLit.getFields().length; i++) { + IObjectLiteralField field = objLit.getFields()[i]; + + char[] name = null; + int nameStart = -1; + + if(field.getFieldName() instanceof SingleNameReference) { + SingleNameReference singleNameReference = (SingleNameReference) field.getFieldName(); + name = singleNameReference.token; + nameStart = singleNameReference.sourceStart; + } else if(field.getFieldName() instanceof IStringLiteral) { + IStringLiteral stringLiteral = (IStringLiteral) field.getFieldName(); + name = stringLiteral.source(); + nameStart = stringLiteral.sourceStart(); + } else + continue; // not supporting this case right now + + Javadoc javaDoc = (Javadoc) field.getJsDoc(); + InferredType returnType = null; + if(javaDoc != null) { + if(javaDoc.memberOf != null) { + char[] typeName = javaDoc.memberOf.getFullTypeName(); + convertAnonymousTypeToNamed(type, typeName); + type.setIsDefinition(true); + } else if(this.currentContext.isJsDocClass && javaDoc.property != null) { + if(type.isAnonymous) { + InferredType previousType = this.currentContext.currentType; + if(previousType != null) { + copyAnonymousTypeToNamed(type, previousType); + objLit.setInferredType(type = this.currentContext.currentType = previousType); + } + + } + } + if(javaDoc.returnType != null) { + returnType = this.addType(changePrimitiveToObject(javaDoc.returnType.getFullTypeName())); + } + } + + // need to build the members of the anonymous inferred type + if(field.getInitializer() instanceof IFunctionExpression) { + IFunctionExpression functionExpression = (IFunctionExpression) field.getInitializer(); + InferredMember method = + type.addMethod(name, functionExpression.getMethodDeclaration(), nameStart); + method.isStatic = isStatic; + if(javaDoc != null) { + functionExpression.getMethodDeclaration().modifiers = javaDoc.modifiers; + } + handleFunctionDeclarationArguments(functionExpression.getMethodDeclaration(), javaDoc); + if(returnType != null && functionExpression.getMethodDeclaration().getInferredType() == null) { + functionExpression.getMethodDeclaration().setInferredType(returnType); + } + + } + // attribute + else if (field.getInitializer() != null) { + InferredAttribute attribute = type.findAttribute(name); + if(attribute == null) { + attribute = type.addAttribute(name, field.getInitializer(), nameStart); + handleAttributeDeclaration(attribute, field.getInitializer()); + attribute.isStatic = isStatic; + // @GINO: recursion might not be the best idea + if(returnType != null) { + attribute.type = returnType; + // apply (force) type onto OL initializer + if(field.getInitializer() instanceof ObjectLiteral) { + ((ObjectLiteral) field.getInitializer()).setInferredType(returnType); + } + } else { + attribute.type = getTypeOf(field.getInitializer()); + } + + + } + + //if attribute is function then create a function as well + if(attribute.type != null && attribute.type.isFunction()) { + if( type.findMethod(attribute.name, null) == null) { + IAbstractFunctionDeclaration func = this.getFunction(field.getInitializer()); + if(func instanceof IFunctionDeclaration) { + type.addMethod(name, (IFunctionDeclaration)func, nameStart); + } + } + } + } + } + } + } + } + + public void endVisit(IAssignment assignment) { + popContext(); + } + + protected boolean handleAttributeDeclaration(InferredAttribute attribute) { + return true; + } + + protected boolean handleAttributeDeclaration(InferredAttribute attribute, IExpression initializer) { + return true; + } + + protected boolean handleFunctionCall(IFunctionCall messageSend) { + return handleFunctionCall(messageSend, null); + } + + protected boolean handleFunctionCall(IFunctionCall messageSend, LocalDeclaration assignmentExpression) { + return true; + } + + public boolean visit(IReturnStatement returnStatement) { + this.pushContext(); + this.currentContext.currentReturn = returnStatement; + + if(currentContext.currentMethod != null) { + if(returnStatement.getExpression() != null) { + + InferredType type = null; + IExpression expression = returnStatement.getExpression(); + if(expression instanceof IObjectLiteral) { + type = createAnonymousType((ObjectLiteral) expression); + + // set the start and end + type.sourceStart = expression.sourceStart(); + type.sourceEnd = expression.sourceEnd(); + } else { + type = getTypeOf(expression); + } + if(currentContext.currentMethod.getInferredType() == this.getVoidType() && type != null) { + currentContext.currentMethod.setInferredType(type); + } else if(currentContext.currentMethod.getInferredType() == this.getArrayType() + && currentContext.currentMethod.getInferredType().referenceClass == null + && type != null && CharOperation.equals(type.name, TypeConstants.ARRAY[0])){ + currentContext.currentMethod.setInferredType(type); + } else { + /* If the return statement inferred type is null or + * the existing inferred return type and the statement return type are not + * equal and the return type is either not well known or is well + * known and the return type names are the same + * + * This logic is to cover the scenario where the return type is a known type but + * is from a different instance of the InferEngine */ + boolean shouldSetToAny = !((MethodDeclaration) currentContext.currentMethod).isInferredJsDocType(); + if(type != null && shouldSetToAny) { + // get the name of the current methods inferred return type + String currentMethodInferredType = null; + if(this.currentContext.currentMethod.getInferredType() != null + && this.currentContext.currentMethod.getInferredType().name != null) { + currentMethodInferredType = + new String(this.currentContext.currentMethod.getInferredType().name); + } + + boolean returnTypesEqual = type.equals(currentContext.currentMethod.getInferredType()); + boolean returnTypeNamesEqual = (new String(type.name)).equals(currentMethodInferredType); + boolean returnTypeIsWellKnown = WellKnownTypes.containsKey(type.name); + + shouldSetToAny = + !returnTypesEqual + && (!returnTypeIsWellKnown || !(returnTypeIsWellKnown && returnTypeNamesEqual)); + } + + if(shouldSetToAny) { + currentContext.currentMethod.setInferredType(null); + } + } + } + } + return false; + } + + /** + * @see org.eclipse.wst.jsdt.core.ast.ASTVisitor#endVisit(org.eclipse.wst.jsdt.core.ast.IReturnStatement) + */ + public void endVisit(IReturnStatement returnStatement) { + this.popContext(); + } + + /* (non-Javadoc) + * @see org.eclipse.wst.jsdt.core.ast.ASTVisitor#endVisit(org.eclipse.wst.jsdt.core.ast.IFunctionCall) + */ + public void endVisit(IFunctionCall functionCall) { + super.endVisit(functionCall); + + if(functionCall.getReceiver() instanceof FunctionExpression) { + if (this.contextPtr == -1) { + this.isTopLevelAnonymousFunction = true; + } + if (functionCall instanceof MessageSend && ((MessageSend) functionCall).getArguments() != null) { + MethodDeclaration methodDeclaration = ((FunctionExpression) functionCall.getReceiver()).getMethodDeclaration(); + if (methodDeclaration != null && methodDeclaration.getArguments() != null) { + IArgument[] declaredArguments = methodDeclaration.getArguments(); + IExpression[] sentArguments = ((MessageSend) functionCall).getArguments(); + for (int i = 0; i < declaredArguments.length; i++) { + if (i >= sentArguments.length) { + continue; + } + // if a sent argument now is a subtype of the declared argument, update the sent argument to be the type of the declared argument + char[] parameterName = null; + if ((parameterName = getName(sentArguments[i])) != null && passNumber == 2 && declaredArguments[i].getInferredType()!=null) { + IASTNode node = (IASTNode) currentContext.getMember(parameterName); + if (node instanceof IAbstractVariableDeclaration && ((IAbstractVariableDeclaration) node).getInferredType() != null) { + if (((IAbstractVariableDeclaration) node).getInferredType().isNamed() && ((LocalDeclaration) node).getInferredType().equals(declaredArguments[i].getInferredType().getSuperType())) { + ((IAbstractVariableDeclaration) node).setInferredType(declaredArguments[i].getInferredType()); + } + } + else if (node instanceof IAssignment && ((IAssignment) node).getInferredType() != null) { + if (((IAssignment) node).getInferredType().isNamed() && ((IAssignment) node).getInferredType().equals(declaredArguments[i].getInferredType().getSuperType())) { + ((IAssignment) node).setInferredType(declaredArguments[i].getInferredType()); + } + } + } + } + } + } + } + } + + public void endVisit(IFunctionDeclaration methodDeclaration) { + popContext(); + } + + public boolean visit(IFunctionDeclaration methodDeclaration) { + pushContext(); + if(this.isTopLevelAnonymousFunction && this.currentContext.currentType == null) { + this.currentContext.currentType = this.getInferredGlobal(true); + } else if(!this.isTopLevelAnonymousFunction && this.currentContext.currentType != null && CharOperation.equals(this.currentContext.currentType.getName(), IIndexConstants.GLOBAL_SYMBOL)) { + // if we are not a top level function and the current type is global, reset it to null. + // this prevents this.anything style attributes from leaking to the global scope. + this.currentContext.currentType = null; + } + + this.isTopLevelAnonymousFunction = false; + char[] methodName = methodDeclaration.getName(); + // if declaration didn't have name get name from inferred method if there is one + if(methodName == null && methodDeclaration.getInferredMethod() != null) { + methodName = methodDeclaration.getInferredMethod().name; + } + + //set the function that contains this assignment + if(this.passNumber == 1 && methodDeclaration instanceof AbstractMethodDeclaration && this.currentContext.currentMethod != null) { + ((AbstractMethodDeclaration)methodDeclaration).setContainingFunction(this.currentContext.currentMethod); + } + + //always need to build arguments + buildDefinedMembers(methodDeclaration.getStatements(), methodDeclaration.getArguments()); + + //only on the first pass should JS doc be looked at + if(passNumber == 1) { + if(methodDeclaration.getJsDoc() != null) { + InferredMethod method = null; + Javadoc javadoc = (Javadoc) methodDeclaration.getJsDoc(); + createTypeIfNecessary(javadoc); + if(javadoc.isConstructor) { + InferredType type; + if(!this.currentContext.isJsDocClass && methodName != null) { + type = this.addType(methodName); + } else { + type = this.currentContext.currentType; + } + + if(type != null) { + handleJSDocConstructor(type, methodDeclaration, methodDeclaration.sourceStart()); + } + } else if(javadoc.memberOf != null) { + InferredType type = this.addType(javadoc.memberOf.getFullTypeName(), true); + char[] name = methodName; + int nameStart = methodDeclaration.sourceStart(); + if(name != null) { + method = type.addMethod(methodName, methodDeclaration, nameStart); + } + } else if(javadoc.methodDef != null && this.currentContext.isJsDocClass) { + InferredType type = this.currentContext.currentType; + char[][] methName = javadoc.methodDef.getTypeName(); + int nameStart = ((MethodDeclaration) methodDeclaration).sourceStart; + if(methName.length == 1) { + method = type.addMethod(methName[0], methodDeclaration, nameStart); + } else { + method = type.addMethod(methName[methName.length - 1], methodDeclaration, nameStart); + method.isStatic = true; + } + + } + + if(javadoc.returnType != null) { + InferredType type = this.addType(changePrimitiveToObject(javadoc.returnType.getFullTypeName())); + methodDeclaration.setInferredType(type); + ((MethodDeclaration) methodDeclaration).bits |= ASTNode.IsInferredJsDocType; + } + + } + handleFunctionDeclarationArguments(methodDeclaration, methodDeclaration.getJsDoc()); + } + + // check if this is a constructor + if(passNumber == 2) { + if(methodName != null) { + InferredType type = compUnit.findInferredType(methodName); + InferredMethod inferMeth = methodDeclaration.getInferredMethod(); + + //only a constructor if the method is in the found type, or is in a type with the same name + if(type != null && + (inferMeth == null || + inferMeth.inType == null || + inferMeth.inType == type || + CharOperation.equals(inferMeth.inType.getName(), type.getName())) ) { + + this.currentContext.currentType = type; + type.setIsDefinition(true); + + if(inferMeth == null || !inferMeth.isConstructor) { + int nameStart = methodDeclaration.sourceStart(); + type.addConstructorMethod(methodName, methodDeclaration, nameStart); + } + } + } + } + this.currentContext.currentMethod = methodDeclaration; + if(methodDeclaration.getInferredMethod() != null && methodDeclaration.getInferredMethod().inType != null) { + this.currentContext.currentType = methodDeclaration.getInferredMethod().inType; + } + + if(methodDeclaration.getInferredType() == null) { + methodDeclaration.setInferredType(this.getVoidType()); + } + + return true; + } + + protected void handleConstructor(InferredType type, IFunctionDeclaration methodDeclaration, int start, int end) { + type.setIsDefinition(true); + type.addConstructorMethod(type.name, methodDeclaration, start); + type.updatePositions(start, end); + } + + protected void handleJSDocConstructor(InferredType type, IFunctionDeclaration methodDeclaration, int nameStart) { + Javadoc javadoc = (Javadoc) methodDeclaration.getJsDoc(); + type.setIsDefinition(true); + type.addConstructorMethod(type.name, methodDeclaration, nameStart); + + if(javadoc.extendsType != null) { + InferredType superType = this.addType(javadoc.extendsType.getFullTypeName()); + type.setSuperType(superType); + } + + } + + protected void handleFunctionDeclarationArguments(IFunctionDeclaration methodDeclaration, IJsDoc jsdoc) { + if(jsdoc == null || !(jsdoc instanceof Javadoc)) + return; + Javadoc javadoc = (Javadoc) jsdoc; + + IArgument[] arguments = methodDeclaration.getArguments(); + if(arguments != null) { + for(int i = 0; i < arguments.length; i++) { + //skip if argument already has a named type + InferredType currType = arguments[i].getInferredType(); + if(currType != null && !currType.isAnonymous) { + //TODO: this could possibly be smarter + continue; + } + + InferredType paramType = null; + JavadocSingleNameReference param = javadoc.findParam(arguments[i].getName()); + if(param != null) { + if(param.types != null) { + char[] name = {}; + for(int j = 0; j < param.types.length; j++) { + // char []typeName=param.types[j].getFullTypeName(); + // make sure we are using the type version of Boolean, even if the user + // entered boolean as the JSdoc type. + char[] typeName = changePrimitiveToObject(param.types[j].getFullTypeName()); + if(j == 0) { + name = typeName; + } else { + name = CharOperation.append(name, '|'); + name = CharOperation.concat(name, typeName); + } + } + + paramType = this.addType(name); + } + } + /** + * http://code.google.com/p/jsdoc-toolkit/wiki/InlineDocs + **/ + else if(arguments[i].getJsDoc() != null) { + if(((Javadoc) arguments[i].getJsDoc()).returnType != null) { + paramType = this.addType(((Javadoc) arguments[i].getJsDoc()).returnType.getFullTypeName()); + } + } else if(arguments[i].getComment() != null) { + char[] comment = CharOperation.trim(arguments[i].getComment()); + boolean validForName = true; + for(int j = 0; j < comment.length && validForName; j++) { + validForName &= + !CharOperation.isWhitespace(comment[j]) + && (Character.isJavaIdentifierPart(comment[j]) || comment[j] == '.'); + } + if(validForName) { + paramType = this.addType(comment); + } + } + + if(paramType != null) { + /* if the current type is not null (then it it is also anonymous) + * set the doced type as its parent */ + if(currType != null) { + InferredType currSuperType = currType.getSuperType(); + currType.setSuperType(paramType); + paramType.setSuperType(currSuperType); + + paramType = currType; + } + + arguments[i].setInferredType(paramType); + } + } + } + } + + private void copyAnonymousTypeToNamed(InferredType inClass, InferredType toType) { + if(toType == null) + return; + + compUnit.inferredTypesHash.removeKey(inClass.name); + if(inClass.methods != null) { + toType.methods.addAll(inClass.methods); + } + if(inClass.attributes != null) { + for(int i = 0; i < inClass.numberAttributes; i++) { + toType.addAttribute(inClass.attributes[i]); + } + } + + } + + /** + *

+ * Renames the given type to the given name. If there is a constructor on the type + * that is also renamed. + *

+ * + * @param type + * {@link InferredType} to rename + * @param newTypeName + * new type name for the given {@link InferredType} + */ + protected void renameType(InferredType type, char[] newTypeName) { + //rename constructor on type if there is one + InferredMethod constructor = type.findMethod(TypeConstants.INIT, null); + if(constructor != null) { + constructor.name = newTypeName; + } + + //rename the type + compUnit.inferredTypesHash.removeKey(type.name); + type.name = newTypeName; + compUnit.inferredTypesHash.put(newTypeName, type); + } + + /** + *

+ * Converts the given anonymous type to a named global type. If the given type is not anonymous + * then this is a no-op. + *

+ * + * @param type + * anonymous {@link InferredType} to name + * @param newTypeName + * new type name for the given anonymous {@link InferredType} + * + * @see InferredType#isAnonymous + */ + protected void convertAnonymousTypeToNamed(InferredType type, char[] newTypeName) { + if(type.isAnonymous) { + this.renameType(type, newTypeName); + type.isAnonymous = false; + type.setIsGlobal(true); + } + } + + protected boolean isMatch(IExpression expr, char[][] names, int index) { + char[] matchName = names[index]; + if(expr instanceof SingleNameReference) { + SingleNameReference snr = (SingleNameReference) expr; + return CharOperation.equals(snr.token, matchName); + } else if(expr instanceof FieldReference && names.length > 1 && index > 0) { + FieldReference fieldReference = (FieldReference) expr; + if(CharOperation.equals(fieldReference.token, matchName)) { + return isMatch(fieldReference.receiver, names, index - 1); + } + + } + return false; + } + + /** + * @deprecated not used + */ + protected boolean isFunction(IFunctionCall messageSend, String string) { + String[] names = string.split("\\."); //$NON-NLS-1$ + char[] functionName = names[names.length - 1].toCharArray(); + if(!CharOperation.equals(functionName, messageSend.getSelector())) { + return false; + } + + char[][] namesChars = new char[names.length][]; + for(int i = 0; i < namesChars.length; i++) { + namesChars[i] = names[i].toCharArray(); + } + if(names.length > 1) { + return isMatch(messageSend.getReceiver(), namesChars, namesChars.length - 2); + } + return true; + } + + protected boolean isFunction(IFunctionCall messageSend, char[][] names) { + if(messageSend == null) { + return false; + } + + char[] functionName = names[names.length - 1]; + if(!CharOperation.equals(functionName, messageSend.getSelector())) { + return false; + } + + if(names.length > 1) { + return isMatch(messageSend.getReceiver(), names, names.length - 2); + } + + return true; + } + + public void doInfer() { + try { + long time0 = 0; + if(REPORT_INFER_TIME) { + time0 = System.currentTimeMillis(); + } + clearBuiltInTypes(); + + ASTVisitor visitor = getVisitor(compUnit); + if (visitor != null) + compUnit.traverse(visitor); + + passNumber = 2; + visitor = getVisitor(compUnit); + if (visitor != null) + compUnit.traverse(visitor); + + for(int i = 0; i < compUnit.numberInferredTypes; i++) { + if(compUnit.inferredTypes[i].sourceStart < 0) + compUnit.inferredTypes[i].sourceStart = 0; + } + + if(REPORT_INFER_TIME) { + long time = System.currentTimeMillis() - time0; + System.err.println(getClass().getName() + " inferred " + new String(compUnit.getFileName()) + " in " //$NON-NLS-1$ //$NON-NLS-2$ + + time + "ms"); //$NON-NLS-1$ + } + this.compUnit = null; + + } catch(RuntimeException e) { + org.eclipse.wst.jsdt.internal.core.util.Util.log(e, "error during type inferencing"); //$NON-NLS-1$ + } + } + + protected InferredType addType(char[] className) { + return addType(className, false); + } + + /** + * Create a new inferred type with the given name + * + * @param className + * the name of the inferred type + * @param isDefinition + * true if this unit defines the type + * @return new Inferred type + */ + protected InferredType addType(char[] className, boolean isDefinition) { + InferredType type = compUnit.addType(className, isDefinition, this.inferenceProvider.getID()); + + return type; + } + + protected final void pushContext() { + Context newContext = new Context(currentContext); + contexts[++contextPtr] = currentContext; + currentContext = newContext; + + } + + protected final void popContext() { + currentContext = contexts[contextPtr]; + contexts[contextPtr--] = null; + } + + + /** + * @deprecated not used internally, will be removed + */ + protected final boolean isInNamedMethod() { + return this.currentContext.currentMethod != null && this.currentContext.currentMethod.getName() != null; + } + + /** + * Finds a Var Declaration on the context from the name represented with the expression + */ + protected IAbstractVariableDeclaration getVariable(IExpression expression) { + char[] name = null; + + if(expression instanceof ISingleNameReference) { + name = ((ISingleNameReference) expression).getToken(); + } else if(expression instanceof IFieldReference) { + IReference ref = getRoot((IFieldReference)expression); + if(ref != null && ref instanceof SingleNameReference) { + name = ((SingleNameReference)ref).getToken(); + } + } + + if(name != null) { + Object var = this.currentContext.getMember(name); + if(var instanceof IAbstractVariableDeclaration) { + return (IAbstractVariableDeclaration) var; + } + + } + return null; + + } + + /** + * Finds a assignment on the context from the name represented with the expression + */ + protected IAssignment getAssignment(IExpression expression) { + char[] name = null; + + if(expression instanceof ISingleNameReference) { + name = ((ISingleNameReference) expression).getToken(); + } else if(expression instanceof IFieldReference) { + IReference ref = getRoot((IFieldReference)expression); + if(ref != null && ref instanceof SingleNameReference) { + name = ((SingleNameReference)ref).getToken(); + } + } + + if(name != null) { + Object assignment = this.currentContext.getMember(name); + if(assignment instanceof IAssignment) { + return (IAssignment) assignment; + } + } + + return null; + } + + /** + *

+ * Finds a Function Declaration on the context from the name represented + * with the expression + *

+ * + *

+ * Supported: + *

    + *
  • {@link ISingleNameReference}
  • + *
  • {@link ILocalDeclaration}
  • + *
+ *

+ */ + protected IAbstractFunctionDeclaration getFunction(IExpression expression) { + IAbstractFunctionDeclaration function = null; + + char[] name = null; + if(expression instanceof ISingleNameReference) { + name = ((ISingleNameReference) expression).getToken(); + + Object method = this.currentContext.getMember(name); + if(method instanceof IAbstractFunctionDeclaration) { + function = (IAbstractFunctionDeclaration) method; + } else if(method instanceof ILocalDeclaration) { + IExpression init = ((ILocalDeclaration) method).getInitialization(); + if(init instanceof IFunctionExpression) { + function = ((IFunctionExpression)init).getMethodDeclaration(); + } + } + } else if(expression instanceof IFieldReference) { + InferredType receiverType = this.getReceiverType(((IFieldReference) expression).getReceiver(), false); + if(receiverType != null) { + InferredMethod inferredMethod = receiverType.findMethod(((IFieldReference) expression).getToken(), null); + if(inferredMethod != null) { + function = inferredMethod.getFunctionDeclaration(); + } + } + name = ((IFieldReference) expression).getToken(); + } else if(expression instanceof MessageSend) { + name = ((MessageSend)expression).selector; + if(name != null) { + // look up the function in the current context, we want to get + // to its return statement eventually. + Object method = this.currentContext.getMember(name); + if(method instanceof IAbstractFunctionDeclaration) { + IAbstractFunctionDeclaration calledFunction = (IAbstractFunctionDeclaration) method; + if(calledFunction.getStatements() != null) { + IProgramElement[] statements = calledFunction.getStatements(); + // this is a bit of a guess, but look for a return statement + // if found and it is returning a function, then use that + // if not we just return nothing, no harm done. + for(int i = 0; i < statements.length; i++) { + if(statements[i] instanceof IReturnStatement) { + if(((IReturnStatement)statements[i]).getExpression() instanceof IFunctionExpression) { + function = ((IFunctionExpression) ((IReturnStatement)statements[i]).getExpression()).getMethodDeclaration(); + break; + } + } + } + } + } + } + } + + return function; + } + + private void buildDefinedMembers(IProgramElement[] statements, IArgument[] arguments) { + + if(arguments != null) { + for(int i = 0; i < arguments.length; i++) { + this.currentContext.addMember(arguments[i].getName(), arguments[i]); + } + } + if(statements != null) { + for(int i = 0; i < statements.length; i++) { + if(statements[i] instanceof ILocalDeclaration) { + ILocalDeclaration local = (ILocalDeclaration) statements[i]; + this.currentContext.addMember(local.getName(), local); + } else if(statements[i] instanceof IAbstractFunctionDeclaration) { + IAbstractFunctionDeclaration method = (IAbstractFunctionDeclaration) statements[i]; + if(method.getName() != null) + this.currentContext.addMember(method.getName(), method); + } + } + } + } + + private static boolean isThis(IExpression expression) { + return expression instanceof ASTNode && ((ASTNode)expression).isThis(); + } + + /* This method is used to determined the inferred type of a LHS Expression. + * + * It could return null. + * + * a.b.c */ + private InferredType getInferredType(IExpression expression) { + + InferredType type = null; + + /* this */ + if(expression instanceof IThisReference) { + type = this.currentContext.currentType; + } + /* foo (could be a Type name or a reference to a variable) */ + else if(expression instanceof SingleNameReference) { + //check for local variable first + IAbstractVariableDeclaration varDecl = this.getVariable(expression); + if(varDecl != null) { + type = varDecl.getInferredType(); + } + + //if not found type yet check for assignment + IAssignment assignment = null; + if(type == null) { + assignment = getAssignment(expression); + if(assignment != null) { + type = assignment.getInferredType(); + } + } + + /* if not found type yet and there was no declaration or assignment, + * or the found type is Function then check if there is a known type + * with the same name as the SNR. */ + if((type == null && varDecl == null && assignment == null) || + (type != null && type.isFunction())) { + + char[] possibleTypeName = constructTypeName(expression); + if(possibleTypeName != null) { + /* if pre-existing type, use that + * else check if known type name */ + InferredType existingType = compUnit.findInferredType(possibleTypeName); + if(existingType != null) { + type = existingType; + } else if(WellKnownTypes.containsKey(possibleTypeName) || + this.isKnownType(possibleTypeName)) { + + type = addType(possibleTypeName, false); + } + } + } + } + /* foo.bar.xxx... */ + else if(expression instanceof FieldReference) { + char[] possibleTypeName = constructTypeName(expression); + + if(possibleTypeName != null) { + // search the defined types in the context + type = compUnit.findInferredType(possibleTypeName); + } + + if(type == null && isPossibleClassName(possibleTypeName)) { + type = addType(possibleTypeName, true); + } + + /* Continue the search by trying to resolve further down the name + * because this token of the field reference could be a member of a + * type or instance of a type */ + if(type == null) { + FieldReference fRef = (FieldReference) expression; + + // this + InferredType parentType = getInferredType(fRef.receiver); + + if(parentType != null) { + // check the members and return type + InferredAttribute typeAttribute = parentType.findAttribute(fRef.token); + + if(typeAttribute != null) { + type = typeAttribute.type; + } + } + } + + } + + return type; + } + + /** + * @deprecated - here for compatibility + */ + protected InferredType getInferredType2(IExpression fieldReceiver) { + InferredType receiverType = null; + IAbstractVariableDeclaration var = getVariable(fieldReceiver); + if(var != null) { + receiverType = createAnonymousType(var); + } else { + if(this.inferredGlobal != null && fieldReceiver instanceof ISingleNameReference) { + char[] name = ((ISingleNameReference) fieldReceiver).getToken(); + InferredAttribute attr = this.inferredGlobal.findAttribute(name); + if(attr != null) { + receiverType = attr.type; + } + } + + } + return receiverType; + } + + protected boolean isKnownType(char[] possibleTypeName) { + return false; + } + + /* For SNR it returns the name + * For FR it construct a Qualified name separated by '.' + * + * If at any point it hits a portion of the Field reference that is + * not supported (such as a function call, a prototype, or this ) */ + protected final char[] constructTypeName(IExpression expression) { + return Util.getTypeName(expression); + } + + public boolean visit(IObjectLiteral literal) { + if(this.passNumber == 1 && literal.getInferredType() == null) { + createAnonymousType(literal); + } + pushContext(); + this.currentContext.currentType = literal.getInferredType(); + return true; + } + + public void endVisit(IObjectLiteral literal) { + popContext(); + } + + /** + * Overridden by client who wish to update the infer options + * + * @param options + */ + public void initializeOptions(InferOptions options) { + } + + protected boolean isPossibleClassName(char[] name) { + return false; + } + + /** + * Get the Script file this inference is being done on + * + * @return + */ + public IScriptFileDeclaration getScriptFileDeclaration() { + return this.compUnit; + } + + public InferredType findDefinedType(char[] className) { + return compUnit.findInferredType(className); + } + + protected Object findDefinedMember(char[] memberName) { + return currentContext.getMember(memberName); + } + + protected char[] changePrimitiveToObject(char[] name) { + /* + * Changes the first character of the name of the primitive types to + * uppercase. This will allow future reference to the object wrapper + * instead of the primitive type. + */ + if(CharOperation.equals(name, TypeConstants.BOOLEAN, false)) { + return this.getBooleanType().getName(); + } + + return name; + } + + /** + * @return {@link InferredType} for the String type + */ + protected InferredType getStringType() { + if(fStringType == null) { + fStringType = this.addType(TypeConstants.JAVA_LANG_STRING[0]); + } + + return fStringType; + } + + /** + * @return {@link InferredType} for the Number type + */ + protected InferredType getNumberType() { + if(fNumberType == null) { + fNumberType = this.addType(TypeConstants.NUMBER[0]); + } + + return fNumberType; + } + + /** + * @return {@link InferredType} for the Boolean type + */ + protected InferredType getBooleanType() { + if (fBooleanType == null) { + fBooleanType = this.addType(TypeConstants.BOOLEAN_OBJECT[0]); + } + + return fBooleanType; + } + + /** + * @return {@link InferredType} for the Function type + */ + protected InferredType getFunctionType() { + if(fFunctionType == null) { + fFunctionType = this.addType(TypeConstants.FUNCTION[0]); + } + + return fFunctionType; + } + + /** + * @return {@link InferredType} for the Array type + */ + protected InferredType getArrayType() { + if(fArrayType == null) { + fArrayType = this.addType(TypeConstants.ARRAY[0]); + } + + return fArrayType; + } + + /** + * @return {@link InferredType} for the Void type + */ + protected InferredType getVoidType() { + if(fVoidType == null) { + fVoidType = this.addType(TypeConstants.VOID); + } + + return fVoidType; + } + + /** + * @return {@link InferredType} for the Object type + */ + protected InferredType getObjectType() { + if(fObjectType == null) { + fObjectType = this.addType(TypeConstants.OBJECT); + } + + return fObjectType; + } + + /** + *

+ * Gets the name of the given expression. + *

+ * + *

+ * Supported: + *

    + *
  • {@link ISingleNameReference}
  • + *
  • {@link IFieldReference}
  • + *
  • {@link IAssignment}
  • + *
+ *

+ * + * @param expression + * {@link IExpression} to get the name for + * + * @return name of the given {@link IExpression} or null if none + * can be determined + */ + protected char[] getName(IExpression expression) { + char[] name = null; + + if(expression instanceof ISingleNameReference) { + name = ((ISingleNameReference) expression).getToken(); + } else if(expression instanceof IFieldReference) { + name = ((IFieldReference) expression).getToken(); + } else if(expression instanceof IAssignment) { + name = this.getName(((IAssignment) expression).getLeftHandSide()); + } + + return name; + } + + /** + *

+ * Given a variable name and an initialization expression determines the + * type to initialize the variable with the given name to. + *

+ * + * @param variableName + * name of the variable to be initialized + * @param initialization + * the initialization expression used to initialize the + * variable with the given name + * + * @return {@link InferredType} to initialize the variable with the given + * name with + */ + private InferredType getTypeForVariableInitialization(char[] variableName, IExpression initialization) { + InferredType type = this.getTypeOf(initialization); + + /* if the initialization type is not indexed and the variable declaration is in the global scope + * rename the type to a globally anonymous type and mark it as a global type + */ + boolean isGlobal = this.isGlobal(variableName); + if(type != null && !type.isIndexed() && isGlobal) { + char[] globalTypeName = createAnonymousGlobalTypeName(variableName); + this.renameType(type, globalTypeName); + type.isAnonymous = true; + type.setIsGlobal(true); + } else if(type == null && isGlobal && this.passNumber == 2) { + type = this.createAnonymousGlobalType(variableName); + } + + return type; + } + + /** + *

+ * Will create a type to assign to given the receiver that is being assigned to, the current + * type that is or will be assigned to the receiver, and the assignment expression that will be + * used for the assignment. + *

+ * + *

+ * NOTE: This does not actually deal with the assignment, it just creates the type to assign + * to and updates the type for the given receiver. + *

+ * + * @param receiver + * the receiver to update the type for + * @param currentReceiverType + * current type that is or will be assigned to the receiver + * + * @return {@link InferredType} that was created to do the assignment to or the given current + * receiver type if no new type was created + */ + private InferredType createTypeToAssignTo(IExpression receiver, InferredType currentReceiverType) { + char[] varName = this.getName(receiver); + InferredType newType = null; + + /* If the current receiver type is not anonymous and is not a this statement, + * and the receiver is not a type (rather then instance of a type, then + * create a new anonymous type with current type as the parent. + * + * else use the given current receiver type */ + if(!currentReceiverType.isAnonymous && !isThis(receiver) + && !CharOperation.equals(currentReceiverType.name, varName) && !this.isExpressionAType(receiver)) { + + /* if the variable being assigned to is in the global scope then + * need to create a global type + * + * else create a local anonymous type + */ + boolean isGlobal = this.isGlobal(varName); + if(isGlobal) { + /* if current type is a function create a new type with the var name + * else create new anonymous global type */ + if(currentReceiverType.isFunction()) { + newType = this.addType(varName, true); + } else { + newType = this.createAnonymousGlobalType(varName); + } + } else { + newType = this.createAnonymousType(receiver, currentReceiverType); + } + } + + /* if created a new type set its super type to the original type and update the type for the receiver + * + * else just return the original given current receiver type */ + if(newType != null) { + newType.setSuperType(currentReceiverType); + this.setTypeOf(receiver, newType); + } else { + newType = currentReceiverType; + } + + return newType; + } + + /** + *

+ * Clears out all of the built in types. + *

+ */ + private void clearBuiltInTypes() { + fStringType = null; + fNumberType = null; + fBooleanType = null; + fFunctionType = null; + fArrayType = null; + fVoidType = null; + fObjectType = null; + } + + /** + *

+ * This method is intended to take a chain of field references and + * determine the type that the last field should be or is defined on. + *

+ * + *

+ * EX: foo.bar.awesome.crazy = 42;
+ *
+ * If that is the entirety of the file and the receiver of the + * foo.bar.awesome.crazy statement is given to this function, + * so the foo.bar.awesome part, then this function will + * create a foo field on the global inferred type and and + * then give it a type that has a bar field, and then give + * the bar field a type with an awesome field + * and then finally return a new type assigned to the awesome + * field such that some other code can deal with assigning the + * crazy field with whatever type is on the right hand side + * of the assignment. + *

+ * + * @param receiver + * the receiver side of a {@link FieldReference} to get the + * type for + * + * @param defineRoot + * Has two purposes. If the root of the field reference has no + * type and this is true a type will be created. + * If the root of this field reference does not have a type and + * this is false no root type will be created an + * thus no type will be returned by this method. When there is + * a root type if this argument is true then the + * type on the root will be marked as a definition, else if + * false the root will not be marked as a + * definition. + * + * @return {@link InferredType} associated with the given receiver side of + * a {@link FieldReference} + */ + protected InferredType getReceiverType(IExpression receiver, boolean defineRoot) { + InferredType receiverType = null; + IExpression current = receiver; + List recievers = new ArrayList(); + InferredType rootType = null; + + /* Find the SingleNameReference that the reference chain starts with + * or the root type if the chain starts with a THIS statement */ + while(current != null && !(current instanceof SingleNameReference) && rootType == null) { + if(current instanceof FieldReference) { + recievers.add(current); + current = ((FieldReference) current).getReceiver(); + } else if(current instanceof ThisReference) { + rootType = this.currentContext.currentType; + ((ThisReference) current).setInferredType(rootType); + current = null; + } else { + current = null; + } + } + + //if the root was a single name then determine or create its type + IAbstractVariableDeclaration rootVarDecl = null; + IAssignment rootAssignment = null; + if(rootType == null && current instanceof SingleNameReference) { + + //first check if there is a type with the same name as the single name reference + char[] name = ((SingleNameReference) current).getToken(); + rootType = this.findDefinedType(name); + + // if the single name reference is a function then create a type using the function name + if(rootType == null) { + IFunctionDeclaration func = this.getDefinedFunction(current); + if(func != null) { + rootType = this.addType(name, true); + rootType.setNameStart(current.sourceStart()); + rootType.setSourceEnd(current.sourceEnd()); + } + } + + // if single name reference is to a variable + if(rootType == null) { + rootVarDecl = this.getVariable(current); + if(rootVarDecl != null) { + rootType = rootVarDecl.getInferredType(); + + /* if variable does not already have an inferred type create an anonymous one + * or if the receiver type is not anonymous and is the expression is not a type then + * create a new anonymous sub type to do the assignment to */ + + if(rootType == null || (!rootType.isAnonymous && !rootVarDecl.isType())) { + /* if global then create anonymous global type and set super type as current root type + * else create anonymous type using current root type as super type */ + boolean isGlobal = this.isGlobal(name); + if(isGlobal) { + InferredType globalType = this.createAnonymousGlobalType(name); + globalType.setSuperType(rootType); + rootType = globalType; + rootType.setIsDefinition(true); + rootVarDecl.setInferredType(rootType); + } else if(defineRoot) { + rootType = this.createAnonymousType(current, rootType); + rootType.setIsDefinition(true); + rootVarDecl.setInferredType(rootType); + } + } + } + } + + //if single name reference is to a field on the inferred 'global' type + if(rootType == null && this.inferredGlobal != null) { + InferredAttribute attr = this.getInferredGlobal(false).findAttribute(name); + if(attr != null) { + if(attr.type == null) { + attr.type = this.createAnonymousGlobalType(attr.name); + } + rootType = attr.type; + } else { + InferredMethod meth = this.getInferredGlobal(false).findMethod(name, null); + if(meth != null) { + rootType = this.addType(name, true); + rootType.setNameStart(current.sourceStart()); + rootType.setSourceEnd(current.sourceEnd()); + } + } + } + + // if single name reference is to an existing assignment with no declaration + if(rootType == null) { + rootAssignment = this.getAssignment(current); + if(rootAssignment != null) { + rootType = rootAssignment.getInferredType(); + } + } + + /* else if define root create a new anonymous global type */ + if(rootType == null && defineRoot) { + rootType = this.createAnonymousGlobalType(name); + } + } + + /* if determined a root type, and there is no case where we should not, + * make sure there is fields and types built up for the rest of the reference chain */ + if(rootType != null) { + /* only define root if requested and root not part of long chain, + * or the root was already defined somewhere else in this file + * + * IE: foo.bar.blarg = 42, foo is not defined here + * foo.bar = 42, foo is defined here */ + if(defineRoot && (recievers.isEmpty() || rootVarDecl != null || rootAssignment != null)) { + rootType.setIsDefinition(true); + } + + InferredType currentType = rootType; + for(int i = recievers.size()-1; i >= 0; --i) { + FieldReference ref = (FieldReference)recievers.get(i); + + InferredAttribute attr = currentType.findAttribute(ref.getToken()); + if(attr != null) { + if(attr.type != null) { + currentType = attr.type; + } else { + attr.type = this.createAnonymousType(attr, null); + currentType = attr.type; + } + } else { + InferredMethod meth = currentType.findMethod(ref.getToken(), null); + if(meth != null) { + char[] typeName = CharOperation.concatWith(ref.asQualifiedName(), '.'); + currentType = this.addType(typeName, true); + } else { + attr = currentType.addAttribute(ref.getToken(), ref, ref.sourceStart); + + if(currentType == this.getInferredGlobal(false)) { + attr.type = this.createAnonymousGlobalType(attr.name); + attr.type.setIsDefinition(true); + } else { + attr.type = this.createAnonymousType(attr, null); + } + currentType = attr.type; + } + } + } + + //set the last type in the chain as the receiver type + receiverType = currentType; + } + + return receiverType; + } + + /** + * @param define + * true to define the inferred global type if one + * is not yet defined, false otherwise + * + * @return inferred global type, or null if none is yet + * defined and define was given as false + */ + protected InferredType getInferredGlobal(boolean define) { + if(this.inferredGlobal == null && define) { + this.inferredGlobal = addType(IIndexConstants.GLOBAL_SYMBOL, true); + this.inferredGlobal.isAnonymous = true; + this.inferredGlobal.setIsGlobal(true); + } + + return this.inferredGlobal; + } + + /** + *

+ * Determine if the root of the given expression is global or not. + *

+ * + * @param expr + * Determine if the root of this expression is global or not + * + * @return true if the root of the given expression is + * global, false otherwise + */ + private boolean isRootGlobal(IExpression expr) { + boolean isGlobal = false; + + IReference root = null; + if(expr instanceof SingleNameReference) { + root = (SingleNameReference) expr; + } else if(expr instanceof FieldReference) { + root = getRoot((FieldReference)expr); + } + + /* if root is a single name reference then determine if it is global + * else if no root then assume global */ + if(root != null && root instanceof ISingleNameReference) { + isGlobal = this.isGlobal(((ISingleNameReference)root).getToken()); + } else if(root != null && root instanceof IThisReference) { + isGlobal = this.currentContext.currentType == this.getInferredGlobal(false); + } else if(root == null){ + isGlobal = true; + } + + return isGlobal; + } + + /** + *

+ * Determines if the given variable name is global. + *

+ * + * @param name + * determine if there is a global variable with this name + * + * @return true if there is a global variable with this name, + * false otherwise + */ + protected boolean isGlobal(char[] name) { + boolean isGlobal = false; + + if (name == null) + return isGlobal; + + //check the root context + Object globalMember; + Object currentContextMember = this.currentContext.getMember(name); + if(this.contexts[0] != null) { + globalMember = this.contexts[0].getMember(name); + } else { + globalMember = currentContextMember; + } + + /* is global if global member with same name is not null and from the current context + * the first member with that name is also the global member, this is to cover the case + * with a shadowing local variable */ + isGlobal = globalMember != null && currentContextMember == globalMember; + + /* if not determined to be global then check if the current context member + * is an assignment. If it is then that assignment is an assignment without + * a local declaration which means it is global */ + if(!isGlobal) { + isGlobal = currentContextMember instanceof Assignment; + } + + //if not determined to be global yet then check inferred global type + if(!isGlobal) { + globalMember = null; + InferredType inferredGlobal = this.getInferredGlobal(false); + if(inferredGlobal != null) { + globalMember = inferredGlobal.findAttribute(name); + + if(globalMember == null) { + globalMember = inferredGlobal.findMethod(name, null); + } + } + + isGlobal = globalMember != null; + } + + /* if not determined to be global yet and no global member or + * local member found assume to be global */ + if(!isGlobal) { + if(globalMember == null && currentContextMember == null) { + isGlobal = true; + } + } + + return isGlobal; + } + + /** + *

+ * Given an {@link IFieldReference} finds the root + * {@link SingleNameReference}. + *

+ * + * @param ref + * {@link IFieldReference} to find the root + * {@link SingleNameReference} for + * + * @return {@link SingleNameReference} that is the root of the given + * {@link IFieldReference}, or null if it can not be + * found. + */ + private static IReference getRoot(IFieldReference ref) { + IReference root = null; + + IExpression current = ref; + while(root == null && current != null) { + if(current instanceof IFieldReference) { + current = ((IFieldReference) current).getReceiver(); + } else if(current instanceof SingleNameReference) { + root = (SingleNameReference)current; + } else if(current instanceof IThisReference) { + root = (IThisReference)current; + } else { + current = null; + } + } + + return root; + } + + /** + *

+ * Determines if the given parent expression contains or is the given + * needle expression. + *

+ * + *

+ * Handles: + *

    + *
  • {@link IBinaryExpression}
  • + *
+ *

+ * + * @param parent + * determine if the given needle is or is contained by this + * parent expression + * @param needle + * determine if the this needle is or is contained by the given + * parent expression + * + * @return true if the given needle is or is contained by the + * given parent expression, false otherwise + */ + private static boolean expressionContains(IExpression parent, IExpression needle) { + boolean contains = false; + + LinkedList expressions = new LinkedList(); + expressions.add(parent); + + while(expressions.size() > 0 && !contains) { + IExpression current = (IExpression)expressions.removeFirst(); + + contains = needle == current; + + if(!contains) { + if(current instanceof IBinaryExpression) { + expressions.add(((IBinaryExpression) current).getLeft()); + expressions.add(((IBinaryExpression) current).getRight()); + } else if(current instanceof Assignment) { + expressions.add(((Assignment) current).getLeftHandSide()); + expressions.add(((Assignment) current).getExpression()); + } + } + } + + return contains; + } + + /** + *

+ * Determines if the given expression is a type rather then an instance of + * a type. + *

+ * + * @param expr + * determine if this expression is a type rather then an + * instance of a type + * + * @return true if the given expression is a type, + * false if the given expression is the instance of a + * type or unknown + */ + private boolean isExpressionAType(IExpression expr) { + boolean isType = false; + + if(expr instanceof IAssignment) { + isType = ((IAssignment) expr).isType(); + } else if(expr instanceof IAbstractVariableDeclaration) { + isType = ((IAbstractVariableDeclaration) expr).isType(); + } else if(expr instanceof IFieldReference) { + IExpression receiver = ((IFieldReference) expr).getReceiver(); + InferredType receiverType = this.getTypeOf(receiver); + if(receiverType != null) { + InferredAttribute attr = receiverType.findAttribute(((IFieldReference) expr).getToken()); + isType = attr != null && attr.isType(); + } + } else if(expr instanceof ISingleNameReference) { + IAbstractVariableDeclaration varDecl = this.getVariable(expr); + if(varDecl != null) { + isType = varDecl.isType(); + } + + if(!isType) { + IAssignment assign = this.getAssignment(expr); + if(assign != null) { + isType = assign.isType(); + } + } + + if(!isType) { + IAbstractFunctionDeclaration funcDecl = this.getFunction(expr); + if(funcDecl != null && funcDecl.getName() != null) { + InferredType typeDefinedByFunc = this.findDefinedType(funcDecl.getName()); + isType = typeDefinedByFunc != null; + } + } + + if(!isType) { + InferredType existingType =this.compUnit.findInferredType(((ISingleNameReference) expr).getToken()); + isType = existingType != null; + } + } else if(expr instanceof IThisReference) { + isType = true; + } + + return isType; + } + + protected InferredType createAnonymousTypeForMixin(IExpression mixInto, InferredType parentType) { + InferredType mixIntoType; + IAbstractVariableDeclaration localVar = getVariable(mixInto); + char[] varName = getName(mixInto); + if (mixInto instanceof ISingleNameReference && (localVar == null || isGlobal(varName))) { + mixIntoType = createAnonymousGlobalType(varName); + mixIntoType.setSuperType(parentType); + } + else { + mixIntoType = createAnonymousType(mixInto, parentType); + } + mixIntoType.isObjectLiteral = false; + return mixIntoType; + } + + protected InferredType getAttributeType(char[] attName, IExpression receiver, boolean defineRoot) { + InferredType attrType = null; + InferredType receiverType = this.getReceiverType(receiver, defineRoot); + if (receiverType != null) { + InferredAttribute attr = receiverType.findAttribute(attName); + if (attr != null && attr.type != null) { + attrType = attr.type; + } + } + return attrType; + } + + /** + * Return a visitor to traverse the given compilation unit's AST. + * Subclasses may override to provide a more minimal implementations while + * retaining use of utility methods from the base InferEngine. + * + * @return a visitor for use with the given compilation unit and current + * engine states, or null + */ + protected ASTVisitor getVisitor(CompilationUnitDeclaration compilationUnit) { + return this; + } +} \ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferOptions.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferOptions.java index 52169f96..700bf29b 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferOptions.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferOptions.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferredAttribute.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferredAttribute.java index 1b963ca2..5a8f21dd 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferredAttribute.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferredAttribute.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2010 IBM Corporation and others. + * Copyright (c) 2005, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -35,6 +35,15 @@ public class InferredAttribute extends InferredMember{ public InferredType type; public ASTNode node; public int modifiers; + + /** + *

+ * true if this attribute is actually a type, + * rather then the instance of a type. false if this attribute is + * an instance of a type rather then the type itself. + *

+ */ + private boolean fIsType; /** * Creates an attribute with this name in the given inferred type. This @@ -72,5 +81,24 @@ public class InferredAttribute extends InferredMember{ output.append(" ").append(name); //$NON-NLS-1$ return output; } + + /** + * @param isType + * true if this attribute is actually a type, + * rather then the instance of a type. false if + * this attribute is an instance of a type rather then the type + * itself. + */ + public void setIsType(boolean isType) { + this.fIsType = isType; + } -} + /** + * @return true if this attribute is actually a type, rather + * then the instance of a type. false if this + * attribute is an instance of a type rather then the type itself. + */ + public boolean isType() { + return this.fIsType; + } +} \ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferredType.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferredType.java index 90f3eae6..ec865d57 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferredType.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferredType.java @@ -1,469 +1,942 @@ -/******************************************************************************* - * Copyright (c) 2005, 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.jsdt.core.infer; - -import java.util.ArrayList; -import java.util.Iterator; - -import org.eclipse.wst.jsdt.core.ast.IASTNode; -import org.eclipse.wst.jsdt.core.ast.IAbstractFunctionDeclaration; -import org.eclipse.wst.jsdt.core.ast.IFunctionDeclaration; -import org.eclipse.wst.jsdt.core.compiler.CharOperation; -import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode; -import org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration; -import org.eclipse.wst.jsdt.internal.compiler.lookup.ArrayBinding; -import org.eclipse.wst.jsdt.internal.compiler.lookup.ClassScope; -import org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding; -import org.eclipse.wst.jsdt.internal.compiler.lookup.MultipleTypeBinding; -import org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding; -import org.eclipse.wst.jsdt.internal.compiler.lookup.Scope; -import org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding; -import org.eclipse.wst.jsdt.internal.compiler.lookup.TagBits; -import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding; -import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeConstants; -import org.eclipse.wst.jsdt.internal.compiler.util.HashtableOfObject; - - -/** - * The represenation of an inferred type. - * - * Provisional API: This class/interface is part of an interim API that is still under development and expected to - * change significantly before reaching stability. It is being made available at this early stage to solicit feedback - * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken - * (repeatedly) as the API evolves. - */ -public class InferredType extends ASTNode { - - char [] name; - public ArrayList methods; - public InferredAttribute[] attributes=new InferredAttribute[5]; - public int numberAttributes=0; - HashtableOfObject attributesHash = new HashtableOfObject(); - public InferredType superClass; - - public InferredType referenceClass; - - public SourceTypeBinding binding; - public boolean isDefinition; - private TypeBinding resolvedType; - public ClassScope scope; - ReferenceBinding resolvedSuperType; - - public boolean isArray=false; - public boolean isAnonymous=false; - public boolean isObjectLiteral=false; - - private int nameStart = -1; - - public String inferenceProviderID; - public String inferenceStyle; - - public ArrayList mixins; - - public final static char[] OBJECT_NAME=new char[]{'O','b','j','e','c','t'}; - public final static char[] OBJECT_LITERAL_NAME = new char[]{'{','}'}; - - public final static char[] ARRAY_NAME=new char[]{'A','r','r','a','y'}; - public final static char[] FUNCTION_NAME=new char[]{'F','u','n','c','t','i','o','n'}; - public final static char[] GLOBAL_NAME=new char[]{'G','l','o','b','a','l'}; - - public Object userData; - - boolean allStatic=false; - - /** - * Create a new inferred type - * - * @param className inferred type name - */ - public InferredType(char [] className) - { - this.name=className; - this.sourceStart=-1; - } - - /** - * Gets the name of the inferred type - * - * @return the inferred type name - */ - public char [] getName() { - return name; - } - - /** - * Get the superclass name of the inferred type - * - * @return superclass name - */ - public char [] getSuperClassName() - { - return superClass!=null ? superClass.getName() : OBJECT_NAME; - } - - /** - * Add a new inferred attribute to the inferred type - * - * @param name the attribute name - * @param definer the ASTNode which this attribute is inferred from - * @param nameStart character position (in the source) of the attribute name - * @return a new InferredAttribute - */ - public InferredAttribute addAttribute(char [] name, IASTNode definer, int nameStart) - { - InferredAttribute attribute = findAttribute(name); - if (attribute==null) - { - attribute=new InferredAttribute(name, this, definer); - attribute.node=(ASTNode)definer; - - if (this.numberAttributes == this.attributes.length) - - System.arraycopy( - this.attributes, - 0, - this.attributes = new InferredAttribute[this.numberAttributes * 2], - 0, - this.numberAttributes ); - this.attributes [this.numberAttributes ++] = attribute; - - - attributesHash.put(name, attribute); - - if (!isAnonymous) { - this.updatePositions(definer.sourceStart(), definer.sourceEnd()); - } - } - attribute.nameStart = nameStart; - return attribute; - } - - /** - * Add an InferredAttribute to this inferred type. - * - * @param newAttribute the attribute to add. - * @return - */ - public InferredAttribute addAttribute(InferredAttribute newAttribute) - { - IASTNode definer=newAttribute.node; - InferredAttribute attribute = findAttribute(newAttribute.name); - if (attribute==null) - { - - if (this.numberAttributes == this.attributes.length) - - System.arraycopy( - this.attributes, - 0, - this.attributes = new InferredAttribute[this.numberAttributes * 2], - 0, - this.numberAttributes ); - this.attributes [this.numberAttributes ++] = newAttribute; - - - attributesHash.put(newAttribute.name, newAttribute); - - if (!isAnonymous) { - if (definer != null) { - this.updatePositions(definer.sourceStart(), definer.sourceEnd()); - } - else { - this.updatePositions(newAttribute.sourceStart(), newAttribute.sourceEnd()); - } - } - } - return newAttribute; - } - /** - * Find the inferred attribute with the given name - * - * @param name name of the attribute to find - * @return the found InferredAttribute, or null if not found - */ - public InferredAttribute findAttribute(char [] name) - { - return (InferredAttribute)attributesHash.get(name); -// if (attributes!=null) -// for (Iterator attrIterator = attributes.iterator(); attrIterator.hasNext();) { -// InferredAttribute attribute = (InferredAttribute) attrIterator.next(); -// if (CharOperation.equals(name,attribute.name)) -// return attribute; -// } -// return null; - } - - - /** - * Add a new constructor method to the inferred type - * - * @param methodName name of the method to add - * @param functionDeclaration the AST Node containing the method bode - * @param nameStart character position (in the source) of the method name - * @return a new inferred method - */ - public InferredMethod addConstructorMethod(char [] methodName, IFunctionDeclaration functionDeclaration, int nameStart) { - InferredMethod method = this.addMethod(methodName, functionDeclaration, nameStart, true); - method.isConstructor = true; - this.setNameStart(nameStart); - method.getFunctionDeclaration().setInferredType(this); - return method; - } - - /** - * Add a new method to the inferred type - * - * @param methodName name of the method to add - * @param functionDeclaration the AST Node containing the method bode - * @param nameStart character position (in the source) of the method name - * @return a new inferred method - */ - public InferredMethod addMethod(char [] methodName, IFunctionDeclaration functionDeclaration, int nameStart) { - return this.addMethod(methodName, functionDeclaration, nameStart, false); - } - - /** - * Add a new method to the inferred type - * - * @param methodName name of the method to add - * @param functionDeclaration the AST Node containing the method bode - * @param isConstructor true if it is a constructor - * @return a new inferred method - */ - private InferredMethod addMethod(char [] methodName, IFunctionDeclaration functionDeclaration, int nameStart, boolean isConstructor) { - MethodDeclaration methodDeclaration = (MethodDeclaration)functionDeclaration; - InferredMethod method = findMethod(methodName, methodDeclaration); - if (method==null) { - method=new InferredMethod(methodName,methodDeclaration,this); - if (methodDeclaration.inferredMethod==null) - methodDeclaration.inferredMethod = method; - else - { - if (isConstructor) - { - methodDeclaration.inferredMethod.inType=this; - method.isStatic=methodDeclaration.inferredMethod.isStatic; - method.bits=methodDeclaration.inferredMethod.bits; - methodDeclaration.inferredMethod = method; - } else if (methodDeclaration.inferredMethod.isConstructor) - method.inType=methodDeclaration.inferredMethod.inType; - - } - if (methods==null) - methods=new ArrayList(); - methods.add(method); - - if( !isAnonymous ) - this.updatePositions(methodDeclaration.sourceStart, methodDeclaration.sourceEnd); - method.isConstructor=isConstructor; - method.nameStart = nameStart; - } else { - if (methodDeclaration.inferredMethod==null) { - methodDeclaration.inferredMethod=method; - } - } - - return method; - } - - /** - * Find an inferred method - * - * @param methodName name of the method to find - * @param methodDeclaration not used - * @return the found method, or null - */ - public InferredMethod findMethod(char [] methodName, IFunctionDeclaration methodDeclaration) { - boolean isConstructor= methodName==TypeConstants.INIT; - if (methods!=null) - for (Iterator methodIterator = methods.iterator(); methodIterator.hasNext();) { - InferredMethod method = (InferredMethod) methodIterator.next(); - if (CharOperation.equals(methodName,method.name)) - return method; - if (isConstructor && method.isConstructor) - return method; - } - return null; - - } - - public TypeBinding resolveType(Scope scope, ASTNode node) { - // handle the error here - if (this.resolvedType != null) // is a shared type reference which was already resolved - return this.resolvedType.isValidBinding() ? this.resolvedType : null; // already reported error - - - if (isArray()) - { - TypeBinding memberType = (referenceClass!=null)?referenceClass.resolveType(scope,node):null; - if (memberType==null) - memberType=TypeBinding.UNKNOWN; - this.resolvedType=new ArrayBinding(memberType, 1, scope.compilationUnitScope().environment) ; - - } - else { - if (CharOperation.indexOf('|', name)>0) - { - char[][] names = CharOperation.splitAndTrimOn('|', name); - this.resolvedType=new MultipleTypeBinding(scope,names); - } - else - this.resolvedType = scope.getType(name); - /* the inferred type isn't valid, so don't assign it to the variable */ - if(!this.resolvedType.isValidBinding()) this.resolvedType = null; - } - - - if (this.resolvedType == null) - return null; // detected cycle while resolving hierarchy - if (node!=null && !this.resolvedType.isValidBinding()) { - scope.problemReporter().invalidType(node, this.resolvedType); - return null; - } - if (node!=null && node.isTypeUseDeprecated(this.resolvedType, scope)) - scope.problemReporter().deprecatedType(this.resolvedType, node); - - if( isAnonymous ) - this.resolvedType.tagBits |= TagBits.AnonymousTypeMask; - - return this.resolvedType ; - } - - - - public void dumpReference(StringBuffer sb) - { - sb.append(name); - if (referenceClass!=null) - { - sb.append('('); - referenceClass.dumpReference(sb); - sb.append(')'); - } - } - - public boolean containsMethod(IAbstractFunctionDeclaration inMethod) { - if (methods!=null) - for (Iterator iter = methods.iterator(); iter.hasNext();) { - InferredMethod method = (InferredMethod) iter.next(); - if (method.getFunctionDeclaration()==inMethod) - return true; - } - return false; - } - - - - public ReferenceBinding resolveSuperType(ClassScope classScope) { - if (this.resolvedSuperType != null) - return this.resolvedSuperType; - - if(superClass != null) - this.resolvedSuperType = (ReferenceBinding)classScope.getType(superClass.getName()); - - return this.resolvedSuperType; - } - - public boolean isArray() - { - return CharOperation.equals(ARRAY_NAME, name); - } - - public boolean isFunction() - { - return CharOperation.equals(FUNCTION_NAME, name); - } - - public StringBuffer print(int indent, StringBuffer output) { - printIndent(indent, output); - char[] superName= getSuperClassName(); - output.append("class ").append(name).append(" extends ").append(superName).append("{\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - for (int i=0;i=0 && start0&&end>this.sourceEnd) - this.sourceEnd=end; - } - - public IAbstractFunctionDeclaration declarationOf(MethodBinding methodBinding) { - if (methodBinding != null && this.methods != null) { - for (int i = 0, max = this.methods.size(); i < max; i++) { - InferredMethod method=(InferredMethod) this.methods.get(i); - - if (method.methodBinding==methodBinding) - return method.getFunctionDeclaration(); - } - } - return null; - } - - public boolean isNamed() - { - return !isAnonymous || !CharOperation.prefixEquals(IInferEngine.ANONYMOUS_PREFIX, this.name); - } - - /** - * Set the charactor position (in the source) of the type name - * - * @param start type name position - */ - public void setNameStart(int start) - { - this.nameStart=start; - } - - public int getNameStart() - { - return this.nameStart!= -1 ? this.nameStart : this.sourceStart; - } - - public boolean isEmptyGlobal() - { - return (CharOperation.equals(GLOBAL_NAME, this.name) && - this.numberAttributes==0 && - (this.methods==null || this.methods.isEmpty())); - } - - - /** - *

Adds the name of a type to mix into this type once all of the types have - * been inferred

- * - * @param mixinTypeName the name of the type to mix into this type - */ - public void addMixin(char[] mixinTypeName) - { - if (mixins==null) - mixins=new ArrayList(); - mixins.add(mixinTypeName); - } - -} +/******************************************************************************* + * Copyright (c) 2005, 2013 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.wst.jsdt.core.infer; + +import java.util.ArrayList; +import java.util.Iterator; + +import org.eclipse.wst.jsdt.core.ast.IASTNode; +import org.eclipse.wst.jsdt.core.ast.IAbstractFunctionDeclaration; +import org.eclipse.wst.jsdt.core.ast.IFunctionDeclaration; +import org.eclipse.wst.jsdt.core.compiler.CharOperation; +import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode; +import org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration; +import org.eclipse.wst.jsdt.internal.compiler.ast.ObjectLiteral; +import org.eclipse.wst.jsdt.internal.compiler.lookup.ArrayBinding; +import org.eclipse.wst.jsdt.internal.compiler.lookup.ClassScope; +import org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding; +import org.eclipse.wst.jsdt.internal.compiler.lookup.MultipleTypeBinding; +import org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding; +import org.eclipse.wst.jsdt.internal.compiler.lookup.Scope; +import org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding; +import org.eclipse.wst.jsdt.internal.compiler.lookup.TagBits; +import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding; +import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeConstants; +import org.eclipse.wst.jsdt.internal.compiler.util.HashtableOfObject; +import org.eclipse.wst.jsdt.internal.core.Logger; + + +/** + * The representation of an inferred type. + * + * Provisional API: This class/interface is part of an interim API that is still under development and expected to + * change significantly before reaching stability. It is being made available at this early stage to solicit feedback + * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken + * (repeatedly) as the API evolves. + */ +public class InferredType extends ASTNode { + + char [] name; + public ArrayList methods; + public InferredAttribute[] attributes=new InferredAttribute[5]; + public int numberAttributes=0; + public HashtableOfObject attributesHash = new HashtableOfObject(); + + /** + *

The parent type of this type, or null if this type does not have a parent type

+ * + *

NOTE: This field should not be accessed directly, use the appropriate getter and setter.

+ * + * @see {@link #setSuperType(InferredType)} + * @see {@link #getSuperType()} + */ + public InferredType superClass; + + public InferredType referenceClass; + + public SourceTypeBinding binding; + + /** + * @deprecated this will not remain public forever + * + * @see #isDefinition() + * @see #setIsDefinition(boolean) + */ + public boolean isDefinition; + private TypeBinding resolvedType; + public ClassScope scope; + ReferenceBinding resolvedSuperType; + + public boolean isArray=false; + public boolean isAnonymous=false; + public boolean isObjectLiteral=false; + + private int nameStart = -1; + + public String inferenceProviderID; + public String inferenceStyle; + + public ArrayList mixins; + /** + * @since 1.1 + */ + public int modifiers; + + // in the case where a type extends functions, we sometimes need + // to know the actual function in order to create inferred methods + private IFunctionDeclaration correspondingFunction; + + /** + *

+ * true if this type is a globally visible type, + * false otherwise. + *

+ * + *

+ * EX: The anonymous type for a global variable would be globally visible, + * the anonymous type for a local would not. + *

+ * + * @see #isIndexed() + * @see #setIsGlobal(boolean) + * + * @since 1.2 + */ + private boolean fIsGlobal; + /** + * Contains the InferredTypes that with which this type is synonymous + * + * @see #getSynonyms() + * @see #addSynonym(InferredType) + * + * @since 1.2 + */ + private InferredType[] fSynonyms; + + public final static char[] OBJECT_NAME=new char[]{'O','b','j','e','c','t'}; + + /** + * @deprecated this is not used internally, this will be removed + */ + public final static char[] OBJECT_LITERAL_NAME = new char[]{'{','}'}; + + public final static char[] ARRAY_NAME=new char[]{'A','r','r','a','y'}; + public final static char[] FUNCTION_NAME =new char[]{'F','u','n','c','t','i','o','n'}; + public final static char[] VOID_NAME =new char[]{'v','o','i','d'}; + + /** + * @deprecated - no longer used + */ + public final static char[] GLOBAL_NAME=new char[]{'G','l','o','b','a','l'}; + + /** + * @deprecated this is not used internally, this will be removed + */ + public Object userData; + + /** + * @deprecated this is not used internally, this will be removed + */ + boolean allStatic=false; + + /** + * Create a new inferred type + * + * @param className inferred type name + */ + public InferredType(char [] className) { + this.name=className; + this.sourceStart=-1; + this.fIsGlobal = false; + this.isDefinition = false; + } + + /** + * @since 1.1 + * @return + */ + public int getModifiers() { + return modifiers; + } + + /** + * Gets the name of the inferred type + * + * @return the inferred type name + */ + public char [] getName() { + return name; + } + + /** + * Get the superclass name of the inferred type + * + * @return superclass name + */ + public char [] getSuperClassName() + { + return superClass!=null ? superClass.getName() : OBJECT_NAME; + } + + /** + * Add a new inferred attribute to the inferred type + * + * @param name the attribute name + * @param definer the ASTNode which this attribute is inferred from + * @param nameStart character position (in the source) of the attribute name + * @return a new InferredAttribute + */ + public InferredAttribute addAttribute(char [] name, IASTNode definer, int nameStart) + { + InferredAttribute attribute = findAttribute(name); + if (attribute==null) + { + attribute=new InferredAttribute(name, this, definer); + attribute.node=(ASTNode)definer; + + if (this.numberAttributes == this.attributes.length) + + System.arraycopy( + this.attributes, + 0, + this.attributes = new InferredAttribute[this.numberAttributes * 2], + 0, + this.numberAttributes ); + this.attributes [this.numberAttributes ++] = attribute; + + + attributesHash.put(name, attribute); + + if (!isAnonymous) { + this.updatePositions(definer.sourceStart(), definer.sourceEnd()); + } + } + attribute.nameStart = nameStart; + return attribute; + } + + /** + * Adds a new inferred attribute to the inferred type if it doesn't already exist + * otherwise it replaces the existing one with the new one. + * + * @param name the attribute name + * @param definer the ASTNode which this attribute is inferred from + * @param nameStart character position (in the source) of the attribute name + * @return a inferredAttribute + */ + public InferredAttribute replaceAttribute(char [] name, IASTNode definer, int nameStart) { + InferredAttribute attribute = findAttribute(name); + if (attribute == null) + return addAttribute(name, definer, nameStart); + + attributesHash.removeKey(name); + + InferredAttribute newAttribute = new InferredAttribute(name, this, definer); + newAttribute.node=(ASTNode)definer; + + for (int i = 0; i < this.numberAttributes; i++) { + if (this.attributes[i].equals(attribute)) { + this.attributes [i] = newAttribute; + } + } + attributesHash.put(name, newAttribute); + + if (!isAnonymous) { + this.updatePositions(definer.sourceStart(), definer.sourceEnd()); + } + newAttribute.nameStart = nameStart; + return newAttribute; + } + + /** + * Add an InferredAttribute to this inferred type. + * + * @param newAttribute the attribute to add. + * @return + */ + public InferredAttribute addAttribute(InferredAttribute newAttribute) + { + IASTNode definer=newAttribute.node; + InferredAttribute attribute = findAttribute(newAttribute.name); + if (attribute==null) + { + + if (this.numberAttributes == this.attributes.length) + + System.arraycopy( + this.attributes, + 0, + this.attributes = new InferredAttribute[this.numberAttributes * 2], + 0, + this.numberAttributes ); + this.attributes [this.numberAttributes ++] = newAttribute; + + + attributesHash.put(newAttribute.name, newAttribute); + + if (!isAnonymous) { + if (definer != null) { + this.updatePositions(definer.sourceStart(), definer.sourceEnd()); + } + else { + this.updatePositions(newAttribute.sourceStart(), newAttribute.sourceEnd()); + } + } + } + return newAttribute; + } + /** + * Find the inferred attribute with the given name + * + * @param name name of the attribute to find + * @return the found InferredAttribute, or null if not found + */ + public InferredAttribute findAttribute(char [] name) + { + return (InferredAttribute)attributesHash.get(name); +// if (attributes!=null) +// for (Iterator attrIterator = attributes.iterator(); attrIterator.hasNext();) { +// InferredAttribute attribute = (InferredAttribute) attrIterator.next(); +// if (CharOperation.equals(name,attribute.name)) +// return attribute; +// } +// return null; + } + + + /** + * Add a new constructor method to the inferred type + * + * @param methodName name of the method to add + * @param functionDeclaration the AST Node containing the method bode + * @param nameStart character position (in the source) of the method name + * @return a new inferred method + */ + public InferredMethod addConstructorMethod(char [] methodName, IFunctionDeclaration functionDeclaration, int nameStart) { + InferredMethod method = this.addMethod(methodName, functionDeclaration, nameStart, true); + method.isConstructor = true; + this.setNameStart(nameStart); + //method.getFunctionDeclaration().setInferredType(this); + return method; + } + + /** + * Add a new method to the inferred type + * + * @param methodName name of the method to add + * @param functionDeclaration the AST Node containing the method bode + * @param nameStart character position (in the source) of the method name + * @return a new inferred method + */ + public InferredMethod addMethod(char [] methodName, IFunctionDeclaration functionDeclaration, int nameStart) { + return this.addMethod(methodName, functionDeclaration, nameStart, false); + } + + /** + * Add a new method to the inferred type + * + * @param methodName name of the method to add + * @param functionDeclaration the AST Node containing the method bode + * @param isConstructor true if it is a constructor + * @return a new inferred method + */ + private InferredMethod addMethod(char [] methodName, IFunctionDeclaration functionDeclaration, int nameStart, boolean isConstructor) { + MethodDeclaration methodDeclaration = (MethodDeclaration)functionDeclaration; + InferredMethod method = findMethod(methodName, methodDeclaration); + if (method==null) { + /* if the inferred method for the declaration specifies that it is in a + * type use that one. + * + * This is for the case where a method has been mixed in from another type + * but we still want that method to be reported as defined on the other + * type and not this type + */ + InferredType inType = this; + if(methodDeclaration.getInferredMethod() != null && methodDeclaration.getInferredMethod().inType != null && !isConstructor && + !methodDeclaration.getInferredMethod().isConstructor && + !methodDeclaration.getInferredMethod().inType.isAnonymous && this.isAnonymous) { + inType = methodDeclaration.getInferredMethod().inType; + } + + method=new InferredMethod(methodName,methodDeclaration,inType); + if (methodDeclaration.inferredMethod==null) + methodDeclaration.inferredMethod = method; + else + { + if (isConstructor) + { + methodDeclaration.inferredMethod.inType=this; + method.isStatic=methodDeclaration.inferredMethod.isStatic; + method.bits=methodDeclaration.inferredMethod.bits; + //methodDeclaration.inferredMethod = method; + } //else if (methodDeclaration.inferredMethod.isConstructor) + //method.inType=methodDeclaration.inferredMethod.inType; + + } + if (methods==null) + methods=new ArrayList(); + methods.add(method); + + if(!isAnonymous && !isConstructor) + this.updatePositions(methodDeclaration.sourceStart, methodDeclaration.sourceEnd); + method.isConstructor=isConstructor; + method.nameStart = nameStart; + } else { + if (methodDeclaration.inferredMethod==null) { + methodDeclaration.inferredMethod=method; + } + } + + return method; + } + + /** + * Adds a new inferred method to the inferred type if it doesn't already exist + * otherwise it replaces the existing one with the new one. + * + * @param methodName name of the method to add + * @param functionDeclaration the AST Node containing the method bode + * @param isConstructor true if it is a constructor + * @return an inferred method + */ + private InferredMethod replaceMethod(char [] methodName, IFunctionDeclaration functionDeclaration, int nameStart) { + MethodDeclaration methodDeclaration = (MethodDeclaration) functionDeclaration; + InferredMethod method = findMethod(methodName, methodDeclaration); + if (method == null) + return addMethod(methodName, functionDeclaration, nameStart); + + /* if the inferred method for the declaration specifies that it is in a + * type use that one. + * + * This is for the case where a method has been mixed in from another type + * but we still want that method to be reported as defined on the other + * type and not this type + */ + InferredType inType = this; + if (methodDeclaration.getInferredMethod() != null && methodDeclaration.getInferredMethod().inType != null) { + inType = methodDeclaration.getInferredMethod().inType; + } else { + inType = this; + } + methods.remove(method); + + InferredMethod newMethod = new InferredMethod(methodName, methodDeclaration, inType); + if (methodDeclaration.inferredMethod == null) + methodDeclaration.inferredMethod = newMethod; + else if (methodDeclaration.inferredMethod.isConstructor) + newMethod.inType = methodDeclaration.inferredMethod.inType; + + methods.add(newMethod); + + if (!isAnonymous) + this.updatePositions(methodDeclaration.sourceStart, methodDeclaration.sourceEnd); + newMethod.isConstructor = false; + newMethod.nameStart = nameStart; + + return newMethod; + } + + /** + * Find an inferred method + * + * @param methodName name of the method to find + * @param methodDeclaration not used + * @return the found method, or null + */ + public InferredMethod findMethod(char [] methodName, IFunctionDeclaration methodDeclaration) { + boolean isConstructor= methodName==TypeConstants.INIT; + if (methods!=null) + for (Iterator methodIterator = methods.iterator(); methodIterator.hasNext();) { + InferredMethod method = (InferredMethod) methodIterator.next(); + if (CharOperation.equals(methodName,method.name)) + return method; + if (isConstructor && method.isConstructor) + return method; + } + return null; + + } + + public TypeBinding resolveType(Scope scope, ASTNode node) { + if (scope == null) + return null; + + // handle the error here + if (this.resolvedType != null) // is a shared type reference which was already resolved + return this.resolvedType.isValidBinding() ? this.resolvedType : null; // already reported error + + + if (isArray()) + { + TypeBinding memberType = (referenceClass!=null)?referenceClass.resolveType(scope,node):null; + if (memberType==null) + memberType=TypeBinding.UNKNOWN; + this.resolvedType=new ArrayBinding(memberType, 1, scope.compilationUnitScope().environment) ; + + } + else { + if (CharOperation.indexOf('|', name)>0) + { + char[][] names = CharOperation.splitAndTrimOn('|', name); + this.resolvedType=new MultipleTypeBinding(scope,names); + } + else + this.resolvedType = scope.getType(name); + /* the inferred type isn't valid, so don't assign it to the variable */ + if(!this.resolvedType.isValidBinding()) this.resolvedType = null; + } + + + if (this.resolvedType == null) + return null; // detected cycle while resolving hierarchy + if (node!=null && !this.resolvedType.isValidBinding()) { + scope.problemReporter().invalidType(node, this.resolvedType); + return null; + } + if (node!=null && node.isTypeUseDeprecated(this.resolvedType, scope)) + scope.problemReporter().deprecatedType(this.resolvedType, node); + + if( !isNamed() ) + this.resolvedType.tagBits |= TagBits.AnonymousTypeMask; + + return this.resolvedType ; + } + + + + public void dumpReference(StringBuffer sb) + { + sb.append(name); + if (referenceClass!=null) + { + sb.append('('); + referenceClass.dumpReference(sb); + sb.append(')'); + } + } + + public boolean containsMethod(IAbstractFunctionDeclaration inMethod) { + if (methods!=null) + for (Iterator iter = methods.iterator(); iter.hasNext();) { + InferredMethod method = (InferredMethod) iter.next(); + if (method.getFunctionDeclaration()==inMethod) + return true; + } + return false; + } + + + + public ReferenceBinding resolveSuperType(ClassScope classScope) { + if (this.resolvedSuperType != null) + return this.resolvedSuperType; + + if(superClass != null) { + TypeBinding typeBinding = classScope.getType(superClass.getName()); + if ( typeBinding instanceof ReferenceBinding ) this.resolvedSuperType = (ReferenceBinding)typeBinding; + } + + return this.resolvedSuperType; + } + + public boolean isArray() + { + return CharOperation.equals(ARRAY_NAME, name); + } + + public boolean isFunction() + { + return CharOperation.equals(FUNCTION_NAME, name); + } + + public boolean isVoid() + { + return CharOperation.equals(VOID_NAME, name); + } + + public StringBuffer print(int indent, StringBuffer output) { + printIndent(indent, output); + char[] superName= getSuperClassName(); + output.append("class ").append(name).append(" extends ").append(superName).append("{\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + for (int i=0;i=0 && start0&&end>this.sourceEnd) + this.sourceEnd=end; + } + + public IAbstractFunctionDeclaration declarationOf(MethodBinding methodBinding) { + if (methodBinding != null && this.methods != null) { + for (int i = 0, max = this.methods.size(); i < max; i++) { + InferredMethod method=(InferredMethod) this.methods.get(i); + + if (method.methodBinding==methodBinding) + return method.getFunctionDeclaration(); + } + } + return null; + } + + /** + * @return true if this type is anonymous or the the type + * name starts with the anonymous prefix, false + * otherwise + */ + public boolean isNamed() { + return !isAnonymous || !CharOperation.prefixEquals(IInferEngine.ANONYMOUS_PREFIX, this.name); + } + + /** + * @param modifiers the modifiers to set + * @since 1.1 + */ + public void setModifiers(int modifiers) { + this.modifiers = modifiers; + } + + /** + * Set the charactor position (in the source) of the type name + * + * @param start type name position + */ + public void setNameStart(int start) + { + this.nameStart=start; + } + + public int getNameStart() + { + return this.nameStart!= -1 ? this.nameStart : this.sourceStart; + } + + /** + * @deprecated - no longer used + */ + public boolean isEmptyGlobal() { + return (CharOperation.equals(GLOBAL_NAME, this.name) && this.numberAttributes == 0 && (this.methods == null || this.methods.isEmpty())); + } + + /** + *

Adds the name of a type to mix into this type during the resolving step.

+ * + *

Use {@link #mixin(InferredType)} if the type to mixin is an anonymous type + * since anonymous types are only available at the inference step and will not be + * available at the resolve step when mixins added with this method are mixed in.

+ * + *

NOTE: Do not confuse this with dojo.mixin(), this operation is actually + * more akin to dojo.extend

+ * + * @param mixinTypeName the name of the type to mix into this type + */ + public void addMixin(char[] mixinTypeName) { + if (mixins==null) { + mixins=new ArrayList(); + } + + //prevent duplicates + if(!mixins.contains(mixinTypeName)) { + mixins.add(mixinTypeName); + } + } + + /** + *

Mixes an {@link InferredType} into this {@link InferredType} right now. Thus if the type being + * mixed in changes at all, fields or methods added/removed, at a later point those changes will + * not get reflected in this inferred type. Thus this method should only be used when it is certain the + * mixin type will not change again, such as during the resolving step or an {@link ObjectLiteral} during + * the inference step.

+ * + *

NOTE: Do not confuse this with dojo.mixin(), this operation is actually + * more akin to dojo.extend

+ * + * @param mixin + * @since 1.1 + */ + public void mixin(InferredType mixin) { + if(mixin !=null) { + InferredAttribute[] attributes = mixin.attributes; + ArrayList methods = mixin.methods; + if(methods == null) + methods = new ArrayList(1); + + // get the full list of methods and attributes from the mix class and its super class + InferredType mixSuperType = mixin.getSuperType(); + while(mixSuperType != null && !CharOperation.equals(mixSuperType.getName(), TypeConstants.OBJECT)) { + // attributes + InferredAttribute[] tempAttributes = new InferredAttribute[attributes.length + mixSuperType.numberAttributes]; + System.arraycopy(attributes, 0, tempAttributes, 0, attributes.length); + System.arraycopy(mixSuperType.attributes, 0, tempAttributes, attributes.length - 1, mixSuperType.numberAttributes); + attributes = tempAttributes; + + // methods + if (mixSuperType.methods != null) + methods.addAll(mixSuperType.methods); + mixSuperType = mixSuperType.getSuperType(); + } + + // add attributes to the type + for(int a = 0; a < attributes.length; a++) { + //do not mix in statics + if(attributes[a] != null && !attributes[a].isStatic) { + InferredAttribute attr = this.replaceAttribute( attributes[a].name, attributes[a].node, attributes[a].nameStart); + attr.type=attributes[a].type; + attr.isStatic = false; + attr.nameStart = attributes[a].nameStart; + attr.modifiers = attributes[a].modifiers; + attr.initializationStart = attributes[a].initializationStart; + } + } + + // add functions to the type + for(int m = 0; m < methods.size(); m++) { + InferredMethod functToMixin = (InferredMethod)methods.get(m); + + //do not mix in constructors or statics + if(!functToMixin.isConstructor && !functToMixin.isStatic) { + this.replaceMethod(functToMixin.name, functToMixin.getFunctionDeclaration(), functToMixin.nameStart); + } + } + } + } + + /** + *

Mixes an {@link InferredType} into this {@link InferredType}. By passing true for the second argument, + * objects will be recursively mixed. This means that if a property of the first object is itself an object, + * a mix will be performed if a property with the same key exists in the second object. Otherwise it would be completely + * overriden by the property of the second object. + * + * @param mixin + */ + public void mixin(InferredType mixin, boolean isDeepCopy) { + if (!isDeepCopy) + mixin(mixin); + else if (mixin != null) { + InferredAttribute[] attributes = mixin.attributes; + ArrayList methods = mixin.methods; + if (methods == null) + methods = new ArrayList(1); + + // get the full list of methods and attributes from the mix class and its super class + InferredType mixSuperType = mixin.getSuperType(); + while (mixSuperType != null && !CharOperation.equals(mixSuperType.getName(), TypeConstants.OBJECT)) { + // attributes + InferredAttribute[] tempAttributes = new InferredAttribute[attributes.length + mixSuperType.numberAttributes]; + System.arraycopy(attributes, 0, tempAttributes, 0, attributes.length); + System.arraycopy(mixSuperType.attributes, 0, tempAttributes, attributes.length - 1, mixSuperType.numberAttributes); + attributes = tempAttributes; + + // methods + if (mixSuperType.methods != null) + methods.addAll(mixSuperType.methods); + mixSuperType = mixSuperType.getSuperType(); + } + + // add attributes to the type + for (int a = 0; a < attributes.length; a++) { + //do not mix in statics + if (attributes[a] != null && !attributes[a].isStatic) { + InferredAttribute existingAttr = findAttribute(attributes[a].name); + if (existingAttr != null && existingAttr.type != null && existingAttr.type.isAnonymous) { + existingAttr.type.mixin(attributes[a].type, true); + } + else { + InferredAttribute attr = this.replaceAttribute( attributes[a].name, attributes[a].node, attributes[a].nameStart); + attr.type=attributes[a].type; + attr.isStatic = false; + attr.nameStart = attributes[a].nameStart; + attr.modifiers = attributes[a].modifiers; + attr.initializationStart = attributes[a].initializationStart; + } + } + } + + // add functions to the type + for (int m = 0; m < methods.size(); m++) { + InferredMethod functToMixin = (InferredMethod)methods.get(m); + + //do not mix in constructors or statics + if (!functToMixin.isConstructor && !functToMixin.isStatic) { + this.replaceMethod(functToMixin.name, functToMixin.getFunctionDeclaration(), functToMixin.nameStart); + } + } + } + } + + /** + * @return super {@link InferredType} of this {@link InferredType}, or + * null if none is set + * @since 1.1 + */ + public InferredType getSuperType() { + return this.superClass; + } + + /** + *

Sets the super type of this type unless the given super type is + * itself then this is a no op

+ * + * @param superType {@link InferredType} to set as the super type of this type, + * can not be the same as this type + * @since 1.1 + */ + public void setSuperType(InferredType superType) { + // prevent cycles, and log if someone attempts to create one + InferredType testType = superType; + while (testType != null) { + if (testType == this) { + if (InferEngine.DEBUG) + Logger.log(Logger.WARNING, "InferredType#setSuperType: a hierarchy loop would be caused between: " + new String(getName()) + " and " + new String(superType.getName())); //$NON-NLS-1$ //$NON-NLS-2$ + return; + } + testType = testType.getSuperType(); + } + + this.superClass = superType; + } + + /** + *

+ * Determines if this type should be indexed or not. A type should be indexed if it is named or + * has specifically been set to be a global type. + *

+ * + * @return true if this type should be indexed, false otherwise + * + * @see #isNamed() + * @see #isGlobal() + * + * @since 1.1 + */ + public boolean isIndexed() { + return this.isGlobal() || this.isNamed(); + } + + /** + *

+ * EX: The anonymous type for a global variable would be globally visible, the anonymous type + * for a local would not. + *

+ * + * @param isGlobal + * true if this type is a globally visible type, false + * otherwise. + * + * @since 1.1 + */ + public void setIsGlobal(boolean isGlobal) { + this.fIsGlobal = isGlobal; + } + + /** + * @return true if this type is a globally visible type, false + * otherwise. + * + * @since 1.1 + */ + public boolean isGlobal() { + return this.fIsGlobal; + } + + /** + * @return true if this type is a definition, + * false otherwise + */ + public boolean isDefinition() { + return isDefinition; + } + + /** + * @param isDefinition + * true if this type is a definition, + * false otherwise + */ + public void setIsDefinition(boolean isDefinition) { + this.isDefinition = isDefinition; + } + + /** + * @since 1.2 + * @return the types for which this type is synonymous, or null if none have been set + */ + public InferredType[] getSynonyms() { + return fSynonyms; + } + + /** + * @since 1.2 + * @param type - adds a type for which this type is synonymous + */ + public void addSynonym(InferredType type) { + /* be sure given synonym does not have the same name as this type + * also be sure the new synonym is not the super type of this type + * or that this type is the super type of the given synonym + * + * This situation can arise when a pattern like this is used: + * + * define("foo.BarImpl", "foo.Bar", {}): + * foo.Bar = foo.BarImpl; */ + if((type != this && !CharOperation.equals(type.getName(), this.getName())) && + !((this.getSuperType() != null && CharOperation.equals(type.getName(), this.getSuperType().getName())) || + (type.getSuperType() != null && CharOperation.equals(this.getName(), type.getSuperType().getName())))) { + + if (fSynonyms == null) { + fSynonyms = new InferredType[]{type}; + } else { + boolean alreadyContains = false; + for(int i = 0; i < this.fSynonyms.length && !alreadyContains; ++i) { + alreadyContains = type == this.fSynonyms[i]; + } + + if(!alreadyContains) { + InferredType[] synonyms = new InferredType[fSynonyms.length + 1]; + System.arraycopy(fSynonyms, 0, synonyms, 0, fSynonyms.length); + synonyms[fSynonyms.length] = type; + fSynonyms = synonyms; + } + } + } + } + + + /** + * @return the correspondingFunction + */ + public IFunctionDeclaration getCorrespondingFunction() { + return correspondingFunction; + } + + /** + * @param coorespondingFunction the coorespondingFunction to set + */ + public void setCorrespondingFunction(IFunctionDeclaration coorespondingFunction) { + this.correspondingFunction = coorespondingFunction; + } +} \ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferrenceManager.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferrenceManager.java index e80fe85e..abf69fe5 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferrenceManager.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferrenceManager.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2010 IBM Corporation and others. + * Copyright (c) 2005, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -11,6 +11,7 @@ package org.eclipse.wst.jsdt.core.infer; import java.util.ArrayList; +import java.util.Iterator; import java.util.List; import org.eclipse.core.runtime.CoreException; @@ -21,6 +22,7 @@ import org.eclipse.core.runtime.IExtensionRegistry; import org.eclipse.core.runtime.Platform; import org.eclipse.wst.jsdt.core.JavaScriptCore; import org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration; +import org.eclipse.wst.jsdt.internal.core.Logger; import org.eclipse.wst.jsdt.internal.core.util.Util; @@ -35,6 +37,7 @@ import org.eclipse.wst.jsdt.internal.core.util.Util; */ public class InferrenceManager { + private static final boolean _debugInfer = "true".equalsIgnoreCase(Platform.getDebugOption("org.eclipse.wst.jsdt.core/debug/inferEngine")); //$NON-NLS-1$ //$NON-NLS-2$ public static final String EXTENSION_POINT= "inferrenceSupport"; //$NON-NLS-1$ protected static final String TAG_INFERENCE_PROVIDER = "inferenceProvider"; //$NON-NLS-1$ @@ -74,83 +77,75 @@ public class InferrenceManager { public InferrenceProvider [] getInferenceProviders(IInferenceFile script) { + List proposedProviders = new ArrayList(); InferrenceProvider[] inferenceProviders = getInferenceProviders(); - List extProviders=new ArrayList(inferenceProviders.length); - for (int i = 0; i < inferenceProviders.length; i++) { - int applies = inferenceProviders[i].applysTo(script); - switch (applies) { - case InferrenceProvider.MAYBE_THIS: - extProviders.add(inferenceProviders[i]); - break; - - case InferrenceProvider.ONLY_THIS: - InferrenceProvider [] thisProvider = {inferenceProviders[i]}; - return thisProvider; - - default: - break; - } + if (inferenceProviders.length==1) + return new InferrenceProvider [] {inferenceProviders[0]}; + else if (inferenceProviders.length>1){ + //Always add the default provider - ModuleInferrenceProvider + proposedProviders.add(inferenceProviders[0]); + } + + for (int i = 1; i < inferenceProviders.length; i++) { + + if (inferenceProviders[i].getID().equals(script.getInferenceID())) { + proposedProviders.clear(); + proposedProviders.add(inferenceProviders[0]); + proposedProviders.add(inferenceProviders[i]); + break; } - return (InferrenceProvider [] )extProviders.toArray(new InferrenceProvider[extProviders.size()]); - } - - - - public IInferEngine [] getInferenceEngines(CompilationUnitDeclaration script) - { - InferrenceProvider[] inferenceProviders = getInferenceProviders(); - if (inferenceProviders.length==1) - return getSingleEngine(inferenceProviders[0]); - - List extEngines=new ArrayList(); - for (int i = 0; i < inferenceProviders.length; i++) { - if (script.compilationResult!=null && script.compilationResult.compilationUnit!=null) - { - String inferenceID = script.compilationResult.compilationUnit.getInferenceID(); - if (inferenceProviders[i].getID().equals(inferenceID)) { - return getSingleEngine(inferenceProviders[i]); -// InferEngine eng=inferenceProviders[i].getInferEngine(); -// eng.appliesTo=InferrenceProvider.MAYBE_THIS; -// eng.inferenceProvider=inferenceProviders[i]; -// extEngines.add(eng); -// continue; - } - } - int applies = InferrenceProvider.NOT_THIS; - try { - applies = inferenceProviders[i].applysTo(script); - } catch (Exception e) { - // TODO Auto-generated catch block - Util.log(e, "exception in inference provider "+inferenceProviders[i].getID()); - } - switch (applies) { + int applies = InferrenceProvider.NOT_THIS; + try { + applies = inferenceProviders[i].applysTo(script); + } catch (Exception e) { + Util.log(e, "exception in inference provider "+inferenceProviders[i].getID()); + } + switch (applies) { case InferrenceProvider.MAYBE_THIS: - IInferEngine eng=inferenceProviders[i].getInferEngine(); - extEngines.add(eng); + proposedProviders.add(inferenceProviders[i]); break; case InferrenceProvider.ONLY_THIS: - return getSingleEngine(inferenceProviders[i]); - + proposedProviders.clear(); + proposedProviders.add(inferenceProviders[0]); + proposedProviders.add(inferenceProviders[i]); + return (InferrenceProvider [] )proposedProviders.toArray(new InferrenceProvider[proposedProviders.size()]); default: break; - } } - return (IInferEngine [] )extEngines.toArray(new IInferEngine[extEngines.size()]); + } + if (_debugInfer){ + String proposedProvidersString = ""; + Iterator providers = proposedProviders.iterator(); + while(providers.hasNext()) + proposedProvidersString += ((InferrenceProvider)providers.next()).getID().toString()+", "; + Logger.log(Logger.INFO_DEBUG, "Proposed Inference Providers: " + proposedProvidersString); + } + + return (InferrenceProvider [] )proposedProviders.toArray(new InferrenceProvider[proposedProviders.size()]); } - - private IInferEngine [] getSingleEngine(InferrenceProvider provider) + /** + * The base Inference Engine is always added first. This method adds + * additional inference engines. + * + * @param script + * @return + */ + public IInferEngine [] getInferenceEngines(CompilationUnitDeclaration script) { - IInferEngine engine=provider.getInferEngine(); - IInferEngine [] thisEngine = {engine}; - return thisEngine; + List proposedEngines = new ArrayList(); + InferrenceProvider[] inferenceProviders = getInferenceProviders(script); + + for (int i = 0; i < inferenceProviders.length; i++) { + proposedEngines.add(inferenceProviders[i].getInferEngine()) ; + } + return (IInferEngine [] )proposedEngines.toArray(new IInferEngine[proposedEngines.size()]); } - protected void loadInferenceExtensions() { IExtensionRegistry registry = Platform.getExtensionRegistry(); ArrayList extList = new ArrayList(); diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferrenceProvider.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferrenceProvider.java index d5dfc70c..d9621bd5 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferrenceProvider.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/infer/InferrenceProvider.java @@ -12,82 +12,56 @@ package org.eclipse.wst.jsdt.core.infer; /** - * Implemented by contributors to the - * org.eclipse.wst.jsdt.core.infer.inferrenceSupport extension point + * Implemented by contributors to the org.eclipse.wst.jsdt.core.infer.inferrenceSupport extension point * - * Provisional API: This class/interface is part of an interim API that is - * still under development and expected to change significantly before - * reaching stability. It is being made available at this early stage to - * solicit feedback from pioneering adopters on the understanding that any - * code that uses this API will almost certainly be broken (repeatedly) as the - * API evolves. + * Provisional API: This class/interface is part of an interim API that is still under development and expected to + * change significantly before reaching stability. It is being made available at this early stage to solicit feedback + * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken + * (repeatedly) as the API evolves. */ public interface InferrenceProvider { - + /** - *

- * Indicates that this InferrenceProvider, and its engine, are the - * only ones that should apply to a script file. - *

- *

- * Its use is discouraged. - *

+ *

Indicates that this InferrenceProvider, and its engine, are the only ones that should apply.

+ *

Its use is discouraged.

*/ public static final int ONLY_THIS = 1; /** - *

- * Indicates that this InferrenceProvider, and its engine, do not apply to - * a script file. - *

+ *

Indicates that this InferrenceProvider, and its engine, do not apply.

*/ public static final int NOT_THIS = 2; - + /** - *

- * Indicates that this InferrenceProvider, and its engine, should - * also apply to a script file. As multiple providers may - * be required and used to completely understand a script file, this value - * is suggested as a default. Care should then be taken to avoid - * duplicating the contributions of the default provider. - *

+ *

Indicates that this InferrenceProvider, and its engine, should apply to a script file.

*/ public static final int MAYBE_THIS = 3; - + /** - * Get the inference engine for this inference provider, or null if one - * will not be provided. Implementors returning null are expected to have - * returned {@link #NOT_THIS} from all calls to {@link #getInferEngine()} - * + * Get the inference engine for this inference provider, or null if one will not be provided. Implementors returning null are expected to return {@link #NOT_THIS} for all calls to {@link #getInferEngine()} * @return an inference engine */ public IInferEngine getInferEngine(); - - + + /** * Determine if this inference provider applies to a script - * - * @param scriptFile - * the script on which the inferencing will be done - * @return {@link #ONLY_THIS}, {@link #NOT_THIS}, {@link #MAYBE_THIS} - * depending on how much this inference provider applies to the - * specified script. See the documentation for each constant for - * when each should be used. + * @param scriptFile The script that the inferencing will be done for + * @return {@link #ONLY_THIS}, {@link #NOT_THIS}, {@link #MAYBE_THIS} depending on how much + * this inference provider applies to the specified script. */ public int applysTo(IInferenceFile scriptFile); /** * Get the inference provider ID - * * @return the id of this inference provider */ public String getID(); - + /** - * @return the ResolutionConfiguration used to resolve the inferred - * classes + * @return the ResolutionConfiguration used to resolve the inferred classes */ public ResolutionConfiguration getResolutionConfiguration(); diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/messages.properties b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/messages.properties index 0339effc..51f1f548 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/messages.properties +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/messages.properties @@ -1 +1,13 @@ +############################################################################### +# Copyright (c) 2011 IBM Corporation and others. +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Eclipse Public License v1.0 +# which accompanies this distribution, and is available at +# http://www.eclipse.org/legal/epl-v10.html +# +# Contributors: +# IBM Corporation - initial API and implementation +############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR LibrarySuperType.0={0}() in {1} diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/FieldReferenceMatch.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/FieldReferenceMatch.java index 4e174d39..0d2dd768 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/FieldReferenceMatch.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/FieldReferenceMatch.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/MethodReferenceMatch.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/MethodReferenceMatch.java index bbce4dbe..f16e447e 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/MethodReferenceMatch.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/MethodReferenceMatch.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/ModuleMatchRequestor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/ModuleMatchRequestor.java new file mode 100644 index 00000000..36ba503e --- /dev/null +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/ModuleMatchRequestor.java @@ -0,0 +1,21 @@ +/******************************************************************************* + * Copyright (c) 2013 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.wst.jsdt.core.search; + +import org.eclipse.wst.jsdt.core.IJavaScriptElement; + + +public abstract class ModuleMatchRequestor { + + public void acceptElementMatch(IJavaScriptElement match) { + + } +} diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/SearchEngine.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/SearchEngine.java index 220ffbbd..8695f2d6 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/SearchEngine.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/SearchEngine.java @@ -1,631 +1,889 @@ -/******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.jsdt.core.search; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.wst.jsdt.core.IJavaScriptElement; -import org.eclipse.wst.jsdt.core.IJavaScriptUnit; -import org.eclipse.wst.jsdt.core.IType; -import org.eclipse.wst.jsdt.core.JavaScriptModelException; -import org.eclipse.wst.jsdt.core.WorkingCopyOwner; -import org.eclipse.wst.jsdt.internal.core.search.BasicSearchEngine; -import org.eclipse.wst.jsdt.internal.core.search.TypeNameMatchRequestorWrapper; -import org.eclipse.wst.jsdt.internal.core.search.TypeNameRequestorWrapper; - -/** - * A {@link SearchEngine} searches for JavaScript elements following a search pattern. - * The search can be limited to a search scope. - *

- * Various search patterns can be created using the factory methods - * {@link SearchPattern#createPattern(String, int, int, int)}, {@link SearchPattern#createPattern(IJavaScriptElement, int)}, - * {@link SearchPattern#createOrPattern(SearchPattern, SearchPattern)}. - *

- *

For example, one can search for references to a method in the hierarchy of a type, - * or one can search for the declarations of types starting with "Abstract" in a project. - *

- *

- * This class may be instantiated; it is not intended to be subclassed. - *

- * - * Provisional API: This class/interface is part of an interim API that is still under development and expected to - * change significantly before reaching stability. It is being made available at this early stage to solicit feedback - * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken - * (repeatedly) as the API evolves. - */ -public class SearchEngine { - - // Search engine now uses basic engine functionalities - private BasicSearchEngine basicEngine; - - /** - * Creates a new search engine. - */ - public SearchEngine() { - this.basicEngine = new BasicSearchEngine(); - } - - /** - * Creates a new search engine with a list of working copies that will take precedence over - * their original javascript unit s in the subsequent search operations. - *

- * Note that passing an empty working copy will be as if the original compilation - * unit had been deleted.

- *

- * Since 3.0 the given working copies take precedence over primary working copies (if any). - * - * @param workingCopies the working copies that take precedence over their original javascript unit s - * - */ - public SearchEngine(IJavaScriptUnit[] workingCopies) { - this.basicEngine = new BasicSearchEngine(workingCopies); - } - /** - * Creates a new search engine with the given working copy owner. - * The working copies owned by this owner will take precedence over - * the primary javascript unit s in the subsequent search operations. - * - * @param workingCopyOwner the owner of the working copies that take precedence over their original javascript unit s - * - */ - public SearchEngine(WorkingCopyOwner workingCopyOwner) { - this.basicEngine = new BasicSearchEngine(workingCopyOwner); - } - - /** - * Returns a JavaScript search scope limited to the hierarchy of the given type. - * The JavaScript elements resulting from a search with this scope will - * be types in this hierarchy, or members of the types in this hierarchy. - * - * @param type the focus of the hierarchy scope - * @return a new hierarchy scope - * @exception JavaScriptModelException if the hierarchy could not be computed on the given type - */ - public static IJavaScriptSearchScope createHierarchyScope(IType type) throws JavaScriptModelException { - return BasicSearchEngine.createHierarchyScope(type); - } - - /** - * Returns a JavaScript search scope limited to the hierarchy of the given type. - * When the hierarchy is computed, the types defined in the working copies owned - * by the given owner take precedence over the original javascript unit s. - * The JavaScript elements resulting from a search with this scope will - * be types in this hierarchy, or members of the types in this hierarchy. - * - * @param type the focus of the hierarchy scope - * @param owner the owner of working copies that take precedence over original javascript unit s - * @return a new hierarchy scope - * @exception JavaScriptModelException if the hierarchy could not be computed on the given type - * - */ - public static IJavaScriptSearchScope createHierarchyScope(IType type, WorkingCopyOwner owner) throws JavaScriptModelException { - return BasicSearchEngine.createHierarchyScope(type, owner); - } - - /** - * Returns a JavaScript search scope limited to the given JavaScript elements. - * The JavaScript elements resulting from a search with this scope will - * be children of the given elements. - *

- * If an element is an IJavaScriptProject, then the project's source folders, - * its jars (external and internal) and its referenced projects (with their source - * folders and jars, recursively) will be included. - * If an element is an IPackageFragmentRoot, then only the package fragments of - * this package fragment root will be included. - * If an element is an IPackageFragment, then only the javascript unit and class - * files of this package fragment will be included. Subpackages will NOT be - * included.

- *

- * In other words, this is equivalent to using SearchEngine.createJavaSearchScope(elements, true).

- * - * @param elements the JavaScript elements the scope is limited to - * @return a new JavaScript search scope - * - */ - public static IJavaScriptSearchScope createJavaSearchScope(IJavaScriptElement[] elements) { - return BasicSearchEngine.createJavaSearchScope(elements); - } - - /** - * Returns a JavaScript search scope limited to the given JavaScript elements. - * The JavaScript elements resulting from a search with this scope will - * be children of the given elements. - * - * If an element is an IJavaScriptProject, then the project's source folders, - * its jars (external and internal) and - if specified - its referenced projects - * (with their source folders and jars, recursively) will be included. - * If an element is an IPackageFragmentRoot, then only the package fragments of - * this package fragment root will be included. - * If an element is an IPackageFragment, then only the javascript unit and class - * files of this package fragment will be included. Subpackages will NOT be - * included. - * - * @param elements the JavaScript elements the scope is limited to - * @param includeReferencedProjects a flag indicating if referenced projects must be - * recursively included - * @return a new JavaScript search scope - * - */ - public static IJavaScriptSearchScope createJavaSearchScope(IJavaScriptElement[] elements, boolean includeReferencedProjects) { - return BasicSearchEngine.createJavaSearchScope(elements, includeReferencedProjects); - } - - /** - * Returns a JavaScript search scope limited to the given JavaScript elements. - * The JavaScript elements resulting from a search with this scope will - * be children of the given elements. - * - * If an element is an IJavaScriptProject, then it includes: - * - its source folders if IJavaScriptSearchScope.SOURCES is specified, - * - its application libraries (internal and external jars, class folders that are on the raw includepath, - * or the ones that are coming from a includepath path variable, - * or the ones that are coming from a includepath container with the K_APPLICATION kind) - * if IJavaScriptSearchScope.APPLICATION_LIBRARIES is specified - * - its system libraries (internal and external jars, class folders that are coming from an - * IJsGlobalScopeContainer with the K_SYSTEM kind) - * if IJavaScriptSearchScope.APPLICATION_LIBRARIES is specified - * - its referenced projects (with their source folders and jars, recursively) - * if IJavaScriptSearchScope.REFERENCED_PROJECTS is specified. - * If an element is an IPackageFragmentRoot, then only the package fragments of - * this package fragment root will be included. - * If an element is an IPackageFragment, then only the javascript unit and class - * files of this package fragment will be included. Subpackages will NOT be - * included. - * - * @param elements the JavaScript elements the scope is limited to - * @param includeMask the bit-wise OR of all include types of interest - * @return a new JavaScript search scope - * @see IJavaScriptSearchScope#SOURCES - * @see IJavaScriptSearchScope#APPLICATION_LIBRARIES - * @see IJavaScriptSearchScope#SYSTEM_LIBRARIES - * @see IJavaScriptSearchScope#REFERENCED_PROJECTS - * - */ - public static IJavaScriptSearchScope createJavaSearchScope(IJavaScriptElement[] elements, int includeMask) { - return BasicSearchEngine.createJavaSearchScope(elements, includeMask); - } - - /** - * Create a type name match on a given type with specific modifiers. - * - * @param type The javascript model handle of the type - * @param modifiers Modifiers of the type - * @return A non-null match on the given type. - * - */ - public static TypeNameMatch createTypeNameMatch(IType type, int modifiers) { - return BasicSearchEngine.createTypeNameMatch(type, modifiers); - } - - /** - * Returns a JavaScript search scope with the workspace as the only limit. - * - * @return a new workspace scope - */ - public static IJavaScriptSearchScope createWorkspaceScope() { - return BasicSearchEngine.createWorkspaceScope(); - } - /** - * Returns a new default JavaScript search participant. - * - * @return a new default JavaScript search participant - * - */ - public static SearchParticipant getDefaultSearchParticipant() { - return BasicSearchEngine.getDefaultSearchParticipant(); - } - - /** - * Searches for matches of a given search pattern. Search patterns can be created using helper - * methods (from a String pattern or a JavaScript element) and encapsulate the description of what is - * being searched (for example, search method declarations in a case sensitive way). - * - * @param pattern the pattern to search - * @param participants the particpants in the search - * @param scope the search scope - * @param requestor the requestor to report the matches to - * @param monitor the progress monitor used to report progress - * @exception CoreException if the search failed. Reasons include: - *
    - *
  • the includepath is incorrectly set
  • - *
- * - */ - public void search(SearchPattern pattern, SearchParticipant[] participants, IJavaScriptSearchScope scope, SearchRequestor requestor, IProgressMonitor monitor) throws CoreException { - this.basicEngine.search(pattern, participants, scope, requestor, monitor); - } - - /** - * Searches for all top-level types and member types in the given scope. - * The search can be selecting specific types (given a package name using specific match mode - * and/or a type name using another specific match mode). - * - * @param packageName the full name of the package of the searched types, or a prefix for this - * package, or a wild-carded string for this package. - * May be null, then any package name is accepted. - * @param typeName the dot-separated qualified name of the searched type (the qualification include - * the enclosing types if the searched type is a member type), or a prefix - * for this type, or a wild-carded string for this type. - * May be null, then any type name is accepted. - * @param packageMatchRule one of - *
    - *
  • {@link SearchPattern#R_EXACT_MATCH} if the package name and type name are the full names - * of the searched types.
  • - *
  • {@link SearchPattern#R_PREFIX_MATCH} if the package name and type name are prefixes of the names - * of the searched types.
  • - *
  • {@link SearchPattern#R_PATTERN_MATCH} if the package name and type name contain wild-cards.
  • - *
  • {@link SearchPattern#R_CAMELCASE_MATCH} if type name are camel case of the names of the searched types.
  • - *
- * combined with {@link SearchPattern#R_CASE_SENSITIVE}, - * e.g. {@link SearchPattern#R_EXACT_MATCH} | {@link SearchPattern#R_CASE_SENSITIVE} if an exact and case sensitive match is requested, - * or {@link SearchPattern#R_PREFIX_MATCH} if a prefix non case sensitive match is requested. - * @param typeMatchRule one of - *
    - *
  • {@link SearchPattern#R_EXACT_MATCH} if the package name and type name are the full names - * of the searched types.
  • - *
  • {@link SearchPattern#R_PREFIX_MATCH} if the package name and type name are prefixes of the names - * of the searched types.
  • - *
  • {@link SearchPattern#R_PATTERN_MATCH} if the package name and type name contain wild-cards.
  • - *
  • {@link SearchPattern#R_CAMELCASE_MATCH} if type name are camel case of the names of the searched types.
  • - *
- * combined with {@link SearchPattern#R_CASE_SENSITIVE}, - * e.g. {@link SearchPattern#R_EXACT_MATCH} | {@link SearchPattern#R_CASE_SENSITIVE} if an exact and case sensitive match is requested, - * or {@link SearchPattern#R_PREFIX_MATCH} if a prefix non case sensitive match is requested. - * @param searchFor determines the nature of the searched elements - *
    - *
  • {@link IJavaScriptSearchConstants#CLASS}: only look for classes
  • - *
  • {@link IJavaScriptSearchConstants#INTERFACE}: only look for interfaces
  • - *
  • {@link IJavaScriptSearchConstants#ENUM}: only look for enumeration
  • - *
  • {@link IJavaScriptSearchConstants#ANNOTATION_TYPE}: only look for annotation type
  • - *
  • {@link IJavaScriptSearchConstants#CLASS_AND_ENUM}: only look for classes and enumerations
  • - *
  • {@link IJavaScriptSearchConstants#CLASS_AND_INTERFACE}: only look for classes and interfaces
  • - *
  • {@link IJavaScriptSearchConstants#TYPE}: look for all types (ie. classes, interfaces, enum and annotation types)
  • - *
- * @param scope the scope to search in - * @param nameRequestor the requestor that collects the results of the search - * @param waitingPolicy one of - *
    - *
  • {@link IJavaScriptSearchConstants#FORCE_IMMEDIATE_SEARCH} if the search should start immediately
  • - *
  • {@link IJavaScriptSearchConstants#CANCEL_IF_NOT_READY_TO_SEARCH} if the search should be cancelled if the - * underlying indexer has not finished indexing the workspace
  • - *
  • {@link IJavaScriptSearchConstants#WAIT_UNTIL_READY_TO_SEARCH} if the search should wait for the - * underlying indexer to finish indexing the workspace
  • - *
- * @param progressMonitor the progress monitor to report progress to, or null if no progress - * monitor is provided - * @exception JavaScriptModelException if the search failed. Reasons include: - *
    - *
  • the includepath is incorrectly set
  • - *
- * - */ - public void searchAllTypeNames( - final char[] packageName, - final int packageMatchRule, - final char[] typeName, - final int typeMatchRule, - int searchFor, - IJavaScriptSearchScope scope, - final TypeNameRequestor nameRequestor, - int waitingPolicy, - IProgressMonitor progressMonitor) throws JavaScriptModelException { - - TypeNameRequestorWrapper requestorWrapper = new TypeNameRequestorWrapper(nameRequestor); - this.basicEngine.searchAllTypeNames(packageName, packageMatchRule, typeName, typeMatchRule, searchFor, scope, requestorWrapper, waitingPolicy, progressMonitor); - } - - /** - * Searches for all top-level types and member types in the given scope. - * The search can be selecting specific types (given a package name using specific match mode - * and/or a type name using another specific match mode). - *

- * Provided {@link TypeNameMatchRequestor} requestor will collect {@link TypeNameMatch} - * matches found during the search. - *

- * - * @param packageName the full name of the package of the searched types, or a prefix for this - * package, or a wild-carded string for this package. - * May be null, then any package name is accepted. - * @param packageMatchRule one of - *
    - *
  • {@link SearchPattern#R_EXACT_MATCH} if the package name and type name are the full names - * of the searched types.
  • - *
  • {@link SearchPattern#R_PREFIX_MATCH} if the package name and type name are prefixes of the names - * of the searched types.
  • - *
  • {@link SearchPattern#R_PATTERN_MATCH} if the package name and type name contain wild-cards.
  • - *
  • {@link SearchPattern#R_CAMELCASE_MATCH} if type name are camel case of the names of the searched types.
  • - *
- * combined with {@link SearchPattern#R_CASE_SENSITIVE}, - * e.g. {@link SearchPattern#R_EXACT_MATCH} | {@link SearchPattern#R_CASE_SENSITIVE} if an exact and case sensitive match is requested, - * or {@link SearchPattern#R_PREFIX_MATCH} if a prefix non case sensitive match is requested. - * @param typeName the dot-separated qualified name of the searched type (the qualification include - * the enclosing types if the searched type is a member type), or a prefix - * for this type, or a wild-carded string for this type. - * May be null, then any type name is accepted. - * @param typeMatchRule one of - *
    - *
  • {@link SearchPattern#R_EXACT_MATCH} if the package name and type name are the full names - * of the searched types.
  • - *
  • {@link SearchPattern#R_PREFIX_MATCH} if the package name and type name are prefixes of the names - * of the searched types.
  • - *
  • {@link SearchPattern#R_PATTERN_MATCH} if the package name and type name contain wild-cards.
  • - *
  • {@link SearchPattern#R_CAMELCASE_MATCH} if type name are camel case of the names of the searched types.
  • - *
- * combined with {@link SearchPattern#R_CASE_SENSITIVE}, - * e.g. {@link SearchPattern#R_EXACT_MATCH} | {@link SearchPattern#R_CASE_SENSITIVE} if an exact and case sensitive match is requested, - * or {@link SearchPattern#R_PREFIX_MATCH} if a prefix non case sensitive match is requested. - * @param searchFor determines the nature of the searched elements - *
    - *
  • {@link IJavaScriptSearchConstants#CLASS}: only look for classes
  • - *
  • {@link IJavaScriptSearchConstants#INTERFACE}: only look for interfaces
  • - *
  • {@link IJavaScriptSearchConstants#ENUM}: only look for enumeration
  • - *
  • {@link IJavaScriptSearchConstants#ANNOTATION_TYPE}: only look for annotation type
  • - *
  • {@link IJavaScriptSearchConstants#CLASS_AND_ENUM}: only look for classes and enumerations
  • - *
  • {@link IJavaScriptSearchConstants#CLASS_AND_INTERFACE}: only look for classes and interfaces
  • - *
  • {@link IJavaScriptSearchConstants#TYPE}: look for all types (ie. classes, interfaces, enum and annotation types)
  • - *
- * @param scope the scope to search in - * @param nameMatchRequestor the {@link TypeNameMatchRequestor requestor} that collects - * {@link TypeNameMatch matches} of the search. - * @param waitingPolicy one of - *
    - *
  • {@link IJavaScriptSearchConstants#FORCE_IMMEDIATE_SEARCH} if the search should start immediately
  • - *
  • {@link IJavaScriptSearchConstants#CANCEL_IF_NOT_READY_TO_SEARCH} if the search should be cancelled if the - * underlying indexer has not finished indexing the workspace
  • - *
  • {@link IJavaScriptSearchConstants#WAIT_UNTIL_READY_TO_SEARCH} if the search should wait for the - * underlying indexer to finish indexing the workspace
  • - *
- * @param progressMonitor the progress monitor to report progress to, or null if no progress - * monitor is provided - * @exception JavaScriptModelException if the search failed. Reasons include: - *
    - *
  • the includepath is incorrectly set
  • - *
- * - */ - public void searchAllTypeNames( - final char[] packageName, - final int packageMatchRule, - final char[] typeName, - final int typeMatchRule, - int searchFor, - IJavaScriptSearchScope scope, - final TypeNameMatchRequestor nameMatchRequestor, - int waitingPolicy, - IProgressMonitor progressMonitor) throws JavaScriptModelException { - - TypeNameMatchRequestorWrapper requestorWrapper = new TypeNameMatchRequestorWrapper(nameMatchRequestor, scope); - this.basicEngine.searchAllTypeNames(packageName, packageMatchRule, typeName, typeMatchRule, searchFor, scope, requestorWrapper, waitingPolicy, progressMonitor); - } - - /** - * Searches for all top-level types and member types in the given scope matching any of the given qualifications - * and type names in a case sensitive way. - * - * @param qualifications the qualified name of the package/enclosing type of the searched types. - * May be null, then any package name is accepted. - * @param typeNames the simple names of the searched types. - * If this parameter is null, then no type will be found. - * @param scope the scope to search in - * @param nameRequestor the requestor that collects the results of the search - * @param waitingPolicy one of - *
    - *
  • {@link IJavaScriptSearchConstants#FORCE_IMMEDIATE_SEARCH} if the search should start immediately
  • - *
  • {@link IJavaScriptSearchConstants#CANCEL_IF_NOT_READY_TO_SEARCH} if the search should be cancelled if the - * underlying indexer has not finished indexing the workspace
  • - *
  • {@link IJavaScriptSearchConstants#WAIT_UNTIL_READY_TO_SEARCH} if the search should wait for the - * underlying indexer to finish indexing the workspace
  • - *
- * @param progressMonitor the progress monitor to report progress to, or null if no progress - * monitor is provided - * @exception JavaScriptModelException if the search failed. Reasons include: - *
    - *
  • the includepath is incorrectly set
  • - *
- * - */ - public void searchAllTypeNames( - final char[][] qualifications, - final char[][] typeNames, - IJavaScriptSearchScope scope, - final TypeNameRequestor nameRequestor, - int waitingPolicy, - IProgressMonitor progressMonitor) throws JavaScriptModelException { - - TypeNameRequestorWrapper requestorWrapper = new TypeNameRequestorWrapper(nameRequestor); - this.basicEngine.searchAllTypeNames( - qualifications, - typeNames, - SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE, - IJavaScriptSearchConstants.TYPE, - scope, - requestorWrapper, - waitingPolicy, - progressMonitor); - } - - /** - * Searches for all top-level types and member types in the given scope matching any of the given qualifications - * and type names in a case sensitive way. - *

- * Provided {@link TypeNameMatchRequestor} requestor will collect {@link TypeNameMatch} - * matches found during the search. - *

- * - * @param qualifications the qualified name of the package/enclosing type of the searched types. - * May be null, then any package name is accepted. - * @param typeNames the simple names of the searched types. - * If this parameter is null, then no type will be found. - * @param scope the scope to search in - * @param nameMatchRequestor the {@link TypeNameMatchRequestor requestor} that collects - * {@link TypeNameMatch matches} of the search. - * @param waitingPolicy one of - *
    - *
  • {@link IJavaScriptSearchConstants#FORCE_IMMEDIATE_SEARCH} if the search should start immediately
  • - *
  • {@link IJavaScriptSearchConstants#CANCEL_IF_NOT_READY_TO_SEARCH} if the search should be cancelled if the - * underlying indexer has not finished indexing the workspace
  • - *
  • {@link IJavaScriptSearchConstants#WAIT_UNTIL_READY_TO_SEARCH} if the search should wait for the - * underlying indexer to finish indexing the workspace
  • - *
- * @param progressMonitor the progress monitor to report progress to, or null if no progress - * monitor is provided - * @exception JavaScriptModelException if the search failed. Reasons include: - *
    - *
  • the includepath is incorrectly set
  • - *
- * - */ - public void searchAllTypeNames( - final char[][] qualifications, - final char[][] typeNames, - IJavaScriptSearchScope scope, - final TypeNameMatchRequestor nameMatchRequestor, - int waitingPolicy, - IProgressMonitor progressMonitor) throws JavaScriptModelException { - - TypeNameMatchRequestorWrapper requestorWrapper = new TypeNameMatchRequestorWrapper(nameMatchRequestor, scope); - this.basicEngine.searchAllTypeNames( - qualifications, - typeNames, - SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE, - IJavaScriptSearchConstants.TYPE, - scope, - requestorWrapper, - waitingPolicy, - progressMonitor); - } - - /** - * Searches for all declarations of the fields accessed in the given element. - * The element can be a javascript unit , a source type, or a source method. - * Reports the field declarations using the given requestor. - *

- * Consider the following code: - * - *

-	 *		class A {
-	 *			int field1;
-	 *		}
-	 *		class B extends A {
-	 *			String value;
-	 *		}
-	 *		class X {
-	 *			void test() {
-	 *				B b = new B();
-	 *				System.out.println(b.value + b.field1);
-	 *			};
-	 *		}
-	 * 
- * - * then searching for declarations of accessed fields in method - * X.test() would collect the fields - * B.value and A.field1. - *

- * - * @param enclosingElement the method, type, or javascript unit to be searched in - * @param requestor a callback object to which each match is reported - * @param monitor the progress monitor used to report progress - * @exception JavaScriptModelException if the search failed. Reasons include: - *
    - *
  • the element doesn't exist
  • - *
  • the includepath is incorrectly set
  • - *
- * - */ - public void searchDeclarationsOfAccessedFields(IJavaScriptElement enclosingElement, SearchRequestor requestor, IProgressMonitor monitor) throws JavaScriptModelException { - this.basicEngine.searchDeclarationsOfAccessedFields(enclosingElement, requestor, monitor); - } - - /** - * Searches for all declarations of the types referenced in the given element. - * The element can be a javascript unit , a source type, or a source method. - * Reports the type declarations using the given requestor. - *

- * Consider the following code: - * - *

-	 *		class A {
-	 *		}
-	 *		class B extends A {
-	 *		}
-	 *		interface I {
-	 *		  int VALUE = 0;
-	 *		}
-	 *		class X {
-	 *			void test() {
-	 *				B b = new B();
-	 *				this.foo(b, I.VALUE);
-	 *			};
-	 *		}
-	 * 
- * - * then searching for declarations of referenced types in method X.test() - * would collect the class B and the interface I. - *

- * - * @param enclosingElement the method, type, or javascript unit to be searched in - * @param requestor a callback object to which each match is reported - * @param monitor the progress monitor used to report progress - * @exception JavaScriptModelException if the search failed. Reasons include: - *
    - *
  • the element doesn't exist
  • - *
  • the includepath is incorrectly set
  • - *
- * - */ - public void searchDeclarationsOfReferencedTypes(IJavaScriptElement enclosingElement, SearchRequestor requestor, IProgressMonitor monitor) throws JavaScriptModelException { - this.basicEngine.searchDeclarationsOfReferencedTypes(enclosingElement, requestor, monitor); - } - - /** - * Searches for all declarations of the methods invoked in the given element. - * The element can be a javascript unit , a source type, or a source method. - * Reports the method declarations using the given requestor. - *

- * Consider the following code: - * - *

-	 *		class A {
-	 *			void foo() {};
-	 *			void bar() {};
-	 *		}
-	 *		class B extends A {
-	 *			void foo() {};
-	 *		}
-	 *		class X {
-	 *			void test() {
-	 *				A a = new B();
-	 *				a.foo();
-	 *				B b = (B)a;
-	 *				b.bar();
-	 *			};
-	 *		}
-	 * 
- * - * then searching for declarations of sent messages in method - * X.test() would collect the methods - * A.foo(), B.foo(), and A.bar(). - *

- * - * @param enclosingElement the method, type, or javascript unit to be searched in - * @param requestor a callback object to which each match is reported - * @param monitor the progress monitor used to report progress - * @exception JavaScriptModelException if the search failed. Reasons include: - *
    - *
  • the element doesn't exist
  • - *
  • the includepath is incorrectly set
  • - *
- * - */ - public void searchDeclarationsOfSentMessages(IJavaScriptElement enclosingElement, SearchRequestor requestor, IProgressMonitor monitor) throws JavaScriptModelException { - this.basicEngine.searchDeclarationsOfSentMessages(enclosingElement, requestor, monitor); - } -} +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.wst.jsdt.core.search; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.wst.jsdt.core.IJavaScriptElement; +import org.eclipse.wst.jsdt.core.IJavaScriptUnit; +import org.eclipse.wst.jsdt.core.IType; +import org.eclipse.wst.jsdt.core.JavaScriptModelException; +import org.eclipse.wst.jsdt.core.WorkingCopyOwner; +import org.eclipse.wst.jsdt.core.compiler.CharOperation; +import org.eclipse.wst.jsdt.internal.compiler.env.AccessRuleSet; +import org.eclipse.wst.jsdt.internal.compiler.util.SimpleSetOfCharArray; +import org.eclipse.wst.jsdt.internal.core.JavaModelManager; +import org.eclipse.wst.jsdt.internal.core.search.BasicSearchEngine; +import org.eclipse.wst.jsdt.internal.core.search.IndexQueryRequestor; +import org.eclipse.wst.jsdt.internal.core.search.JavaSearchParticipant; +import org.eclipse.wst.jsdt.internal.core.search.PatternSearchJob; +import org.eclipse.wst.jsdt.internal.core.search.TypeNameMatchRequestorWrapper; +import org.eclipse.wst.jsdt.internal.core.search.TypeNameRequestorWrapper; +import org.eclipse.wst.jsdt.internal.core.search.indexing.IIndexConstants; +import org.eclipse.wst.jsdt.internal.core.search.indexing.IndexManager; +import org.eclipse.wst.jsdt.internal.core.search.matching.TypeDeclarationPattern; +import org.eclipse.wst.jsdt.internal.core.search.matching.TypeSynonymsPattern; + +/** + * A {@link SearchEngine} searches for JavaScript elements following a search pattern. + * The search can be limited to a search scope. + *

+ * Various search patterns can be created using the factory methods + * {@link SearchPattern#createPattern(String, int, int, int)}, {@link SearchPattern#createPattern(IJavaScriptElement, int)}, + * {@link SearchPattern#createOrPattern(SearchPattern, SearchPattern)}. + *

+ *

For example, one can search for references to a method in the hierarchy of a type, + * or one can search for the declarations of types starting with "Abstract" in a project. + *

+ *

+ * This class may be instantiated; it is not intended to be subclassed. + *

+ * + * Provisional API: This class/interface is part of an interim API that is still under development and expected to + * change significantly before reaching stability. It is being made available at this early stage to solicit feedback + * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken + * (repeatedly) as the API evolves. + */ +public class SearchEngine { + + // Search engine now uses basic engine functionalities + private BasicSearchEngine basicEngine; + + /** + * Creates a new search engine. + */ + public SearchEngine() { + this.basicEngine = new BasicSearchEngine(); + } + + /** + * Creates a new search engine with a list of working copies that will take precedence over + * their original javascript unit s in the subsequent search operations. + *

+ * Note that passing an empty working copy will be as if the original compilation + * unit had been deleted.

+ *

+ * Since 3.0 the given working copies take precedence over primary working copies (if any). + * + * @param workingCopies the working copies that take precedence over their original javascript unit s + * + */ + public SearchEngine(IJavaScriptUnit[] workingCopies) { + this.basicEngine = new BasicSearchEngine(workingCopies); + } + /** + * Creates a new search engine with the given working copy owner. + * The working copies owned by this owner will take precedence over + * the primary javascript unit s in the subsequent search operations. + * + * @param workingCopyOwner the owner of the working copies that take precedence over their original javascript unit s + * + */ + public SearchEngine(WorkingCopyOwner workingCopyOwner) { + this.basicEngine = new BasicSearchEngine(workingCopyOwner); + } + + /** + * Returns a JavaScript search scope limited to the hierarchy of the given type. + * The JavaScript elements resulting from a search with this scope will + * be types in this hierarchy, or members of the types in this hierarchy. + * + * @param type the focus of the hierarchy scope + * @return a new hierarchy scope + * @exception JavaScriptModelException if the hierarchy could not be computed on the given type + */ + public static IJavaScriptSearchScope createHierarchyScope(IType type) throws JavaScriptModelException { + return BasicSearchEngine.createHierarchyScope(type); + } + + /** + * Returns a JavaScript search scope limited to the hierarchy of the given type. + * When the hierarchy is computed, the types defined in the working copies owned + * by the given owner take precedence over the original javascript unit s. + * The JavaScript elements resulting from a search with this scope will + * be types in this hierarchy, or members of the types in this hierarchy. + * + * @param type the focus of the hierarchy scope + * @param owner the owner of working copies that take precedence over original javascript unit s + * @return a new hierarchy scope + * @exception JavaScriptModelException if the hierarchy could not be computed on the given type + * + */ + public static IJavaScriptSearchScope createHierarchyScope(IType type, WorkingCopyOwner owner) throws JavaScriptModelException { + return BasicSearchEngine.createHierarchyScope(type, owner); + } + + /** + * Returns a JavaScript search scope limited to the given JavaScript elements. + * The JavaScript elements resulting from a search with this scope will + * be children of the given elements. + *

+ * If an element is an IJavaScriptProject, then the project's source folders, + * its jars (external and internal) and its referenced projects (with their source + * folders and jars, recursively) will be included. + * If an element is an IPackageFragmentRoot, then only the package fragments of + * this package fragment root will be included. + * If an element is an IPackageFragment, then only the javascript unit and class + * files of this package fragment will be included. Subpackages will NOT be + * included.

+ *

+ * In other words, this is equivalent to using SearchEngine.createJavaSearchScope(elements, true).

+ * + * @param elements the JavaScript elements the scope is limited to + * @return a new JavaScript search scope + * + */ + public static IJavaScriptSearchScope createJavaSearchScope(IJavaScriptElement[] elements) { + return BasicSearchEngine.createJavaSearchScope(elements); + } + + /** + * Returns a JavaScript search scope limited to the given JavaScript elements. + * The JavaScript elements resulting from a search with this scope will + * be children of the given elements. + * + * If an element is an IJavaScriptProject, then the project's source folders, + * its jars (external and internal) and - if specified - its referenced projects + * (with their source folders and jars, recursively) will be included. + * If an element is an IPackageFragmentRoot, then only the package fragments of + * this package fragment root will be included. + * If an element is an IPackageFragment, then only the javascript unit and class + * files of this package fragment will be included. Subpackages will NOT be + * included. + * + * @param elements the JavaScript elements the scope is limited to + * @param includeReferencedProjects a flag indicating if referenced projects must be + * recursively included + * @return a new JavaScript search scope + * + */ + public static IJavaScriptSearchScope createJavaSearchScope(IJavaScriptElement[] elements, boolean includeReferencedProjects) { + return BasicSearchEngine.createJavaSearchScope(elements, includeReferencedProjects); + } + + /** + * Returns a JavaScript search scope limited to the given JavaScript elements. + * The JavaScript elements resulting from a search with this scope will + * be children of the given elements. + * + * If an element is an IJavaScriptProject, then it includes: + * - its source folders if IJavaScriptSearchScope.SOURCES is specified, + * - its application libraries (internal and external jars, class folders that are on the raw includepath, + * or the ones that are coming from a includepath path variable, + * or the ones that are coming from a includepath container with the K_APPLICATION kind) + * if IJavaScriptSearchScope.APPLICATION_LIBRARIES is specified + * - its system libraries (internal and external jars, class folders that are coming from an + * IJsGlobalScopeContainer with the K_SYSTEM kind) + * if IJavaScriptSearchScope.APPLICATION_LIBRARIES is specified + * - its referenced projects (with their source folders and jars, recursively) + * if IJavaScriptSearchScope.REFERENCED_PROJECTS is specified. + * If an element is an IPackageFragmentRoot, then only the package fragments of + * this package fragment root will be included. + * If an element is an IPackageFragment, then only the javascript unit and class + * files of this package fragment will be included. Subpackages will NOT be + * included. + * + * @param elements the JavaScript elements the scope is limited to + * @param includeMask the bit-wise OR of all include types of interest + * @return a new JavaScript search scope + * @see IJavaScriptSearchScope#SOURCES + * @see IJavaScriptSearchScope#APPLICATION_LIBRARIES + * @see IJavaScriptSearchScope#SYSTEM_LIBRARIES + * @see IJavaScriptSearchScope#REFERENCED_PROJECTS + * + */ + public static IJavaScriptSearchScope createJavaSearchScope(IJavaScriptElement[] elements, int includeMask) { + return BasicSearchEngine.createJavaSearchScope(elements, includeMask); + } + + /** + * Create a type name match on a given type with specific modifiers. + * + * @param type The javascript model handle of the type + * @param modifiers Modifiers of the type + * @return A non-null match on the given type. + * + */ + public static TypeNameMatch createTypeNameMatch(IType type, int modifiers) { + return BasicSearchEngine.createTypeNameMatch(type, modifiers); + } + + /** + * Returns a JavaScript search scope with the workspace as the only limit. + * + * @return a new workspace scope + */ + public static IJavaScriptSearchScope createWorkspaceScope() { + return BasicSearchEngine.createWorkspaceScope(); + } + /** + * Returns a new default JavaScript search participant. + * + * @return a new default JavaScript search participant + * + */ + public static SearchParticipant getDefaultSearchParticipant() { + return BasicSearchEngine.getDefaultSearchParticipant(); + } + + /** + * Searches for matches of a given search pattern. Search patterns can be created using helper + * methods (from a String pattern or a JavaScript element) and encapsulate the description of what is + * being searched (for example, search method declarations in a case sensitive way). + * + * @param pattern the pattern to search + * @param participants the particpants in the search + * @param scope the search scope + * @param requestor the requestor to report the matches to + * @param monitor the progress monitor used to report progress + * @exception CoreException if the search failed. Reasons include: + *
    + *
  • the includepath is incorrectly set
  • + *
+ * + */ + public void search(SearchPattern pattern, SearchParticipant[] participants, IJavaScriptSearchScope scope, SearchRequestor requestor, IProgressMonitor monitor) throws CoreException { + this.basicEngine.search(pattern, participants, scope, requestor, monitor); + } + + /** + * Searches for all top-level types and member types in the given scope. + * The search can be selecting specific types (given a package name using specific match mode + * and/or a type name using another specific match mode). + * + * @param packageName the full name of the package of the searched types, or a prefix for this + * package, or a wild-carded string for this package. + * May be null, then any package name is accepted. + * @param typeName the dot-separated qualified name of the searched type (the qualification include + * the enclosing types if the searched type is a member type), or a prefix + * for this type, or a wild-carded string for this type. + * May be null, then any type name is accepted. + * @param packageMatchRule ignored + * @param typeMatchRule one of + *
    + *
  • {@link SearchPattern#R_EXACT_MATCH} if the package name and type name are the full names + * of the searched types.
  • + *
  • {@link SearchPattern#R_PREFIX_MATCH} if the package name and type name are prefixes of the names + * of the searched types.
  • + *
  • {@link SearchPattern#R_PATTERN_MATCH} if the package name and type name contain wild-cards.
  • + *
  • {@link SearchPattern#R_CAMELCASE_MATCH} if type name are camel case of the names of the searched types.
  • + *
+ * combined with {@link SearchPattern#R_CASE_SENSITIVE}, + * e.g. {@link SearchPattern#R_EXACT_MATCH} | {@link SearchPattern#R_CASE_SENSITIVE} if an exact and case sensitive match is requested, + * or {@link SearchPattern#R_PREFIX_MATCH} if a prefix non case sensitive match is requested. + * @param searchFor determines the nature of the searched elements + *
    + *
  • {@link IJavaScriptSearchConstants#CLASS}: only look for classes
  • + *
  • {@link IJavaScriptSearchConstants#INTERFACE}: only look for interfaces
  • + *
  • {@link IJavaScriptSearchConstants#ENUM}: only look for enumeration
  • + *
  • {@link IJavaScriptSearchConstants#ANNOTATION_TYPE}: only look for annotation type
  • + *
  • {@link IJavaScriptSearchConstants#CLASS_AND_ENUM}: only look for classes and enumerations
  • + *
  • {@link IJavaScriptSearchConstants#CLASS_AND_INTERFACE}: only look for classes and interfaces
  • + *
  • {@link IJavaScriptSearchConstants#TYPE}: look for all types (ie. classes, interfaces, enum and annotation types)
  • + *
+ * @param scope the scope to search in + * @param nameRequestor the requestor that collects the results of the search + * @param waitingPolicy one of + *
    + *
  • {@link IJavaScriptSearchConstants#FORCE_IMMEDIATE_SEARCH} if the search should start immediately
  • + *
  • {@link IJavaScriptSearchConstants#CANCEL_IF_NOT_READY_TO_SEARCH} if the search should be cancelled if the + * underlying indexer has not finished indexing the workspace
  • + *
  • {@link IJavaScriptSearchConstants#WAIT_UNTIL_READY_TO_SEARCH} if the search should wait for the + * underlying indexer to finish indexing the workspace
  • + *
+ * @param progressMonitor the progress monitor to report progress to, or null if no progress + * monitor is provided + * @exception JavaScriptModelException if the search failed. Reasons include: + *
    + *
  • the includepath is incorrectly set
  • + *
+ * + */ + public void searchAllTypeNames( + final char[] packageName, + final int packageMatchRule, //ignored + final char[] typeName, + final int typeMatchRule, + int searchFor, + IJavaScriptSearchScope scope, + final TypeNameRequestor nameRequestor, + int waitingPolicy, + IProgressMonitor progressMonitor) throws JavaScriptModelException { + + TypeNameRequestorWrapper requestorWrapper = new TypeNameRequestorWrapper(nameRequestor); + this.basicEngine.searchAllTypeNames(packageName, typeName, typeMatchRule, scope, requestorWrapper, waitingPolicy, progressMonitor); + } + + /** + * Searches for all top-level types and member types in the given scope. + *

+ * Provided {@link TypeNameMatchRequestor} requestor will collect {@link TypeNameMatch} + * matches found during the search. + *

+ * + * @param prefix The prefix could be part of the qualification or simple name for a type, + * or it could be a camel case statement for a simple name of a type. + * @param typeMatchRule one of + *
    + *
  • {@link SearchPattern#R_EXACT_MATCH} if the package name and type name are the full names + * of the searched types.
  • + *
  • {@link SearchPattern#R_PREFIX_MATCH} if the package name and type name are prefixes of the names + * of the searched types.
  • + *
  • {@link SearchPattern#R_PATTERN_MATCH} if the package name and type name contain wild-cards.
  • + *
  • {@link SearchPattern#R_CAMELCASE_MATCH} if type name are camel case of the names of the searched types.
  • + *
+ * combined with {@link SearchPattern#R_CASE_SENSITIVE}, + * e.g. {@link SearchPattern#R_EXACT_MATCH} | {@link SearchPattern#R_CASE_SENSITIVE} if an exact and case sensitive match is requested, + * or {@link SearchPattern#R_PREFIX_MATCH} if a prefix non case sensitive match is requested. + * @param searchFor determines the nature of the searched elements + *
    + *
  • {@link IJavaScriptSearchConstants#CLASS}: only look for classes
  • + *
  • {@link IJavaScriptSearchConstants#INTERFACE}: only look for interfaces
  • + *
  • {@link IJavaScriptSearchConstants#ENUM}: only look for enumeration
  • + *
  • {@link IJavaScriptSearchConstants#ANNOTATION_TYPE}: only look for annotation type
  • + *
  • {@link IJavaScriptSearchConstants#CLASS_AND_ENUM}: only look for classes and enumerations
  • + *
  • {@link IJavaScriptSearchConstants#CLASS_AND_INTERFACE}: only look for classes and interfaces
  • + *
  • {@link IJavaScriptSearchConstants#TYPE}: look for all types (ie. classes, interfaces, enum and annotation types)
  • + *
+ * @param scope the scope to search in + * @param nameMatchRequestor the {@link TypeNameMatchRequestor requestor} that collects + * {@link TypeNameMatch matches} of the search. + * @param waitingPolicy one of + *
    + *
  • {@link IJavaScriptSearchConstants#FORCE_IMMEDIATE_SEARCH} if the search should start immediately
  • + *
  • {@link IJavaScriptSearchConstants#CANCEL_IF_NOT_READY_TO_SEARCH} if the search should be cancelled if the + * underlying indexer has not finished indexing the workspace
  • + *
  • {@link IJavaScriptSearchConstants#WAIT_UNTIL_READY_TO_SEARCH} if the search should wait for the + * underlying indexer to finish indexing the workspace
  • + *
+ * @param progressMonitor the progress monitor to report progress to, or null if no progress + * monitor is provided + * @exception JavaScriptModelException if the search failed. Reasons include: + *
    + *
  • the includepath is incorrectly set
  • + *
+ * + */ + public void searchAllTypeNames( + final char[] prefix, + final int typeMatchRule, + int searchFor, + IJavaScriptSearchScope scope, + final TypeNameMatchRequestor nameMatchRequestor, + int waitingPolicy, + IProgressMonitor progressMonitor) throws JavaScriptModelException { + + TypeNameMatchRequestorWrapper requestorWrapper = new TypeNameMatchRequestorWrapper(nameMatchRequestor, scope); + this.basicEngine.searchAllTypeNames(prefix, typeMatchRule, scope, requestorWrapper, waitingPolicy, progressMonitor); + } + + /** + * Searches for all top-level types and member types in the given scope. + * The search can be selecting specific types (given a package name using specific match mode + * and/or a type name using another specific match mode). + *

+ * Provided {@link TypeNameMatchRequestor} requestor will collect {@link TypeNameMatch} + * matches found during the search. + *

+ * + * @param packageName the full name of the package of the searched types, or a prefix for this + * package, or a wild-carded string for this package. + * May be null, then any package name is accepted. + * @param packageMatchRule IGNORED + * @param typeName the dot-separated qualified name of the searched type (the qualification include + * the enclosing types if the searched type is a member type), or a prefix + * for this type, or a wild-carded string for this type. + * May be null, then any type name is accepted. + * @param typeMatchRule one of + *
    + *
  • {@link SearchPattern#R_EXACT_MATCH} if the package name and type name are the full names + * of the searched types.
  • + *
  • {@link SearchPattern#R_PREFIX_MATCH} if the package name and type name are prefixes of the names + * of the searched types.
  • + *
  • {@link SearchPattern#R_PATTERN_MATCH} if the package name and type name contain wild-cards.
  • + *
  • {@link SearchPattern#R_CAMELCASE_MATCH} if type name are camel case of the names of the searched types.
  • + *
+ * combined with {@link SearchPattern#R_CASE_SENSITIVE}, + * e.g. {@link SearchPattern#R_EXACT_MATCH} | {@link SearchPattern#R_CASE_SENSITIVE} if an exact and case sensitive match is requested, + * or {@link SearchPattern#R_PREFIX_MATCH} if a prefix non case sensitive match is requested. + * @param searchFor determines the nature of the searched elements + *
    + *
  • {@link IJavaScriptSearchConstants#CLASS}: only look for classes
  • + *
  • {@link IJavaScriptSearchConstants#INTERFACE}: only look for interfaces
  • + *
  • {@link IJavaScriptSearchConstants#ENUM}: only look for enumeration
  • + *
  • {@link IJavaScriptSearchConstants#ANNOTATION_TYPE}: only look for annotation type
  • + *
  • {@link IJavaScriptSearchConstants#CLASS_AND_ENUM}: only look for classes and enumerations
  • + *
  • {@link IJavaScriptSearchConstants#CLASS_AND_INTERFACE}: only look for classes and interfaces
  • + *
  • {@link IJavaScriptSearchConstants#TYPE}: look for all types (ie. classes, interfaces, enum and annotation types)
  • + *
+ * @param scope the scope to search in + * @param nameMatchRequestor the {@link TypeNameMatchRequestor requestor} that collects + * {@link TypeNameMatch matches} of the search. + * @param waitingPolicy one of + *
    + *
  • {@link IJavaScriptSearchConstants#FORCE_IMMEDIATE_SEARCH} if the search should start immediately
  • + *
  • {@link IJavaScriptSearchConstants#CANCEL_IF_NOT_READY_TO_SEARCH} if the search should be cancelled if the + * underlying indexer has not finished indexing the workspace
  • + *
  • {@link IJavaScriptSearchConstants#WAIT_UNTIL_READY_TO_SEARCH} if the search should wait for the + * underlying indexer to finish indexing the workspace
  • + *
+ * @param progressMonitor the progress monitor to report progress to, or null if no progress + * monitor is provided + * @exception JavaScriptModelException if the search failed. Reasons include: + *
    + *
  • the includepath is incorrectly set
  • + *
+ * + */ + public void searchAllTypeNames( + final char[] packageName, + final int packageMatchRule, //ignored + final char[] typeName, + final int typeMatchRule, + int searchFor, + IJavaScriptSearchScope scope, + final TypeNameMatchRequestor nameMatchRequestor, + int waitingPolicy, + IProgressMonitor progressMonitor) throws JavaScriptModelException { + + TypeNameMatchRequestorWrapper requestorWrapper = new TypeNameMatchRequestorWrapper(nameMatchRequestor, scope); + this.basicEngine.searchAllTypeNames(packageName, typeName, typeMatchRule, scope, requestorWrapper, waitingPolicy, progressMonitor); + } + + /** + * Searches for all top-level types and member types in the given scope matching any of the given qualifications + * and type names in a case sensitive way. + * + * @param qualifications the qualified name of the package/enclosing type of the searched types. + * May be null, then any package name is accepted. + * @param typeNames the simple names of the searched types. + * If this parameter is null, then no type will be found. + * @param scope the scope to search in + * @param nameRequestor the requestor that collects the results of the search + * @param waitingPolicy one of + *
    + *
  • {@link IJavaScriptSearchConstants#FORCE_IMMEDIATE_SEARCH} if the search should start immediately
  • + *
  • {@link IJavaScriptSearchConstants#CANCEL_IF_NOT_READY_TO_SEARCH} if the search should be cancelled if the + * underlying indexer has not finished indexing the workspace
  • + *
  • {@link IJavaScriptSearchConstants#WAIT_UNTIL_READY_TO_SEARCH} if the search should wait for the + * underlying indexer to finish indexing the workspace
  • + *
+ * @param progressMonitor the progress monitor to report progress to, or null if no progress + * monitor is provided + * @exception JavaScriptModelException if the search failed. Reasons include: + *
    + *
  • the includepath is incorrectly set
  • + *
+ * + */ + public void searchAllTypeNames( + final char[][] qualifications, + final char[][] typeNames, + IJavaScriptSearchScope scope, + final TypeNameRequestor nameRequestor, + int waitingPolicy, + IProgressMonitor progressMonitor) throws JavaScriptModelException { + + TypeNameRequestorWrapper requestorWrapper = new TypeNameRequestorWrapper(nameRequestor); + this.basicEngine.searchAllTypeNames( + qualifications, + typeNames, + SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE, + scope, + requestorWrapper, + waitingPolicy, + progressMonitor); + } + + /** + * Searches for all top-level types and member types in the given scope matching any of the given qualifications + * and type names in a case sensitive way. + *

+ * Provided {@link TypeNameMatchRequestor} requestor will collect {@link TypeNameMatch} + * matches found during the search. + *

+ * + * @param qualifications the qualified name of the package/enclosing type of the searched types. + * May be null, then any package name is accepted. + * @param typeNames the simple names of the searched types. + * If this parameter is null, then no type will be found. + * @param scope the scope to search in + * @param nameMatchRequestor the {@link TypeNameMatchRequestor requestor} that collects + * {@link TypeNameMatch matches} of the search. + * @param waitingPolicy one of + *
    + *
  • {@link IJavaScriptSearchConstants#FORCE_IMMEDIATE_SEARCH} if the search should start immediately
  • + *
  • {@link IJavaScriptSearchConstants#CANCEL_IF_NOT_READY_TO_SEARCH} if the search should be cancelled if the + * underlying indexer has not finished indexing the workspace
  • + *
  • {@link IJavaScriptSearchConstants#WAIT_UNTIL_READY_TO_SEARCH} if the search should wait for the + * underlying indexer to finish indexing the workspace
  • + *
+ * @param progressMonitor the progress monitor to report progress to, or null if no progress + * monitor is provided + * @exception JavaScriptModelException if the search failed. Reasons include: + *
    + *
  • the includepath is incorrectly set
  • + *
+ * + */ + public void searchAllTypeNames( + final char[][] qualifications, + final char[][] typeNames, + IJavaScriptSearchScope scope, + final TypeNameMatchRequestor nameMatchRequestor, + int waitingPolicy, + IProgressMonitor progressMonitor) throws JavaScriptModelException { + + TypeNameMatchRequestorWrapper requestorWrapper = new TypeNameMatchRequestorWrapper(nameMatchRequestor, scope); + this.basicEngine.searchAllTypeNames( + qualifications, + typeNames, + SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE, + scope, + requestorWrapper, + waitingPolicy, + progressMonitor); + } + + /** + * Searches for all declarations of the fields accessed in the given element. + * The element can be a javascript unit , a source type, or a source method. + * Reports the field declarations using the given requestor. + *

+ * Consider the following code: + * + *

+	 *		class A {
+	 *			int field1;
+	 *		}
+	 *		class B extends A {
+	 *			String value;
+	 *		}
+	 *		class X {
+	 *			void test() {
+	 *				B b = new B();
+	 *				System.out.println(b.value + b.field1);
+	 *			};
+	 *		}
+	 * 
+ * + * then searching for declarations of accessed fields in method + * X.test() would collect the fields + * B.value and A.field1. + *

+ * + * @param enclosingElement the method, type, or javascript unit to be searched in + * @param requestor a callback object to which each match is reported + * @param monitor the progress monitor used to report progress + * @exception JavaScriptModelException if the search failed. Reasons include: + *
    + *
  • the element doesn't exist
  • + *
  • the includepath is incorrectly set
  • + *
+ * + */ + public void searchDeclarationsOfAccessedFields(IJavaScriptElement enclosingElement, SearchRequestor requestor, IProgressMonitor monitor) throws JavaScriptModelException { + this.basicEngine.searchDeclarationsOfAccessedFields(enclosingElement, requestor, monitor); + } + + /** + * Searches for all declarations of the types referenced in the given element. + * The element can be a javascript unit , a source type, or a source method. + * Reports the type declarations using the given requestor. + *

+ * Consider the following code: + * + *

+	 *		class A {
+	 *		}
+	 *		class B extends A {
+	 *		}
+	 *		interface I {
+	 *		  int VALUE = 0;
+	 *		}
+	 *		class X {
+	 *			void test() {
+	 *				B b = new B();
+	 *				this.foo(b, I.VALUE);
+	 *			};
+	 *		}
+	 * 
+ * + * then searching for declarations of referenced types in method X.test() + * would collect the class B and the interface I. + *

+ * + * @param enclosingElement the method, type, or javascript unit to be searched in + * @param requestor a callback object to which each match is reported + * @param monitor the progress monitor used to report progress + * @exception JavaScriptModelException if the search failed. Reasons include: + *
    + *
  • the element doesn't exist
  • + *
  • the includepath is incorrectly set
  • + *
+ * + */ + public void searchDeclarationsOfReferencedTypes(IJavaScriptElement enclosingElement, SearchRequestor requestor, IProgressMonitor monitor) throws JavaScriptModelException { + this.basicEngine.searchDeclarationsOfReferencedTypes(enclosingElement, requestor, monitor); + } + + /** + * Searches for all declarations of the methods invoked in the given element. + * The element can be a javascript unit , a source type, or a source method. + * Reports the method declarations using the given requestor. + *

+ * Consider the following code: + * + *

+	 *		class A {
+	 *			void foo() {};
+	 *			void bar() {};
+	 *		}
+	 *		class B extends A {
+	 *			void foo() {};
+	 *		}
+	 *		class X {
+	 *			void test() {
+	 *				A a = new B();
+	 *				a.foo();
+	 *				B b = (B)a;
+	 *				b.bar();
+	 *			};
+	 *		}
+	 * 
+ * + * then searching for declarations of sent messages in method + * X.test() would collect the methods + * A.foo(), B.foo(), and A.bar(). + *

+ * + * @param enclosingElement the method, type, or javascript unit to be searched in + * @param requestor a callback object to which each match is reported + * @param monitor the progress monitor used to report progress + * @exception JavaScriptModelException if the search failed. Reasons include: + *
    + *
  • the element doesn't exist
  • + *
  • the includepath is incorrectly set
  • + *
+ * + */ + public void searchDeclarationsOfSentMessages(IJavaScriptElement enclosingElement, SearchRequestor requestor, IProgressMonitor monitor) throws JavaScriptModelException { + this.basicEngine.searchDeclarationsOfSentMessages(enclosingElement, requestor, monitor); + } + + + /** + *

+ * Gets all the names of subtypes of a given type name in the given + * scope. + *

+ * + * @param typeName + * name of the type whose subtype names will be found + * @param scope + * to search in for all the subtypes of the given type name + * @param waitingPolicy + * one of + *
    + *
  • + * {@link IJavaScriptSearchConstants#FORCE_IMMEDIATE_SEARCH} if + * the search should start immediately
  • + *
  • + * {@link IJavaScriptSearchConstants#CANCEL_IF_NOT_READY_TO_SEARCH} + * if the search should be cancelled if the underlying indexer + * has not finished indexing the workspace
  • + *
  • + * {@link IJavaScriptSearchConstants#WAIT_UNTIL_READY_TO_SEARCH} + * if the search should wait for the underlying indexer to + * finish indexing the workspace
  • + *
+ * @param progressMonitor + * monitor to report progress to + * + * @return List of type names that are the subtypes of the given type + * name, if there are no subtypes then the list will only contain + * the given type name. The given type name is ALWAYS the first + * element in the list. + */ + public static char[][] getAllSubtypeNames(char[] typeName, IJavaScriptSearchScope scope, int waitingPolicy, IProgressMonitor progressMonitor) { + final IProgressMonitor monitor = progressMonitor != null ? progressMonitor : new NullProgressMonitor(); + + //list of found names + final SimpleSetOfCharArray subtypeNames = new SimpleSetOfCharArray(); + + // queue of types to search for synonyms for + final LinkedList searchQueue = new LinkedList(); + searchQueue.add(typeName); + + IndexManager indexManager = JavaModelManager.getJavaModelManager().getIndexManager(); + while (!searchQueue.isEmpty()) { + char[] searchName = (char[]) searchQueue.remove(0); + if (subtypeNames.includes(searchName)) + continue; + subtypeNames.add(searchName); + + char[][] synonyms = getAllSynonyms(searchName, scope, waitingPolicy, null); + for (int i = 0; i < synonyms.length; i++) { + if (!subtypeNames.includes(synonyms[i])) { + searchQueue.add(synonyms[i]); + } + } + /* + * create pattern and job to search for subtypes of the parent + * type + */ + TypeDeclarationPattern subtypePattern = new TypeDeclarationPattern(IIndexConstants.ONE_STAR, IIndexConstants.ONE_STAR, new char[][]{searchName}, SearchPattern.R_PATTERN_MATCH | SearchPattern.R_CASE_SENSITIVE); + + // run the search + indexManager.performConcurrentJob(new PatternSearchJob(subtypePattern, new JavaSearchParticipant(), scope, new IndexQueryRequestor() { + public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant, AccessRuleSet access) { + TypeDeclarationPattern record = (TypeDeclarationPattern) indexRecord; + char[] subtype = CharOperation.concat(record.qualification, record.simpleName, IIndexConstants.DOT); + if (!subtypeNames.includes(subtype)) { + searchQueue.add(subtype); + } + return true; + } + }), waitingPolicy, new NullProgressMonitor() { + public void setCanceled(boolean value) { + monitor.setCanceled(value); + } + + public boolean isCanceled() { + return monitor.isCanceled(); + } + }); + } + char[][] names = new char[subtypeNames.elementSize][]; + subtypeNames.asArray(names); + return names; + } + + /** + *

+ * Gets all the synonyms of a given type, including itself, in the given + * scope. + *

+ * + *

+ * NOTE: It is guaranteed that itself will be the first synonym in + * the list. + *

+ * + * @param typeName + * name of the type to get all the synonyms for + * @param scope + * to search in for all the synonyms of the given type + * @param waitingPolicy + * one of + *
    + *
  • + * {@link IJavaScriptSearchConstants#FORCE_IMMEDIATE_SEARCH} if + * the search should start immediately
  • + *
  • + * {@link IJavaScriptSearchConstants#CANCEL_IF_NOT_READY_TO_SEARCH} + * if the search should be cancelled if the underlying indexer + * has not finished indexing the workspace
  • + *
  • + * {@link IJavaScriptSearchConstants#WAIT_UNTIL_READY_TO_SEARCH} + * if the search should wait for the underlying indexer to + * finish indexing the workspace
  • + *
+ * @param progressMonitor + * monitor to report progress to + * + * @return List of type names that are the synonyms of the given type + * name, if there are non synonyms then the list will only contain + * the given type name. The given type name is ALWAYS the first + * element in the list. + */ + public static char[][] getAllSynonyms(char[] typeName, IJavaScriptSearchScope scope, + int waitingPolicy, IProgressMonitor progressMonitor) { + + final IProgressMonitor monitor = progressMonitor != null ? progressMonitor : new NullProgressMonitor(); + + //list of found synonyms + final List allSynonyms = new ArrayList(); + allSynonyms.add(typeName); + + //queue of types to search for synonyms for + final LinkedList searchForSynonyms = new LinkedList(); + searchForSynonyms.add(typeName); + + //for each synonyms search of synonyms of that synonym + IndexManager indexManager = JavaModelManager.getJavaModelManager().getIndexManager(); + while (!searchForSynonyms.isEmpty() && !monitor.isCanceled()) { + char[] needle = (char[])searchForSynonyms.removeFirst(); + + //create pattern and job to search for type synonyms for the parent type that is being searched for + TypeSynonymsPattern typeSynonymsPattern = new TypeSynonymsPattern(needle); + + //search for the type synonyms + indexManager.performConcurrentJob(new PatternSearchJob( + typeSynonymsPattern, + new JavaSearchParticipant(), + scope, + new IndexQueryRequestor() { + public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant, AccessRuleSet access) { + TypeSynonymsPattern record = (TypeSynonymsPattern)indexRecord; + char[][] patternSynonyms = record.getSynonyms(); + + if(patternSynonyms != null && patternSynonyms.length != 0) { + for(int i = 0; i < patternSynonyms.length; ++i) { + /* if new synonym add to list of synonyms to return and to + * list of synonyms to check for more synonyms */ + if(!listContains(allSynonyms, patternSynonyms[i])) { + allSynonyms.add(patternSynonyms[i]); + searchForSynonyms.add(patternSynonyms[i]); + } + } + } + + return true; + } + } + ), + waitingPolicy, + new NullProgressMonitor() { + public void setCanceled(boolean value) { + monitor.setCanceled(value); + } + public boolean isCanceled() { + return monitor.isCanceled(); + } + } + ); + } + + return (char[][])allSynonyms.toArray(new char[allSynonyms.size()][]); + } + + private static boolean listContains(List list, Object elem) { + boolean contains = false; + + //need to do char equals if char array + if(elem instanceof char[]) { + char[] needle = (char[])elem; + for(int i = 0; i < list.size() && !contains; ++i) { + contains = list.get(i) instanceof char[] && CharOperation.equals((char[])list.get(i), needle); + } + } else { + contains = list.contains(elem); + } + + return contains; + } +} diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/SearchMatch.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/SearchMatch.java index 498805c0..ea8c6e42 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/SearchMatch.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/SearchMatch.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/SearchPattern.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/SearchPattern.java index 1b21032c..0512a378 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/SearchPattern.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/core/search/SearchPattern.java @@ -1,1921 +1,1918 @@ -/******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.jsdt.core.search; - -import org.eclipse.wst.jsdt.core.IField; -import org.eclipse.wst.jsdt.core.IFunction; -import org.eclipse.wst.jsdt.core.IImportDeclaration; -import org.eclipse.wst.jsdt.core.IJavaScriptElement; -import org.eclipse.wst.jsdt.core.IMember; -import org.eclipse.wst.jsdt.core.IType; -import org.eclipse.wst.jsdt.core.JavaScriptModelException; -import org.eclipse.wst.jsdt.core.Signature; -import org.eclipse.wst.jsdt.core.compiler.CharOperation; -import org.eclipse.wst.jsdt.core.compiler.InvalidInputException; -import org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants; -import org.eclipse.wst.jsdt.internal.compiler.parser.Scanner; -import org.eclipse.wst.jsdt.internal.compiler.parser.ScannerHelper; -import org.eclipse.wst.jsdt.internal.compiler.parser.TerminalTokens; -import org.eclipse.wst.jsdt.internal.core.LocalVariable; -import org.eclipse.wst.jsdt.internal.core.search.indexing.IIndexConstants; -import org.eclipse.wst.jsdt.internal.core.search.matching.ConstructorPattern; -import org.eclipse.wst.jsdt.internal.core.search.matching.FieldPattern; -import org.eclipse.wst.jsdt.internal.core.search.matching.InternalSearchPattern; -import org.eclipse.wst.jsdt.internal.core.search.matching.LocalVariablePattern; -import org.eclipse.wst.jsdt.internal.core.search.matching.MatchLocator; -import org.eclipse.wst.jsdt.internal.core.search.matching.MethodPattern; -import org.eclipse.wst.jsdt.internal.core.search.matching.OrPattern; -import org.eclipse.wst.jsdt.internal.core.search.matching.PackageDeclarationPattern; -import org.eclipse.wst.jsdt.internal.core.search.matching.PackageReferencePattern; -import org.eclipse.wst.jsdt.internal.core.search.matching.QualifiedTypeDeclarationPattern; -import org.eclipse.wst.jsdt.internal.core.search.matching.SuperTypeReferencePattern; -import org.eclipse.wst.jsdt.internal.core.search.matching.TypeDeclarationPattern; -import org.eclipse.wst.jsdt.internal.core.search.matching.TypeReferencePattern; - - -/** - * A search pattern defines how search results are found. Use SearchPattern.createPattern - * to create a search pattern. - *

- * Search patterns are used during the search phase to decode index entries that were added during the indexing phase - * (see {@link SearchDocument#addIndexEntry(char[], char[])}). When an index is queried, the - * index categories and keys to consider are retrieved from the search pattern using {@link #getIndexCategories()} and - * {@link #getIndexKey()}, as well as the match rule (see {@link #getMatchRule()}). A blank pattern is - * then created (see {@link #getBlankPattern()}). This blank pattern is used as a record as follows. - * For each index entry in the given index categories and that starts with the given key, the blank pattern is fed using - * {@link #decodeIndexKey(char[])}. The original pattern is then asked if it matches the decoded key using - * {@link #matchesDecodedKey(SearchPattern)}. If it matches, a search doument is created for this index entry - * using {@link SearchParticipant#getDocument(String)}. - * - *

- * This class is intended to be subclassed by clients. A default behavior is provided for each of the methods above, that - * clients can ovveride if they wish. - *

- * @see #createPattern(org.eclipse.wst.jsdt.core.IJavaScriptElement, int) - * @see #createPattern(String, int, int, int) - * - * Provisional API: This class/interface is part of an interim API that is still under development and expected to - * change significantly before reaching stability. It is being made available at this early stage to solicit feedback - * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken - * (repeatedly) as the API evolves. - */ -public abstract class SearchPattern extends InternalSearchPattern { - - // Rules for pattern matching: (exact, prefix, pattern) [ | case sensitive] - /** - * Match rule: The search pattern matches exactly the search result, - * that is, the source of the search result equals the search pattern. - */ - public static final int R_EXACT_MATCH = 0; - - /** - * Match rule: The search pattern is a prefix of the search result. - */ - public static final int R_PREFIX_MATCH = 0x0001; - - /** - * Match rule: The search pattern contains one or more wild cards ('*' or '?'). - * A '*' wild-card can replace 0 or more characters in the search result. - * A '?' wild-card replaces exactly 1 character in the search result. - */ - public static final int R_PATTERN_MATCH = 0x0002; - - /** - * Match rule: The search pattern contains a regular expression. - */ - public static final int R_REGEXP_MATCH = 0x0004; - - /** - * Match rule: The search pattern matches the search result only if cases are the same. - * Can be combined to previous rules, e.g. {@link #R_EXACT_MATCH} | {@link #R_CASE_SENSITIVE} - */ - public static final int R_CASE_SENSITIVE = 0x0008; - - /** - * Match rule: The search pattern matches search results as raw/parameterized types/methods with same erasure. - * This mode has no effect on other javascript elements search.
- * Type search example: - *
    - *
  • pattern: List<Exception>
  • - *
  • match: List<Object>
  • - *
- * Method search example: - *
    - *
  • declaration: <T>foo(T t)
  • - *
  • pattern: <Exception>foo(new Exception())
  • - *
  • match: <Object>foo(new Object())
  • - *
- * Can be combined to all other match rules, e.g. {@link #R_CASE_SENSITIVE} | {@link #R_ERASURE_MATCH} - * This rule is not activated by default, so raw types or parameterized types with same erasure will not be found - * for pattern List<String>, - * Note that with this pattern, the match selection will be only on the erasure even for parameterized types. - * - */ - public static final int R_ERASURE_MATCH = 0x0010; - - /** - * Match rule: The search pattern matches search results as raw/parameterized types/methods with equivalent type parameters. - * This mode has no effect on other javascript elements search.
- * Type search example: - *
    - *
  • pattern: List<Exception>
  • - *
  • match: - *
      - *
    • List<? extends Throwable>
    • - *
    • List<? super RuntimeException>
    • - *
    • List<?>
    • - *
    - *
  • - *
- * Method search example: - *
    - *
  • declaration: <T>foo(T t)
  • - *
  • pattern: <Exception>foo(new Exception())
  • - *
  • match: - *
      - *
    • <? extends Throwable>foo(new Exception())
    • - *
    • <? super RuntimeException>foo(new Exception())
    • - *
    • foo(new Exception())
    • - *
    - *
- * Can be combined to all other match rules, e.g. {@link #R_CASE_SENSITIVE} | {@link #R_EQUIVALENT_MATCH} - * This rule is not activated by default, so raw types or equivalent parameterized types will not be found - * for pattern List<String>, - * This mode is overridden by {@link #R_ERASURE_MATCH} as erasure matches obviously include equivalent ones. - * That means that pattern with rule set to {@link #R_EQUIVALENT_MATCH} | {@link #R_ERASURE_MATCH} - * will return same results than rule only set with {@link #R_ERASURE_MATCH}. - * - */ - public static final int R_EQUIVALENT_MATCH = 0x0020; - - /** - * Match rule: The search pattern matches exactly the search result, - * that is, the source of the search result equals the search pattern. - * - */ - public static final int R_FULL_MATCH = 0x0040; - - /** - * Match rule: The search pattern contains a Camel Case expression. - *
- * Examples: - *
    - *
  • NPE type string pattern will match - * NullPointerException and NpPermissionException types,
  • - *
  • NuPoEx type string pattern will only match - * NullPointerException type.
  • - *
- * @see CharOperation#camelCaseMatch(char[], char[]) for a detailed explanation - * of Camel Case matching. - *
- * Can be combined to {@link #R_PREFIX_MATCH} match rule. For example, - * when prefix match rule is combined with Camel Case match rule, - * "nPE" pattern will match nPException. - *
- * Match rule {@link #R_PATTERN_MATCH} may also be combined but both rules - * will not be used simultaneously as they are mutually exclusive. - * Used match rule depends on whether string pattern contains specific pattern - * characters (e.g. '*' or '?') or not. If it does, then only Pattern match rule - * will be used, otherwise only Camel Case match will be used. - * For example, with "NPE" string pattern, search will only use - * Camel Case match rule, but with N*P*E* string pattern, it will - * use only Pattern match rule. - * - * - */ - public static final int R_CAMELCASE_MATCH = 0x0080; - - private static final int MODE_MASK = R_EXACT_MATCH | R_PREFIX_MATCH | R_PATTERN_MATCH | R_REGEXP_MATCH; - - private int matchRule; - -/** - * Creates a search pattern with the rule to apply for matching index keys. - * It can be exact match, prefix match, pattern match or regexp match. - * Rule can also be combined with a case sensitivity flag. - * - * @param matchRule one of {@link #R_EXACT_MATCH}, {@link #R_PREFIX_MATCH}, {@link #R_PATTERN_MATCH}, - * {@link #R_REGEXP_MATCH}, {@link #R_CAMELCASE_MATCH} combined with one of following values: - * {@link #R_CASE_SENSITIVE}, {@link #R_ERASURE_MATCH} or {@link #R_EQUIVALENT_MATCH}. - * e.g. {@link #R_EXACT_MATCH} | {@link #R_CASE_SENSITIVE} if an exact and case sensitive match is requested, - * {@link #R_PREFIX_MATCH} if a prefix non case sensitive match is requested or {@link #R_EXACT_MATCH} | {@link #R_ERASURE_MATCH} - * if a non case sensitive and erasure match is requested.
- * Note that {@link #R_ERASURE_MATCH} or {@link #R_EQUIVALENT_MATCH} have no effect - * on non-generic types/methods search.
- * Note also that default behavior for generic types/methods search is to find exact matches. - */ -public SearchPattern(int matchRule) { - this.matchRule = matchRule; - // Set full match implicit mode - if ((matchRule & (R_EQUIVALENT_MATCH | R_ERASURE_MATCH )) == 0) { - this.matchRule |= R_FULL_MATCH; - } -} - -/** - * Answers true if the pattern matches the given name using CamelCase rules, or false otherwise. - * CamelCase matching does NOT accept explicit wild-cards '*' and '?' and is inherently case sensitive. - *
- * CamelCase denotes the convention of writing compound names without spaces, and capitalizing every term. - * This function recognizes both upper and lower CamelCase, depending whether the leading character is capitalized - * or not. The leading part of an upper CamelCase pattern is assumed to contain a sequence of capitals which are appearing - * in the matching name; e.g. 'NPE' will match 'NullPointerException', but not 'NewPerfData'. A lower CamelCase pattern - * uses a lowercase first character. In Java, type names follow the upper CamelCase convention, whereas method or field - * names follow the lower CamelCase convention. - *
- * The pattern may contain lowercase characters, which will be match in a case sensitive way. These characters must - * appear in sequence in the name. For instance, 'NPExcep' will match 'NullPointerException', but not 'NullPointerExCEPTION' - * or 'NuPoEx' will match 'NullPointerException', but not 'NoPointerException'. - *

- * Examples: - *
    - *
  1. - *    pattern = "NPE"
    - *    name = NullPointerException / NoPermissionException
    - *    result => true
    - * 
    - *
  2. - *
  3. - *    pattern = "NuPoEx"
    - *    name = NullPointerException
    - *    result => true
    - * 
    - *
  4. - *
  5. - *    pattern = "npe"
    - *    name = NullPointerException
    - *    result => false
    - * 
    - *
  6. - *
- * @see CharOperation#camelCaseMatch(char[], char[]) - * Implementation has been entirely copied from this method except for array lengthes - * which were obviously replaced with calls to {@link String#length()}. - * - * @param pattern the given pattern - * @param name the given name - * @return true if the pattern matches the given name, false otherwise - * - */ -public static final boolean camelCaseMatch(String pattern, String name) { - if (pattern == null) - return true; // null pattern is equivalent to '*' - if (name == null) - return false; // null name cannot match - - return camelCaseMatch(pattern, 0, pattern.length(), name, 0, name.length()); -} - -/** - * Answers true if a sub-pattern matches the subpart of the given name using CamelCase rules, or false otherwise. - * CamelCase matching does NOT accept explicit wild-cards '*' and '?' and is inherently case sensitive. - * Can match only subset of name/pattern, considering end positions as non-inclusive. - * The subpattern is defined by the patternStart and patternEnd positions. - *
- * CamelCase denotes the convention of writing compound names without spaces, and capitalizing every term. - * This function recognizes both upper and lower CamelCase, depending whether the leading character is capitalized - * or not. The leading part of an upper CamelCase pattern is assumed to contain a sequence of capitals which are appearing - * in the matching name; e.g. 'NPE' will match 'NullPointerException', but not 'NewPerfData'. A lower CamelCase pattern - * uses a lowercase first character. In Java, type names follow the upper CamelCase convention, whereas method or field - * names follow the lower CamelCase convention. - *
- * The pattern may contain lowercase characters, which will be match in a case sensitive way. These characters must - * appear in sequence in the name. For instance, 'NPExcep' will match 'NullPointerException', but not 'NullPointerExCEPTION' - * or 'NuPoEx' will match 'NullPointerException', but not 'NoPointerException'. - *

- * Examples: - *
    - *
  1. - *    pattern = "NPE"
    - *    patternStart = 0
    - *    patternEnd = 3
    - *    name = NullPointerException
    - *    nameStart = 0
    - *    nameEnd = 20
    - *    result => true
    - * 
    - *
  2. - *
  3. - *    pattern = "NPE"
    - *    patternStart = 0
    - *    patternEnd = 3
    - *    name = NoPermissionException
    - *    nameStart = 0
    - *    nameEnd = 21
    - *    result => true
    - * 
    - *
  4. - *
  5. - *    pattern = "NuPoEx"
    - *    patternStart = 0
    - *    patternEnd = 6
    - *    name = NullPointerException
    - *    nameStart = 0
    - *    nameEnd = 20
    - *    result => true
    - * 
    - *
  6. - *
  7. - *    pattern = "NuPoEx"
    - *    patternStart = 0
    - *    patternEnd = 6
    - *    name = NoPermissionException
    - *    nameStart = 0
    - *    nameEnd = 21
    - *    result => false
    - * 
    - *
  8. - *
  9. - *    pattern = "npe"
    - *    patternStart = 0
    - *    patternEnd = 3
    - *    name = NullPointerException
    - *    nameStart = 0
    - *    nameEnd = 20
    - *    result => false
    - * 
    - *
  10. - *
- * @see CharOperation#camelCaseMatch(char[], int, int, char[], int, int) - * Implementation has been entirely copied from this method except for array lengthes - * which were obviously replaced with calls to {@link String#length()} and - * for array direct access which were replaced with calls to {@link String#charAt(int)}. - * - * @param pattern the given pattern - * @param patternStart the start index of the pattern, inclusive - * @param patternEnd the end index of the pattern, exclusive - * @param name the given name - * @param nameStart the start index of the name, inclusive - * @param nameEnd the end index of the name, exclusive - * @return true if a sub-pattern matches the subpart of the given name, false otherwise - * - */ -public static final boolean camelCaseMatch(String pattern, int patternStart, int patternEnd, String name, int nameStart, int nameEnd) { - if (name == null) - return false; // null name cannot match - if (pattern == null) - return true; // null pattern is equivalent to '*' - if (patternEnd < 0) patternEnd = pattern.length(); - if (nameEnd < 0) nameEnd = name.length(); - - if (patternEnd <= patternStart) return nameEnd <= nameStart; - if (nameEnd <= nameStart) return false; - // check first pattern char - if (name.charAt(nameStart) != pattern.charAt(patternStart)) { - // first char must strictly match (upper/lower) - return false; - } - - char patternChar, nameChar; - int iPattern = patternStart; - int iName = nameStart; - - // Main loop is on pattern characters - while (true) { - - iPattern++; - iName++; - - if (iPattern == patternEnd) { - // We have exhausted pattern, so it's a match - return true; - } - - if (iName == nameEnd){ - // We have exhausted name (and not pattern), so it's not a match - return false; - } - - // For as long as we're exactly matching, bring it on (even if it's a lower case character) - if ((patternChar = pattern.charAt(iPattern)) == name.charAt(iName)) { - continue; - } - - // If characters are not equals, then it's not a match if patternChar is lowercase - if (patternChar < ScannerHelper.MAX_OBVIOUS) { - if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[patternChar] & ScannerHelper.C_UPPER_LETTER) == 0) { - return false; - } - } - else if (Character.isJavaIdentifierPart(patternChar) && !Character.isUpperCase(patternChar)) { - return false; - } - - // patternChar is uppercase, so let's find the next uppercase in name - while (true) { - if (iName == nameEnd){ - // We have exhausted name (and not pattern), so it's not a match - return false; - } - - nameChar = name.charAt(iName); - - if (nameChar < ScannerHelper.MAX_OBVIOUS) { - if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[nameChar] & (ScannerHelper.C_LOWER_LETTER | ScannerHelper.C_SPECIAL | ScannerHelper.C_DIGIT)) != 0) { - // nameChar is lowercase - iName++; - // nameChar is uppercase... - } else if (patternChar != nameChar) { - //.. and it does not match patternChar, so it's not a match - return false; - } else { - //.. and it matched patternChar. Back to the big loop - break; - } - } - else if (Character.isJavaIdentifierPart(nameChar) && !Character.isUpperCase(nameChar)) { - // nameChar is lowercase - iName++; - // nameChar is uppercase... - } else if (patternChar != nameChar) { - //.. and it does not match patternChar, so it's not a match - return false; - } else { - //.. and it matched patternChar. Back to the big loop - break; - } - } - // At this point, either name has been exhausted, or it is at an uppercase letter. - // Since pattern is also at an uppercase letter - } -} - -/** - * Returns a search pattern that combines the given two patterns into an - * "and" pattern. The search result will match both the left pattern and - * the right pattern. - * - * @param leftPattern the left pattern - * @param rightPattern the right pattern - * @return an "and" pattern - */ -public static SearchPattern createAndPattern(SearchPattern leftPattern, SearchPattern rightPattern) { - return MatchLocator.createAndPattern(leftPattern, rightPattern); -} - -/** - * Field pattern are formed by [declaringType.]name[ type] - * e.g. java.lang.String.serialVersionUID long - * field* - */ -private static SearchPattern createFieldPattern(String patternString, int limitTo, int matchRule,boolean isVar) { - - Scanner scanner = new Scanner(false /*comment*/, true /*whitespace*/, false /*nls*/, ClassFileConstants.JDK1_3/*sourceLevel*/, null /*taskTags*/, null/*taskPriorities*/, true/*taskCaseSensitive*/); - scanner.setSource(patternString.toCharArray()); - final int InsideDeclaringPart = 1; - final int InsideType = 2; - int lastToken = -1; - - String declaringType = null, fieldName = null; - String type = null; - int mode = InsideDeclaringPart; - int token; - try { - token = scanner.getNextToken(); - } catch (InvalidInputException e) { - return null; - } - while (token != TerminalTokens.TokenNameEOF) { - switch(mode) { - // read declaring type and fieldName - case InsideDeclaringPart : - switch (token) { - case TerminalTokens.TokenNameDOT: - if (declaringType == null) { - if (fieldName == null) return null; - declaringType = fieldName; - } else { - String tokenSource = scanner.getCurrentTokenString(); - declaringType += tokenSource + fieldName; - } - fieldName = null; - break; - case TerminalTokens.TokenNameWHITESPACE: - if (!(TerminalTokens.TokenNameWHITESPACE == lastToken || TerminalTokens.TokenNameDOT == lastToken)) - mode = InsideType; - break; - default: // all other tokens are considered identifiers (see bug 21763 Problem in JavaScript search [search]) - if (fieldName == null) - fieldName = scanner.getCurrentTokenString(); - else - fieldName += scanner.getCurrentTokenString(); - } - break; - // read type - case InsideType: - switch (token) { - case TerminalTokens.TokenNameWHITESPACE: - break; - default: // all other tokens are considered identifiers (see bug 21763 Problem in JavaScript search [search]) - if (type == null) - type = scanner.getCurrentTokenString(); - else - type += scanner.getCurrentTokenString(); - } - break; - } - lastToken = token; - try { - token = scanner.getNextToken(); - } catch (InvalidInputException e) { - return null; - } - } - if (fieldName == null) return null; - - char[] fieldNameChars = fieldName.toCharArray(); - if (fieldNameChars.length == 1 && fieldNameChars[0] == '*') fieldNameChars = null; - - char[] declaringTypeQualification = null, declaringTypeSimpleName = null; - char[] typeQualification = null, typeSimpleName = null; - - // extract declaring type infos - if (declaringType != null) { - char[] declaringTypePart = declaringType.toCharArray(); - int lastDotPosition = CharOperation.lastIndexOf('.', declaringTypePart); - if (lastDotPosition >= 0) { - declaringTypeQualification = CharOperation.subarray(declaringTypePart, 0, lastDotPosition); - if (declaringTypeQualification.length == 1 && declaringTypeQualification[0] == '*') - declaringTypeQualification = null; - declaringTypeSimpleName = CharOperation.subarray(declaringTypePart, lastDotPosition+1, declaringTypePart.length); - } else { - declaringTypeSimpleName = declaringTypePart; - } - if (declaringTypeSimpleName.length == 1 && declaringTypeSimpleName[0] == '*') - declaringTypeSimpleName = null; - } - // extract type infos - if (type != null) { - char[] typePart = type.toCharArray(); - int lastDotPosition = CharOperation.lastIndexOf('.', typePart); - if (lastDotPosition >= 0) { - typeQualification = CharOperation.subarray(typePart, 0, lastDotPosition); - if (typeQualification.length == 1 && typeQualification[0] == '*') { - typeQualification = null; - } else { - // prefix with a '*' as the full qualification could be bigger (because of an import) - typeQualification = CharOperation.concat(IIndexConstants.ONE_STAR, typeQualification); - } - typeSimpleName = CharOperation.subarray(typePart, lastDotPosition+1, typePart.length); - } else { - typeSimpleName = typePart; - } - if (typeSimpleName.length == 1 && typeSimpleName[0] == '*') - typeSimpleName = null; - } - // Create field pattern - boolean findDeclarations = false; - boolean readAccess = false; - boolean writeAccess = false; - switch (limitTo) { - case IJavaScriptSearchConstants.DECLARATIONS : - findDeclarations = true; - break; - case IJavaScriptSearchConstants.REFERENCES : - readAccess = true; - writeAccess = true; - break; - case IJavaScriptSearchConstants.READ_ACCESSES : - readAccess = true; - break; - case IJavaScriptSearchConstants.WRITE_ACCESSES : - writeAccess = true; - break; - case IJavaScriptSearchConstants.ALL_OCCURRENCES : - findDeclarations = true; - readAccess = true; - writeAccess = true; - break; - } - return new FieldPattern( - findDeclarations, - readAccess, - writeAccess, - isVar, - fieldNameChars, - declaringTypeQualification, - declaringTypeSimpleName, - typeQualification, - typeSimpleName, - matchRule,null); -} - -/** - * Method pattern are formed by:
- * [declaringType '.'] ['<' typeArguments '>'] selector ['(' parameterTypes ')'] [returnType] - *
e.g.
    - *
  • java.lang.Runnable.run() void
  • - *
  • main(*)
  • - *
  • <String>toArray(String[])
  • - *
- * Constructor pattern are formed by:
- * [declaringQualification '.'] ['<' typeArguments '>'] type ['(' parameterTypes ')'] - *
e.g.
    - *
  • java.lang.Object()
  • - *
  • Main(*)
  • - *
  • <Exception>Sample(Exception)
  • - *
- * Type arguments have the same pattern that for type patterns - * @see #createTypePattern(String,int,int,char) - */ -private static SearchPattern createMethodOrConstructorPattern(String patternString, int limitTo, int matchRule, boolean isConstructor, boolean isFunction) { - - Scanner scanner = new Scanner(false /*comment*/, true /*whitespace*/, false /*nls*/, ClassFileConstants.JDK1_3/*sourceLevel*/, null /*taskTags*/, null/*taskPriorities*/, true/*taskCaseSensitive*/); - scanner.setSource(patternString.toCharArray()); - final int InsideSelector = 1; - final int InsideTypeArguments = 2; - final int InsideParameter = 3; - final int InsideReturnType = 4; - int lastToken = -1; - - String declaringType = null, selector = null, parameterType = null; - String[] parameterTypes = null; - char[][] typeArguments = null; - String typeArgumentsString = null; - int parameterCount = -1; - String returnType = null; - boolean foundClosingParenthesis = false; - int mode = InsideSelector; - int token, argCount = 0; - try { - token = scanner.getNextToken(); - } catch (InvalidInputException e) { - return null; - } - while (token != TerminalTokens.TokenNameEOF) { - switch(mode) { - // read declaring type and selector - case InsideSelector : - if (argCount == 0) { - switch (token) { - case TerminalTokens.TokenNameLESS: - argCount++; - if (selector == null || lastToken == TerminalTokens.TokenNameDOT) { - if (typeArgumentsString != null) return null; // invalid syntax - typeArgumentsString = scanner.getCurrentTokenString(); - mode = InsideTypeArguments; - break; - } - if (declaringType == null) { - declaringType = selector; - } else { - declaringType += '.' + selector; - } - declaringType += scanner.getCurrentTokenString(); - selector = null; - break; - case TerminalTokens.TokenNameDOT: - if (typeArgumentsString != null) return null; // invalid syntax - if (declaringType == null) { - if (selector == null) return null; // invalid syntax - declaringType = selector; - } else if (selector != null) { - declaringType += scanner.getCurrentTokenString() + selector; - } - selector = null; - break; - case TerminalTokens.TokenNameLPAREN: - parameterTypes = new String[5]; - parameterCount = 0; - mode = InsideParameter; - break; - case TerminalTokens.TokenNameWHITESPACE: - switch (lastToken) { - case TerminalTokens.TokenNameWHITESPACE: - case TerminalTokens.TokenNameDOT: - case TerminalTokens.TokenNameGREATER: - case TerminalTokens.TokenNameRIGHT_SHIFT: - case TerminalTokens.TokenNameUNSIGNED_RIGHT_SHIFT: - break; - default: - mode = InsideReturnType; - break; - } - break; - default: // all other tokens are considered identifiers (see bug 21763 Problem in JavaScript search [search]) - if (selector == null) - selector = scanner.getCurrentTokenString(); - else - selector += scanner.getCurrentTokenString(); - break; - } - } else { - if (declaringType == null) return null; // invalid syntax - switch (token) { - case TerminalTokens.TokenNameGREATER: - case TerminalTokens.TokenNameRIGHT_SHIFT: - case TerminalTokens.TokenNameUNSIGNED_RIGHT_SHIFT: - argCount--; - break; - case TerminalTokens.TokenNameLESS: - argCount++; - break; - } - declaringType += scanner.getCurrentTokenString(); - } - break; - // read type arguments - case InsideTypeArguments: - if (typeArgumentsString == null) return null; // invalid syntax - typeArgumentsString += scanner.getCurrentTokenString(); - switch (token) { - case TerminalTokens.TokenNameGREATER: - case TerminalTokens.TokenNameRIGHT_SHIFT: - case TerminalTokens.TokenNameUNSIGNED_RIGHT_SHIFT: - argCount--; - if (argCount == 0) { - typeArguments = new char[0][0]; - mode = InsideSelector; - } - break; - case TerminalTokens.TokenNameLESS: - argCount++; - break; - } - break; - // read parameter types - case InsideParameter : - if (argCount == 0) { - switch (token) { - case TerminalTokens.TokenNameWHITESPACE: - break; - case TerminalTokens.TokenNameCOMMA: - if (parameterType == null) return null; - if (parameterTypes != null) { - if (parameterTypes.length == parameterCount) - System.arraycopy(parameterTypes, 0, parameterTypes = new String[parameterCount*2], 0, parameterCount); - parameterTypes[parameterCount++] = parameterType; - } - parameterType = null; - break; - case TerminalTokens.TokenNameRPAREN: - foundClosingParenthesis = true; - if (parameterType != null && parameterTypes != null) { - if (parameterTypes.length == parameterCount) - System.arraycopy(parameterTypes, 0, parameterTypes = new String[parameterCount*2], 0, parameterCount); - parameterTypes[parameterCount++] = parameterType; - } - mode = isConstructor ? InsideTypeArguments : InsideReturnType; - break; - case TerminalTokens.TokenNameLESS: - argCount++; - if (parameterType == null) return null; // invalid syntax - // fall through next case to add token - default: // all other tokens are considered identifiers (see bug 21763 Problem in JavaScript search [search]) - if (parameterType == null) - parameterType = scanner.getCurrentTokenString(); - else - parameterType += scanner.getCurrentTokenString(); - } - } else { - if (parameterType == null) return null; // invalid syntax - switch (token) { - case TerminalTokens.TokenNameGREATER: - case TerminalTokens.TokenNameRIGHT_SHIFT: - case TerminalTokens.TokenNameUNSIGNED_RIGHT_SHIFT: - argCount--; - break; - case TerminalTokens.TokenNameLESS: - argCount++; - break; - } - parameterType += scanner.getCurrentTokenString(); - } - break; - // read return type - case InsideReturnType: - if (argCount == 0) { - switch (token) { - case TerminalTokens.TokenNameWHITESPACE: - break; - case TerminalTokens.TokenNameLPAREN: - parameterTypes = new String[5]; - parameterCount = 0; - mode = InsideParameter; - break; - case TerminalTokens.TokenNameLESS: - argCount++; - if (returnType == null) return null; // invalid syntax - // fall through next case to add token - default: // all other tokens are considered identifiers (see bug 21763 Problem in JavaScript search [search]) - if (returnType == null) - returnType = scanner.getCurrentTokenString(); - else - returnType += scanner.getCurrentTokenString(); - } - } else { - if (returnType == null) return null; // invalid syntax - switch (token) { - case TerminalTokens.TokenNameGREATER: - case TerminalTokens.TokenNameRIGHT_SHIFT: - case TerminalTokens.TokenNameUNSIGNED_RIGHT_SHIFT: - argCount--; - break; - case TerminalTokens.TokenNameLESS: - argCount++; - break; - } - returnType += scanner.getCurrentTokenString(); - } - break; - } - lastToken = token; - try { - token = scanner.getNextToken(); - } catch (InvalidInputException e) { - return null; - } - } - // parenthesis mismatch - if (parameterCount>0 && !foundClosingParenthesis) return null; - // type arguments mismatch - if (argCount > 0) return null; - - char[] selectorChars = null; - if (isConstructor) { - // retrieve type for constructor patterns - if (declaringType == null) - declaringType = selector; - else if (selector != null) - declaringType += '.' + selector; - } else { - // get selector chars - if (selector == null) return null; - selectorChars = selector.toCharArray(); - if (selectorChars.length == 1 && selectorChars[0] == '*') - selectorChars = null; - } - - char[] declaringTypeQualification = null, declaringTypeSimpleName = null; - char[] returnTypeQualification = null, returnTypeSimpleName = null; - char[][] parameterTypeQualifications = null, parameterTypeSimpleNames = null; - // Signatures - String declaringTypeSignature = null; - String returnTypeSignature = null; - String[] parameterTypeSignatures = null; - - // extract declaring type infos - if (declaringType != null) { - // get declaring type part and signature - char[] declaringTypePart = null; - try { - declaringTypeSignature = Signature.createTypeSignature(declaringType, false); - declaringTypePart = declaringType.toCharArray(); - } - catch (IllegalArgumentException iae) { - // declaring type is invalid - return null; - } - int lastDotPosition = CharOperation.lastIndexOf('.', declaringTypePart); - if (lastDotPosition >= 0) { - declaringTypeQualification = CharOperation.subarray(declaringTypePart, 0, lastDotPosition); - if (declaringTypeQualification.length == 1 && declaringTypeQualification[0] == '*') - declaringTypeQualification = null; - declaringTypeSimpleName = CharOperation.subarray(declaringTypePart, lastDotPosition+1, declaringTypePart.length); - } else { - declaringTypeSimpleName = declaringTypePart; - } - if (declaringTypeSimpleName.length == 1 && declaringTypeSimpleName[0] == '*') - declaringTypeSimpleName = null; - } - // extract parameter types infos - if (parameterCount >= 0) { - parameterTypeQualifications = new char[parameterCount][]; - parameterTypeSimpleNames = new char[parameterCount][]; - parameterTypeSignatures = new String[parameterCount]; - for (int i = 0; i < parameterCount; i++) { - // get parameter type part and signature - char[] parameterTypePart = null; - try { - if (parameterTypes != null) { - parameterTypeSignatures[i] = Signature.createTypeSignature(parameterTypes[i], false); - parameterTypePart = parameterTypes[i].toCharArray(); - } - } - catch (IllegalArgumentException iae) { - // string is not a valid type syntax - return null; - } - int lastDotPosition = parameterTypePart==null ? -1 : CharOperation.lastIndexOf('.', parameterTypePart); - if (parameterTypePart != null && lastDotPosition >= 0) { - parameterTypeQualifications[i] = CharOperation.subarray(parameterTypePart, 0, lastDotPosition); - if (parameterTypeQualifications[i].length == 1 && parameterTypeQualifications[i][0] == '*') { - parameterTypeQualifications[i] = null; - } else { - // prefix with a '*' as the full qualification could be bigger (because of an import) - parameterTypeQualifications[i] = CharOperation.concat(IIndexConstants.ONE_STAR, parameterTypeQualifications[i]); - } - parameterTypeSimpleNames[i] = CharOperation.subarray(parameterTypePart, lastDotPosition+1, parameterTypePart.length); - } else { - parameterTypeQualifications[i] = null; - parameterTypeSimpleNames[i] = parameterTypePart; - } - if (parameterTypeSimpleNames[i].length == 1 && parameterTypeSimpleNames[i][0] == '*') - parameterTypeSimpleNames[i] = null; - } - } - // extract return type infos - if (returnType != null) { - // get return type part and signature - char[] returnTypePart = null; - try { - returnTypeSignature = Signature.createTypeSignature(returnType, false); - returnTypePart = returnType.toCharArray(); - } - catch (IllegalArgumentException iae) { - // declaring type is invalid - return null; - } - int lastDotPosition = CharOperation.lastIndexOf('.', returnTypePart); - if (lastDotPosition >= 0) { - returnTypeQualification = CharOperation.subarray(returnTypePart, 0, lastDotPosition); - if (returnTypeQualification.length == 1 && returnTypeQualification[0] == '*') { - returnTypeQualification = null; - } else { - // because of an import - returnTypeQualification = CharOperation.concat(IIndexConstants.ONE_STAR, returnTypeQualification); - } - returnTypeSimpleName = CharOperation.subarray(returnTypePart, lastDotPosition+1, returnTypePart.length); - } else { - returnTypeSimpleName = returnTypePart; - } - if (returnTypeSimpleName.length == 1 && returnTypeSimpleName[0] == '*') - returnTypeSimpleName = null; - } - // Create method/constructor pattern - boolean findDeclarations = true; - boolean findReferences = true; - switch (limitTo) { - case IJavaScriptSearchConstants.DECLARATIONS : - findReferences = false; - break; - case IJavaScriptSearchConstants.REFERENCES : - findDeclarations = false; - break; - case IJavaScriptSearchConstants.ALL_OCCURRENCES : - break; - } - if (isConstructor) { - return new ConstructorPattern( - findDeclarations, - findReferences, - declaringTypeSimpleName, - declaringTypeQualification, - declaringTypeSignature, - parameterTypeQualifications, - parameterTypeSimpleNames, - parameterTypeSignatures, - typeArguments, - matchRule); - } else { - return new MethodPattern( - findDeclarations, - findReferences, - isFunction, - selectorChars, - declaringTypeQualification, - declaringTypeSimpleName, - declaringTypeSignature, - returnTypeQualification, - returnTypeSimpleName, - returnTypeSignature, - parameterTypeQualifications, - parameterTypeSimpleNames, - parameterTypeSignatures, - typeArguments, - matchRule); - } -} - -/** - * Returns a search pattern that combines the given two patterns into an - * "or" pattern. The search result will match either the left pattern or the - * right pattern. - * - * @param leftPattern the left pattern - * @param rightPattern the right pattern - * @return an "or" pattern - */ -public static SearchPattern createOrPattern(SearchPattern leftPattern, SearchPattern rightPattern) { - return new OrPattern(leftPattern, rightPattern); -} - -private static SearchPattern createPackagePattern(String patternString, int limitTo, int matchRule) { - switch (limitTo) { - case IJavaScriptSearchConstants.DECLARATIONS : - return new PackageDeclarationPattern(patternString.toCharArray(), matchRule); - case IJavaScriptSearchConstants.REFERENCES : - return new PackageReferencePattern(patternString.toCharArray(), matchRule); - case IJavaScriptSearchConstants.ALL_OCCURRENCES : - return new OrPattern( - new PackageDeclarationPattern(patternString.toCharArray(), matchRule), - new PackageReferencePattern(patternString.toCharArray(), matchRule) - ); - } - return null; -} - -/** - * Returns a search pattern based on a given string pattern. The string patterns support '*' wild-cards. - * The remaining parameters are used to narrow down the type of expected results. - * - *
- * Examples: - *
    - *
  • search for case insensitive references to Object: - * createSearchPattern("Object", TYPE, REFERENCES, false);
  • - *
  • search for case sensitive references to exact Object() constructor: - * createSearchPattern("java.lang.Object()", CONSTRUCTOR, REFERENCES, true);
  • - *
  • search for implementers of java.lang.Runnable: - * createSearchPattern("java.lang.Runnable", TYPE, IMPLEMENTORS, true);
  • - *
- * @param stringPattern the given pattern - * @param searchFor determines the nature of the searched elements - *
    - *
  • {@link IJavaScriptSearchConstants#CLASS}: only look for classes
  • - *
  • {@link IJavaScriptSearchConstants#INTERFACE}: only look for interfaces
  • - *
  • {@link IJavaScriptSearchConstants#ENUM}: only look for enumeration
  • - *
  • {@link IJavaScriptSearchConstants#ANNOTATION_TYPE}: only look for annotation type
  • - *
  • {@link IJavaScriptSearchConstants#CLASS_AND_ENUM}: only look for classes and enumerations
  • - *
  • {@link IJavaScriptSearchConstants#CLASS_AND_INTERFACE}: only look for classes and interfaces
  • - *
  • {@link IJavaScriptSearchConstants#TYPE}: look for all types (ie. classes, interfaces, enum and annotation types)
  • - *
  • {@link IJavaScriptSearchConstants#FIELD}: look for fields
  • - *
  • {@link IJavaScriptSearchConstants#METHOD}: look for methods
  • - *
  • {@link IJavaScriptSearchConstants#CONSTRUCTOR}: look for constructors
  • - *
  • {@link IJavaScriptSearchConstants#PACKAGE}: look for packages
  • - *
- * @param limitTo determines the nature of the expected matches - *
    - *
  • {@link IJavaScriptSearchConstants#DECLARATIONS}: will search declarations matching - * with the corresponding element. In case the element is a method, declarations of matching - * methods in subtypes will also be found, allowing to find declarations of abstract methods, etc.
    - * Note that additional flags {@link IJavaScriptSearchConstants#IGNORE_DECLARING_TYPE} and - * {@link IJavaScriptSearchConstants#IGNORE_RETURN_TYPE} are ignored for string patterns. - * This is due to the fact that client may omit to define them in string pattern to have same behavior. - *
  • - *
  • {@link IJavaScriptSearchConstants#REFERENCES}: will search references to the given element.
  • - *
  • {@link IJavaScriptSearchConstants#ALL_OCCURRENCES}: will search for either declarations or - * references as specified above. - *
  • - *
  • {@link IJavaScriptSearchConstants#IMPLEMENTORS}: for types, will find all types - * which directly implement/extend a given interface. - * Note that types may be only classes or only interfaces if {@link IJavaScriptSearchConstants#CLASS } or - * {@link IJavaScriptSearchConstants#INTERFACE} is respectively used instead of {@link IJavaScriptSearchConstants#TYPE}. - *
  • - *
- * @param matchRule one of {@link #R_EXACT_MATCH}, {@link #R_PREFIX_MATCH}, {@link #R_PATTERN_MATCH}, - * {@link #R_REGEXP_MATCH}, {@link #R_CAMELCASE_MATCH} combined with one of following values: - * {@link #R_CASE_SENSITIVE}, {@link #R_ERASURE_MATCH} or {@link #R_EQUIVALENT_MATCH}. - * e.g. {@link #R_EXACT_MATCH} | {@link #R_CASE_SENSITIVE} if an exact and case sensitive match is requested, - * {@link #R_PREFIX_MATCH} if a prefix non case sensitive match is requested or {@link #R_EXACT_MATCH} | {@link #R_ERASURE_MATCH} - * if a non case sensitive and erasure match is requested.
- * Note that {@link #R_ERASURE_MATCH} or {@link #R_EQUIVALENT_MATCH} have no effect - * on non-generic types/methods search.
- * Note also that default behavior for generic types/methods search is to find exact matches. - * @return a search pattern on the given string pattern, or null if the string pattern is ill-formed - */ -public static SearchPattern createPattern(String stringPattern, int searchFor, int limitTo, int matchRule) { - if (stringPattern == null || stringPattern.length() == 0) return null; - - if ((matchRule = validateMatchRule(stringPattern, matchRule)) == -1) { - return null; - } - - // Ignore additional nature flags - limitTo &= ~(IJavaScriptSearchConstants.IGNORE_DECLARING_TYPE+IJavaScriptSearchConstants.IGNORE_RETURN_TYPE); - - switch (searchFor) { - case IJavaScriptSearchConstants.CLASS: - return createTypePattern(stringPattern, limitTo, matchRule, IIndexConstants.CLASS_SUFFIX); - case IJavaScriptSearchConstants.TYPE: - return createTypePattern(stringPattern, limitTo, matchRule, IIndexConstants.TYPE_SUFFIX); - case IJavaScriptSearchConstants.FUNCTION: - return createMethodOrConstructorPattern(stringPattern, limitTo, matchRule, false/*not a constructor*/,true); - case IJavaScriptSearchConstants.METHOD: - return createMethodOrConstructorPattern(stringPattern, limitTo, matchRule, false/*not a constructor*/,false); - case IJavaScriptSearchConstants.CONSTRUCTOR: - return createMethodOrConstructorPattern(stringPattern, limitTo, matchRule, true/*constructor*/,false); - case IJavaScriptSearchConstants.FIELD: - return createFieldPattern(stringPattern, limitTo, matchRule,false); - case IJavaScriptSearchConstants.VAR: - return createFieldPattern(stringPattern, limitTo, matchRule,true); - case IJavaScriptSearchConstants.PACKAGE: - return createPackagePattern(stringPattern, limitTo, matchRule); - } - return null; -} - -/** - * Returns a search pattern based on a given JavaScript element. - * The pattern is used to trigger the appropriate search. - *
- * Note that for generic searches, the returned pattern consider {@link #R_ERASURE_MATCH} matches. - * If other kind of generic matches (ie. {@link #R_EXACT_MATCH} or {@link #R_EQUIVALENT_MATCH}) - * are expected, {@link #createPattern(IJavaScriptElement, int, int)} method need to be used instead with - * the explicit match rule specified. - *
- * The pattern can be parameterized as follows: - * - * @param element the JavaScript element the search pattern is based on - * @param limitTo determines the nature of the expected matches - *
    - *
  • {@link IJavaScriptSearchConstants#DECLARATIONS}: will search declarations matching - * with the corresponding element. In case the element is a method, declarations of matching - * methods in subtypes will also be found, allowing to find declarations of abstract methods, etc. - * Some additional flags may be specified while searching declaration: - *
      - *
    • {@link IJavaScriptSearchConstants#IGNORE_DECLARING_TYPE}: declaring type will be ignored - * during the search.
      - * For example using following test case: - *
      - *                  class A { A method() { return null; } }
      - *                  class B extends A { B method() { return null; } }
      - *                  class C { A method() { return null; } }
      - *					
      - * search for method declaration with this flag - * will return 2 matches: in A and in C - *
    • - *
    • {@link IJavaScriptSearchConstants#IGNORE_RETURN_TYPE}: return type will be ignored - * during the search.
      - * Using same example, search for method declaration with this flag - * will return 2 matches: in A and in B. - *
    • - *
    - * Note that these two flags may be combined and both declaring and return types can be ignored - * during the search. Then, using same example, search for method declaration - * with these 2 flags will return 3 matches: in A, in B and in C - *
  • - *
  • {@link IJavaScriptSearchConstants#REFERENCES}: will search references to the given element.
  • - *
  • {@link IJavaScriptSearchConstants#ALL_OCCURRENCES}: will search for either declarations or - * references as specified above. - *
  • - *
  • {@link IJavaScriptSearchConstants#IMPLEMENTORS}: for types, will find all types - * which directly implement/extend a given interface. - *
  • - *
- * @return a search pattern for a JavaScript element or null if the given element is ill-formed - */ -public static SearchPattern createPattern(IJavaScriptElement element, int limitTo) { - return createPattern(element, limitTo, R_EXACT_MATCH | R_CASE_SENSITIVE | R_ERASURE_MATCH); -} - -/** - * Returns a search pattern based on a given JavaScript element. - * The pattern is used to trigger the appropriate search, and can be parameterized as follows: - * - * @param element the JavaScript element the search pattern is based on - * @param limitTo determines the nature of the expected matches - *
    - *
  • {@link IJavaScriptSearchConstants#DECLARATIONS}: will search declarations matching - * with the corresponding element. In case the element is a method, declarations of matching - * methods in subtypes will also be found, allowing to find declarations of abstract methods, etc. - * Some additional flags may be specified while searching declaration: - *
      - *
    • {@link IJavaScriptSearchConstants#IGNORE_DECLARING_TYPE}: declaring type will be ignored - * during the search.
      - * For example using following test case: - *
      - *                  class A { A method() { return null; } }
      - *                  class B extends A { B method() { return null; } }
      - *                  class C { A method() { return null; } }
      - *					
      - * search for method declaration with this flag - * will return 2 matches: in A and in C - *
    • - *
    • {@link IJavaScriptSearchConstants#IGNORE_RETURN_TYPE}: return type will be ignored - * during the search.
      - * Using same example, search for method declaration with this flag - * will return 2 matches: in A and in B. - *
    • - *
    - * Note that these two flags may be combined and both declaring and return types can be ignored - * during the search. Then, using same example, search for method declaration - * with these 2 flags will return 3 matches: in A, in B and in C - *
  • - *
  • {@link IJavaScriptSearchConstants#REFERENCES}: will search references to the given element.
  • - *
  • {@link IJavaScriptSearchConstants#ALL_OCCURRENCES}: will search for either declarations or - * references as specified above. - *
  • - *
  • {@link IJavaScriptSearchConstants#IMPLEMENTORS}: for types, will find all types - * which directly implement/extend a given interface. - *
  • - *
- * @param matchRule one of {@link #R_EXACT_MATCH}, {@link #R_PREFIX_MATCH}, {@link #R_PATTERN_MATCH}, - * {@link #R_REGEXP_MATCH}, {@link #R_CAMELCASE_MATCH} combined with one of following values: - * {@link #R_CASE_SENSITIVE}, {@link #R_ERASURE_MATCH} or {@link #R_EQUIVALENT_MATCH}. - * e.g. {@link #R_EXACT_MATCH} | {@link #R_CASE_SENSITIVE} if an exact and case sensitive match is requested, - * {@link #R_PREFIX_MATCH} if a prefix non case sensitive match is requested or {@link #R_EXACT_MATCH} |{@link #R_ERASURE_MATCH} - * if a non case sensitive and erasure match is requested.
- * Note that {@link #R_ERASURE_MATCH} or {@link #R_EQUIVALENT_MATCH} have no effect on non-generic types - * or methods search.
- * Note also that default behavior for generic types or methods is to find exact matches. - * @return a search pattern for a JavaScript element or null if the given element is ill-formed - * - */ -public static SearchPattern createPattern(IJavaScriptElement element, int limitTo, int matchRule) { - SearchPattern searchPattern = null; - int lastDot; - boolean ignoreDeclaringType = false; - boolean ignoreReturnType = false; - int maskedLimitTo = limitTo & ~(IJavaScriptSearchConstants.IGNORE_DECLARING_TYPE+IJavaScriptSearchConstants.IGNORE_RETURN_TYPE); - if (maskedLimitTo == IJavaScriptSearchConstants.DECLARATIONS || maskedLimitTo == IJavaScriptSearchConstants.ALL_OCCURRENCES) { - ignoreDeclaringType = (limitTo & IJavaScriptSearchConstants.IGNORE_DECLARING_TYPE) != 0; - ignoreReturnType = (limitTo & IJavaScriptSearchConstants.IGNORE_RETURN_TYPE) != 0; - } - char[] declaringSimpleName = null; - char[] declaringQualification = null; - boolean isVar=false; - boolean isFunction=false; - switch (element.getElementType()) { - case IJavaScriptElement.FIELD : - IField field = (IField) element; - IType declaringClassForField = field.getDeclaringType(); - isVar=(declaringClassForField==null); - if (!ignoreDeclaringType) { - if (declaringClassForField!=null) - { - declaringSimpleName = declaringClassForField.getElementName().toCharArray(); - declaringQualification = declaringClassForField.getPackageFragment().getElementName().toCharArray(); - char[][] enclosingNames = enclosingTypeNames(declaringClassForField); - if (enclosingNames.length > 0) { - declaringQualification = CharOperation.concat(declaringQualification, CharOperation.concatWith(enclosingNames, '.'), '.'); - } - } - } - char[] name = field.getElementName().toCharArray(); - char[] typeSimpleName = null; - char[] typeQualification = null; - String typeSignature = null; - if (!ignoreReturnType) { - try { - typeSignature = field.getTypeSignature(); - char[] signature = typeSignature.toCharArray(); - char[] typeErasure = Signature.toCharArray(signature); - CharOperation.replace(typeErasure, '$', '.'); - if ((lastDot = CharOperation.lastIndexOf('.', typeErasure)) == -1) { - typeSimpleName = typeErasure; - } else { - typeSimpleName = CharOperation.subarray(typeErasure, lastDot + 1, typeErasure.length); - typeQualification = CharOperation.subarray(typeErasure, 0, lastDot); - if (!field.isBinary()) { - // prefix with a '*' as the full qualification could be bigger (because of an import) - typeQualification = CharOperation.concat(IIndexConstants.ONE_STAR, typeQualification); - } - } - } catch (JavaScriptModelException e) { - return null; - } - } - - // Create field pattern - boolean findDeclarations = false; - boolean readAccess = false; - boolean writeAccess = false; - switch (maskedLimitTo) { - case IJavaScriptSearchConstants.DECLARATIONS : - findDeclarations = true; - break; - case IJavaScriptSearchConstants.REFERENCES : - readAccess = true; - writeAccess = true; - break; - case IJavaScriptSearchConstants.READ_ACCESSES : - readAccess = true; - break; - case IJavaScriptSearchConstants.WRITE_ACCESSES : - writeAccess = true; - break; - case IJavaScriptSearchConstants.ALL_OCCURRENCES : - findDeclarations = true; - readAccess = true; - writeAccess = true; - break; - } - searchPattern = - new FieldPattern( - findDeclarations, - readAccess, - writeAccess, - isVar, - name, - declaringQualification, - declaringSimpleName, - typeQualification, - typeSimpleName, - typeSignature, - matchRule,field); - break; - case IJavaScriptElement.IMPORT_DECLARATION : - String elementName = element.getElementName(); - lastDot = elementName.lastIndexOf('.'); - if (lastDot == -1) return null; // invalid import declaration - IImportDeclaration importDecl = (IImportDeclaration)element; - if (importDecl.isOnDemand()) { - searchPattern = createPackagePattern(elementName.substring(0, lastDot), maskedLimitTo, matchRule); - } else { - searchPattern = - createTypePattern( - elementName.substring(lastDot+1).toCharArray(), - elementName.substring(0, lastDot).toCharArray(), - null, - null, - null, - maskedLimitTo, - matchRule); - } - break; - case IJavaScriptElement.LOCAL_VARIABLE : - LocalVariable localVar = (LocalVariable) element; - boolean findVarDeclarations = false; - boolean findVarReadAccess = false; - boolean findVarWriteAccess = false; - switch (maskedLimitTo) { - case IJavaScriptSearchConstants.DECLARATIONS : - findVarDeclarations = true; - break; - case IJavaScriptSearchConstants.REFERENCES : - findVarReadAccess = true; - findVarWriteAccess = true; - break; - case IJavaScriptSearchConstants.READ_ACCESSES : - findVarReadAccess = true; - break; - case IJavaScriptSearchConstants.WRITE_ACCESSES : - findVarWriteAccess = true; - break; - case IJavaScriptSearchConstants.ALL_OCCURRENCES : - findVarDeclarations = true; - findVarReadAccess = true; - findVarWriteAccess = true; - break; - } - searchPattern = - new LocalVariablePattern( - findVarDeclarations, - findVarReadAccess, - findVarWriteAccess, - localVar, - matchRule); - break; - case IJavaScriptElement.METHOD : - IFunction method = (IFunction) element; - boolean isConstructor; - try { - isConstructor = method.isConstructor(); - } catch (JavaScriptModelException e) { - return null; - } - IType declaringClass = method.getDeclaringType(); - - if (declaringClass!=null) { - if (ignoreDeclaringType) { - if (isConstructor) - declaringSimpleName = declaringClass.getElementName() - .toCharArray(); - } else { - declaringSimpleName = declaringClass.getElementName() - .toCharArray(); - declaringQualification = declaringClass - .getPackageFragment().getElementName() - .toCharArray(); - char[][] enclosingNames = enclosingTypeNames(declaringClass); - if (enclosingNames.length > 0) { - declaringQualification = CharOperation.concat( - declaringQualification, CharOperation - .concatWith(enclosingNames, '.'), '.'); - } - } - } - else - isFunction=true; - char[] selector = method.getElementName().toCharArray(); - char[] returnSimpleName = null; - char[] returnQualification = null; - String returnSignature = null; - if (!ignoreReturnType) { - try { - returnSignature = method.getReturnType(); - char[] signature = returnSignature.toCharArray(); - char[] returnErasure = Signature.toCharArray(signature); - CharOperation.replace(returnErasure, '$', '.'); - if ((lastDot = CharOperation.lastIndexOf('.', returnErasure)) == -1) { - returnSimpleName = returnErasure; - } else { - returnSimpleName = CharOperation.subarray(returnErasure, lastDot + 1, returnErasure.length); - returnQualification = CharOperation.subarray(returnErasure, 0, lastDot); - if (!method.isBinary()) { - // prefix with a '*' as the full qualification could be bigger (because of an import) - CharOperation.concat(IIndexConstants.ONE_STAR, returnQualification); - } - } - } catch (JavaScriptModelException e) { - return null; - } - } - String[] parameterTypes = method.getParameterTypes(); - int paramCount = parameterTypes.length; - char[][] parameterSimpleNames = new char[paramCount][]; - char[][] parameterQualifications = new char[paramCount][]; - String[] parameterSignatures = new String[paramCount]; - for (int i = 0; i < paramCount; i++) { - parameterSignatures[i] = parameterTypes[i]; - char[] signature = parameterSignatures[i].toCharArray(); - char[] paramErasure = Signature.toCharArray(signature); - CharOperation.replace(paramErasure, '$', '.'); - if ((lastDot = CharOperation.lastIndexOf('.', paramErasure)) == -1) { - parameterSimpleNames[i] = paramErasure; - parameterQualifications[i] = null; - } else { - parameterSimpleNames[i] = CharOperation.subarray(paramErasure, lastDot + 1, paramErasure.length); - parameterQualifications[i] = CharOperation.subarray(paramErasure, 0, lastDot); - if (!method.isBinary()) { - // prefix with a '*' as the full qualification could be bigger (because of an import) - CharOperation.concat(IIndexConstants.ONE_STAR, parameterQualifications[i]); - } - } - } - - // Create method/constructor pattern - boolean findMethodDeclarations = true; - boolean findMethodReferences = true; - switch (maskedLimitTo) { - case IJavaScriptSearchConstants.DECLARATIONS : - findMethodReferences = false; - break; - case IJavaScriptSearchConstants.REFERENCES : - findMethodDeclarations = false; - break; - case IJavaScriptSearchConstants.ALL_OCCURRENCES : - break; - } - if (isConstructor) { - searchPattern = - new ConstructorPattern( - findMethodDeclarations, - findMethodReferences, - declaringSimpleName, - declaringQualification, - parameterQualifications, - parameterSimpleNames, - parameterSignatures, - method, - matchRule); - } else { - searchPattern = - new MethodPattern( - findMethodDeclarations, - findMethodReferences, - isFunction, - selector, - declaringQualification, - declaringSimpleName, - returnQualification, - returnSimpleName, - returnSignature, - parameterQualifications, - parameterSimpleNames, - parameterSignatures, - method, - matchRule); - } - break; - case IJavaScriptElement.TYPE : - IType type = (IType)element; - searchPattern = createTypePattern( - type.getElementName().toCharArray(), - type.getPackageFragment().getElementName().toCharArray(), - ignoreDeclaringType ? null : enclosingTypeNames(type), - null, - type, - maskedLimitTo, - matchRule); - break; - case IJavaScriptElement.PACKAGE_FRAGMENT : - searchPattern = createPackagePattern(element.getElementName(), maskedLimitTo, matchRule); - break; - } - if (searchPattern != null) - MatchLocator.setFocus(searchPattern, element); - return searchPattern; -} - -private static SearchPattern createTypePattern(char[] simpleName, char[] packageName, char[][] enclosingTypeNames, String typeSignature, IType type, int limitTo, int matchRule) { - switch (limitTo) { - case IJavaScriptSearchConstants.DECLARATIONS : - return new TypeDeclarationPattern( - packageName, - enclosingTypeNames, - simpleName, - IIndexConstants.TYPE_SUFFIX, - matchRule); - case IJavaScriptSearchConstants.REFERENCES : - if (type != null) { - return new TypeReferencePattern( - CharOperation.concatWith(packageName, enclosingTypeNames, '.'), - simpleName, - type, - matchRule); - } - return new TypeReferencePattern( - CharOperation.concatWith(packageName, enclosingTypeNames, '.'), - simpleName, - typeSignature, - matchRule); - case IJavaScriptSearchConstants.IMPLEMENTORS : - return new SuperTypeReferencePattern( - CharOperation.concatWith(packageName, enclosingTypeNames, '.'), - simpleName, - matchRule); - case IJavaScriptSearchConstants.ALL_OCCURRENCES : - return new OrPattern( - new TypeDeclarationPattern( - packageName, - enclosingTypeNames, - simpleName, - IIndexConstants.TYPE_SUFFIX, - matchRule), - (type != null) - ? new TypeReferencePattern( - CharOperation.concatWith(packageName, enclosingTypeNames, '.'), - simpleName, - type, - matchRule) - : new TypeReferencePattern( - CharOperation.concatWith(packageName, enclosingTypeNames, '.'), - simpleName, - typeSignature, - matchRule) - ); - } - return null; -} -/** - * Type pattern are formed by [qualification '.']type [typeArguments]. - * e.g. java.lang.Object - * Runnable - * List<String> - */ -private static SearchPattern createTypePattern(String patternString, int limitTo, int matchRule, char indexSuffix) { - - Scanner scanner = new Scanner(false /*comment*/, true /*whitespace*/, false /*nls*/, ClassFileConstants.JDK1_3/*sourceLevel*/, null /*taskTags*/, null/*taskPriorities*/, true/*taskCaseSensitive*/); - scanner.setSource(patternString.toCharArray()); - String type = null; - int token; - try { - token = scanner.getNextToken(); - } catch (InvalidInputException e) { - return null; - } - int argCount = 0; - while (token != TerminalTokens.TokenNameEOF) { - if (argCount == 0) { - switch (token) { - case TerminalTokens.TokenNameWHITESPACE: - break; - case TerminalTokens.TokenNameLESS: - argCount++; - // fall through default case to add token to type - default: // all other tokens are considered identifiers (see bug 21763 Problem in JavaScript search [search]) - if (type == null) - type = scanner.getCurrentTokenString(); - else - type += scanner.getCurrentTokenString(); - } - } else { - switch (token) { - case TerminalTokens.TokenNameGREATER: - case TerminalTokens.TokenNameRIGHT_SHIFT: - case TerminalTokens.TokenNameUNSIGNED_RIGHT_SHIFT: - argCount--; - break; - case TerminalTokens.TokenNameLESS: - argCount++; - break; - } - if (type == null) return null; // invalid syntax - type += scanner.getCurrentTokenString(); - } - try { - token = scanner.getNextToken(); - } catch (InvalidInputException e) { - return null; - } - } - if (type == null) return null; - String typeSignature = null; - char[] qualificationChars = null, typeChars = null; - - // get type part and signature - char[] typePart = null; - try { - typeSignature = Signature.createTypeSignature(type, false); - typePart = type.toCharArray(); - } - catch (IllegalArgumentException iae) { - // string is not a valid type syntax - return null; - } - - // get qualification name - int lastDotPosition = CharOperation.lastIndexOf('.', typePart); - if (lastDotPosition >= 0) { - qualificationChars = CharOperation.subarray(typePart, 0, lastDotPosition); - if (qualificationChars.length == 1 && qualificationChars[0] == '*') - qualificationChars = null; - typeChars = CharOperation.subarray(typePart, lastDotPosition+1, typePart.length); - } else { - typeChars = typePart; - } - if (typeChars.length == 1 && typeChars[0] == '*') { - typeChars = null; - } - switch (limitTo) { - case IJavaScriptSearchConstants.DECLARATIONS : // cannot search for explicit member types - return new QualifiedTypeDeclarationPattern(qualificationChars, typeChars, indexSuffix, matchRule); - case IJavaScriptSearchConstants.REFERENCES : - return new TypeReferencePattern(qualificationChars, typeChars, typeSignature, matchRule); - case IJavaScriptSearchConstants.IMPLEMENTORS : - return new SuperTypeReferencePattern(qualificationChars, typeChars, matchRule); - case IJavaScriptSearchConstants.ALL_OCCURRENCES : - return new OrPattern( - new QualifiedTypeDeclarationPattern(qualificationChars, typeChars, indexSuffix, matchRule),// cannot search for explicit member types - new TypeReferencePattern(qualificationChars, typeChars, matchRule)); - } - return null; -} -/** - * Returns the enclosing type names of the given type. - */ -private static char[][] enclosingTypeNames(IType type) { - IJavaScriptElement parent = type.getParent(); - switch (parent.getElementType()) { - case IJavaScriptElement.CLASS_FILE: - // For a binary type, the parent is not the enclosing type, but the declaring type is. - // (see bug 20532 Declaration of member binary type not found) - IType declaringType = type.getDeclaringType(); - if (declaringType == null) return CharOperation.NO_CHAR_CHAR; - return CharOperation.arrayConcat( - enclosingTypeNames(declaringType), - declaringType.getElementName().toCharArray()); - case IJavaScriptElement.JAVASCRIPT_UNIT: - return CharOperation.NO_CHAR_CHAR; - case IJavaScriptElement.FIELD: - case IJavaScriptElement.INITIALIZER: - case IJavaScriptElement.METHOD: - IType declaringClass = ((IMember) parent).getDeclaringType(); - if (declaringClass!=null) - return CharOperation.arrayConcat( - enclosingTypeNames(declaringClass), - new char[][] {declaringClass.getElementName().toCharArray(), IIndexConstants.ONE_STAR}); - else - return CharOperation.NO_CHAR_CHAR; - case IJavaScriptElement.TYPE: - return CharOperation.arrayConcat( - enclosingTypeNames((IType)parent), - parent.getElementName().toCharArray()); - default: - return null; - } -} - -/** - * Decode the given index key in this pattern. The decoded index key is used by - * {@link #matchesDecodedKey(SearchPattern)} to find out if the corresponding index entry - * should be considered. - *

- * This method should be re-implemented in subclasses that need to decode an index key. - *

- * - * @param key the given index key - */ -public void decodeIndexKey(char[] key) { - // called from findIndexMatches(), override as necessary -} -/** - * Returns a blank pattern that can be used as a record to decode an index key. - *

- * Implementors of this method should return a new search pattern that is going to be used - * to decode index keys. - *

- * - * @return a new blank pattern - * @see #decodeIndexKey(char[]) - */ -public abstract SearchPattern getBlankPattern(); -/** - * Returns a key to find in relevant index categories, if null then all index entries are matched. - * The key will be matched according to some match rule. These potential matches - * will be further narrowed by the match locator, but precise match locating can be expensive, - * and index query should be as accurate as possible so as to eliminate obvious false hits. - *

- * This method should be re-implemented in subclasses that need to narrow down the - * index query. - *

- * - * @return an index key from this pattern, or null if all index entries are matched. - */ -public char[] getIndexKey() { - return null; // called from queryIn(), override as necessary -} -/** - * Returns an array of index categories to consider for this index query. - * These potential matches will be further narrowed by the match locator, but precise - * match locating can be expensive, and index query should be as accurate as possible - * so as to eliminate obvious false hits. - *

- * This method should be re-implemented in subclasses that need to narrow down the - * index query. - *

- * - * @return an array of index categories - */ -public char[][] getIndexCategories() { - return CharOperation.NO_CHAR_CHAR; // called from queryIn(), override as necessary -} -/** - * Returns the rule to apply for matching index keys. Can be exact match, prefix match, pattern match or regexp match. - * Rule can also be combined with a case sensitivity flag. - * - * @return one of R_EXACT_MATCH, R_PREFIX_MATCH, R_PATTERN_MATCH, R_REGEXP_MATCH combined with R_CASE_SENSITIVE, - * e.g. R_EXACT_MATCH | R_CASE_SENSITIVE if an exact and case sensitive match is requested, - * or R_PREFIX_MATCH if a prefix non case sensitive match is requested. - * [TODO (frederic) I hope R_ERASURE_MATCH doesn't need to be on this list. Because it would be a breaking API change.] - */ -public final int getMatchRule() { - return this.matchRule; -} -/** - * Returns whether this pattern matches the given pattern (representing a decoded index key). - *

- * This method should be re-implemented in subclasses that need to narrow down the - * index query. - *

- * - * @param decodedPattern a pattern representing a decoded index key - * @return whether this pattern matches the given pattern - */ -public boolean matchesDecodedKey(SearchPattern decodedPattern) { - return true; // called from findIndexMatches(), override as necessary if index key is encoded -} - -/** - * Returns whether the given name matches the given pattern. - *

- * This method should be re-implemented in subclasses that need to define how - * a name matches a pattern. - *

- * - * @param pattern the given pattern, or null to represent "*" - * @param name the given name - * @return whether the given name matches the given pattern - */ -public boolean matchesName(char[] pattern, char[] name) { - if (pattern == null) return true; // null is as if it was "*" - if (name != null) { - boolean isCaseSensitive = (this.matchRule & R_CASE_SENSITIVE) != 0; - boolean isCamelCase = (this.matchRule & R_CAMELCASE_MATCH) != 0; - int matchMode = this.matchRule & MODE_MASK; - boolean emptyPattern = pattern.length == 0; - if (matchMode == R_PREFIX_MATCH && emptyPattern) return true; - boolean sameLength = pattern.length == name.length; - boolean canBePrefix = name.length >= pattern.length; - boolean matchFirstChar = !isCaseSensitive || emptyPattern || (name.length > 0 && pattern[0] == name[0]); - if (isCamelCase && matchFirstChar && CharOperation.camelCaseMatch(pattern, name)) { - return true; - } - switch (matchMode) { - case R_EXACT_MATCH : - case R_FULL_MATCH : - if (!isCamelCase) { - if (sameLength && matchFirstChar) { - return CharOperation.equals(pattern, name, isCaseSensitive); - } - break; - } - // fall through next case to match as prefix if camel case failed - case R_PREFIX_MATCH : - if (canBePrefix && matchFirstChar) { - return CharOperation.prefixEquals(pattern, name, isCaseSensitive); - } - break; - - case R_PATTERN_MATCH : - if (!isCaseSensitive) - pattern = CharOperation.toLowerCase(pattern); - return CharOperation.match(pattern, name, isCaseSensitive); - - case R_REGEXP_MATCH : - // TODO (frederic) implement regular expression match - return true; - } - } - return false; -} - -/** - * Validate compatibility between given string pattern and match rule. - *
- * Optimized (ie. returned match rule is modified) combinations are: - *
    - *
  • {@link #R_PATTERN_MATCH} without any '*' or '?' in string pattern: - * pattern match bit is unset, - *
  • - *
  • {@link #R_PATTERN_MATCH} and {@link #R_PREFIX_MATCH} bits simultaneously set: - * prefix match bit is unset, - *
  • - *
  • {@link #R_PATTERN_MATCH} and {@link #R_CAMELCASE_MATCH} bits simultaneously set: - * camel case match bit is unset, - *
  • - *
  • {@link #R_CAMELCASE_MATCH} with invalid combination of uppercase and lowercase characters: - * camel case match bit is unset and replaced with prefix match pattern, - *
  • - *
  • {@link #R_CAMELCASE_MATCH} combined with {@link #R_PREFIX_MATCH} and {@link #R_CASE_SENSITIVE} - * bits is reduced to only {@link #R_CAMELCASE_MATCH} as Camel Case search is already prefix and case sensitive, - *
  • - *
- *
- * Rejected (ie. returned match rule -1) combinations are: - *
    - *
  • {@link #R_REGEXP_MATCH} with any other match mode bit set, - *
  • - *
- * - * @param stringPattern The string pattern - * @param matchRule The match rule - * @return Optimized valid match rule or -1 if an incompatibility was detected. - * - */ -public static int validateMatchRule(String stringPattern, int matchRule) { - - // Verify Regexp match rule - if ((matchRule & R_REGEXP_MATCH) != 0) { - if ((matchRule & R_PATTERN_MATCH) != 0 || (matchRule & R_PREFIX_MATCH) != 0 || (matchRule & R_CAMELCASE_MATCH) != 0) { - return -1; - } - } - - // Verify Pattern match rule - int starIndex = stringPattern.indexOf('*'); - int questionIndex = stringPattern.indexOf('?'); - if (starIndex < 0 && questionIndex < 0) { - // reset pattern match bit if any - matchRule &= ~R_PATTERN_MATCH; - } else { - // force Pattern rule - matchRule |= R_PATTERN_MATCH; - } - if ((matchRule & R_PATTERN_MATCH) != 0) { - // remove Camel Case and Prefix match bits if any - matchRule &= ~R_CAMELCASE_MATCH; - matchRule &= ~R_PREFIX_MATCH; - } - - // Verify Camel Case match rule - if ((matchRule & R_CAMELCASE_MATCH) != 0) { - // Verify sting pattern validity - int length = stringPattern.length(); - boolean validCamelCase = true; - boolean uppercase = false; - for (int i=0; iSearchPattern.createPattern + * to create a search pattern. + *

+ * Search patterns are used during the search phase to decode index entries that were added during the indexing phase + * (see {@link SearchDocument#addIndexEntry(char[], char[])}). When an index is queried, the + * index categories and keys to consider are retrieved from the search pattern using {@link #getIndexCategories()} and + * {@link #getIndexKey()}, as well as the match rule (see {@link #getMatchRule()}). A blank pattern is + * then created (see {@link #getBlankPattern()}). This blank pattern is used as a record as follows. + * For each index entry in the given index categories and that starts with the given key, the blank pattern is fed using + * {@link #decodeIndexKey(char[])}. The original pattern is then asked if it matches the decoded key using + * {@link #matchesDecodedKey(SearchPattern)}. If it matches, a search doument is created for this index entry + * using {@link SearchParticipant#getDocument(String)}. + * + *

+ * This class is intended to be subclassed by clients. A default behavior is provided for each of the methods above, that + * clients can ovveride if they wish. + *

+ * @see #createPattern(org.eclipse.wst.jsdt.core.IJavaScriptElement, int) + * @see #createPattern(String, int, int, int) + * + * Provisional API: This class/interface is part of an interim API that is still under development and expected to + * change significantly before reaching stability. It is being made available at this early stage to solicit feedback + * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken + * (repeatedly) as the API evolves. + */ +public abstract class SearchPattern extends InternalSearchPattern { + + // Rules for pattern matching: (exact, prefix, pattern) [ | case sensitive] + /** + * Match rule: The search pattern matches exactly the search result, + * that is, the source of the search result equals the search pattern. + */ + public static final int R_EXACT_MATCH = 0; + + /** + * Match rule: The search pattern is a prefix of the search result. + */ + public static final int R_PREFIX_MATCH = 0x0001; + + /** + * Match rule: The search pattern contains one or more wild cards ('*' or '?'). + * A '*' wild-card can replace 0 or more characters in the search result. + * A '?' wild-card replaces exactly 1 character in the search result. + */ + public static final int R_PATTERN_MATCH = 0x0002; + + /** + * Match rule: The search pattern contains a regular expression. + */ + public static final int R_REGEXP_MATCH = 0x0004; + + /** + * Match rule: The search pattern matches the search result only if cases are the same. + * Can be combined to previous rules, e.g. {@link #R_EXACT_MATCH} | {@link #R_CASE_SENSITIVE} + */ + public static final int R_CASE_SENSITIVE = 0x0008; + + /** + * Match rule: The search pattern matches search results as raw/parameterized types/methods with same erasure. + * This mode has no effect on other javascript elements search.
+ * Type search example: + *
    + *
  • pattern: List<Exception>
  • + *
  • match: List<Object>
  • + *
+ * Method search example: + *
    + *
  • declaration: <T>foo(T t)
  • + *
  • pattern: <Exception>foo(new Exception())
  • + *
  • match: <Object>foo(new Object())
  • + *
+ * Can be combined to all other match rules, e.g. {@link #R_CASE_SENSITIVE} | {@link #R_ERASURE_MATCH} + * This rule is not activated by default, so raw types or parameterized types with same erasure will not be found + * for pattern List<String>, + * Note that with this pattern, the match selection will be only on the erasure even for parameterized types. + * + */ + public static final int R_ERASURE_MATCH = 0x0010; + + /** + * Match rule: The search pattern matches search results as raw/parameterized types/methods with equivalent type parameters. + * This mode has no effect on other javascript elements search.
+ * Type search example: + *
    + *
  • pattern: List<Exception>
  • + *
  • match: + *
      + *
    • List<? extends Throwable>
    • + *
    • List<? super RuntimeException>
    • + *
    • List<?>
    • + *
    + *
  • + *
+ * Method search example: + *
    + *
  • declaration: <T>foo(T t)
  • + *
  • pattern: <Exception>foo(new Exception())
  • + *
  • match: + *
      + *
    • <? extends Throwable>foo(new Exception())
    • + *
    • <? super RuntimeException>foo(new Exception())
    • + *
    • foo(new Exception())
    • + *
    + *
+ * Can be combined to all other match rules, e.g. {@link #R_CASE_SENSITIVE} | {@link #R_EQUIVALENT_MATCH} + * This rule is not activated by default, so raw types or equivalent parameterized types will not be found + * for pattern List<String>, + * This mode is overridden by {@link #R_ERASURE_MATCH} as erasure matches obviously include equivalent ones. + * That means that pattern with rule set to {@link #R_EQUIVALENT_MATCH} | {@link #R_ERASURE_MATCH} + * will return same results than rule only set with {@link #R_ERASURE_MATCH}. + * + */ + public static final int R_EQUIVALENT_MATCH = 0x0020; + + /** + * Match rule: The search pattern matches exactly the search result, + * that is, the source of the search result equals the search pattern. + * + */ + public static final int R_FULL_MATCH = 0x0040; + + /** + * Match rule: The search pattern contains a Camel Case expression. + *
+ * Examples: + *
    + *
  • NPE type string pattern will match + * NullPointerException and NpPermissionException types,
  • + *
  • NuPoEx type string pattern will only match + * NullPointerException type.
  • + *
+ * @see CharOperation#camelCaseMatch(char[], char[]) for a detailed explanation + * of Camel Case matching. + *
+ * Can be combined to {@link #R_PREFIX_MATCH} match rule. For example, + * when prefix match rule is combined with Camel Case match rule, + * "nPE" pattern will match nPException. + *
+ * Match rule {@link #R_PATTERN_MATCH} may also be combined but both rules + * will not be used simultaneously as they are mutually exclusive. + * Used match rule depends on whether string pattern contains specific pattern + * characters (e.g. '*' or '?') or not. If it does, then only Pattern match rule + * will be used, otherwise only Camel Case match will be used. + * For example, with "NPE" string pattern, search will only use + * Camel Case match rule, but with N*P*E* string pattern, it will + * use only Pattern match rule. + * + * + */ + public static final int R_CAMELCASE_MATCH = 0x0080; + + private static final int MODE_MASK = R_EXACT_MATCH | R_PREFIX_MATCH | R_PATTERN_MATCH | R_REGEXP_MATCH; + + private int matchRule; + +/** + * Creates a search pattern with the rule to apply for matching index keys. + * It can be exact match, prefix match, pattern match or regexp match. + * Rule can also be combined with a case sensitivity flag. + * + * @param matchRule one of {@link #R_EXACT_MATCH}, {@link #R_PREFIX_MATCH}, {@link #R_PATTERN_MATCH}, + * {@link #R_REGEXP_MATCH}, {@link #R_CAMELCASE_MATCH} combined with one of following values: + * {@link #R_CASE_SENSITIVE}, {@link #R_ERASURE_MATCH} or {@link #R_EQUIVALENT_MATCH}. + * e.g. {@link #R_EXACT_MATCH} | {@link #R_CASE_SENSITIVE} if an exact and case sensitive match is requested, + * {@link #R_PREFIX_MATCH} if a prefix non case sensitive match is requested or {@link #R_EXACT_MATCH} | {@link #R_ERASURE_MATCH} + * if a non case sensitive and erasure match is requested.
+ * Note that {@link #R_ERASURE_MATCH} or {@link #R_EQUIVALENT_MATCH} have no effect + * on non-generic types/methods search.
+ * Note also that default behavior for generic types/methods search is to find exact matches. + */ +public SearchPattern(int matchRule) { + this.matchRule = matchRule; + // Set full match implicit mode + if ((matchRule & (R_EQUIVALENT_MATCH | R_ERASURE_MATCH )) == 0) { + this.matchRule |= R_FULL_MATCH; + } +} + +/** + * Answers true if the pattern matches the given name using CamelCase rules, or false otherwise. + * CamelCase matching does NOT accept explicit wild-cards '*' and '?' and is inherently case sensitive. + *
+ * CamelCase denotes the convention of writing compound names without spaces, and capitalizing every term. + * This function recognizes both upper and lower CamelCase, depending whether the leading character is capitalized + * or not. The leading part of an upper CamelCase pattern is assumed to contain a sequence of capitals which are appearing + * in the matching name; e.g. 'NPE' will match 'NullPointerException', but not 'NewPerfData'. A lower CamelCase pattern + * uses a lowercase first character. In Java, type names follow the upper CamelCase convention, whereas method or field + * names follow the lower CamelCase convention. + *
+ * The pattern may contain lowercase characters, which will be match in a case sensitive way. These characters must + * appear in sequence in the name. For instance, 'NPExcep' will match 'NullPointerException', but not 'NullPointerExCEPTION' + * or 'NuPoEx' will match 'NullPointerException', but not 'NoPointerException'. + *

+ * Examples: + *
    + *
  1. + *    pattern = "NPE"
    + *    name = NullPointerException / NoPermissionException
    + *    result => true
    + * 
    + *
  2. + *
  3. + *    pattern = "NuPoEx"
    + *    name = NullPointerException
    + *    result => true
    + * 
    + *
  4. + *
  5. + *    pattern = "npe"
    + *    name = NullPointerException
    + *    result => false
    + * 
    + *
  6. + *
+ * @see CharOperation#camelCaseMatch(char[], char[]) + * Implementation has been entirely copied from this method except for array lengthes + * which were obviously replaced with calls to {@link String#length()}. + * + * @param pattern the given pattern + * @param name the given name + * @return true if the pattern matches the given name, false otherwise + * + */ +public static final boolean camelCaseMatch(String pattern, String name) { + if (pattern == null) + return true; // null pattern is equivalent to '*' + if (name == null) + return false; // null name cannot match + + return camelCaseMatch(pattern, 0, pattern.length(), name, 0, name.length()); +} + +/** + * Answers true if a sub-pattern matches the subpart of the given name using CamelCase rules, or false otherwise. + * CamelCase matching does NOT accept explicit wild-cards '*' and '?' and is inherently case sensitive. + * Can match only subset of name/pattern, considering end positions as non-inclusive. + * The subpattern is defined by the patternStart and patternEnd positions. + *
+ * CamelCase denotes the convention of writing compound names without spaces, and capitalizing every term. + * This function recognizes both upper and lower CamelCase, depending whether the leading character is capitalized + * or not. The leading part of an upper CamelCase pattern is assumed to contain a sequence of capitals which are appearing + * in the matching name; e.g. 'NPE' will match 'NullPointerException', but not 'NewPerfData'. A lower CamelCase pattern + * uses a lowercase first character. In Java, type names follow the upper CamelCase convention, whereas method or field + * names follow the lower CamelCase convention. + *
+ * The pattern may contain lowercase characters, which will be match in a case sensitive way. These characters must + * appear in sequence in the name. For instance, 'NPExcep' will match 'NullPointerException', but not 'NullPointerExCEPTION' + * or 'NuPoEx' will match 'NullPointerException', but not 'NoPointerException'. + *

+ * Examples: + *
    + *
  1. + *    pattern = "NPE"
    + *    patternStart = 0
    + *    patternEnd = 3
    + *    name = NullPointerException
    + *    nameStart = 0
    + *    nameEnd = 20
    + *    result => true
    + * 
    + *
  2. + *
  3. + *    pattern = "NPE"
    + *    patternStart = 0
    + *    patternEnd = 3
    + *    name = NoPermissionException
    + *    nameStart = 0
    + *    nameEnd = 21
    + *    result => true
    + * 
    + *
  4. + *
  5. + *    pattern = "NuPoEx"
    + *    patternStart = 0
    + *    patternEnd = 6
    + *    name = NullPointerException
    + *    nameStart = 0
    + *    nameEnd = 20
    + *    result => true
    + * 
    + *
  6. + *
  7. + *    pattern = "NuPoEx"
    + *    patternStart = 0
    + *    patternEnd = 6
    + *    name = NoPermissionException
    + *    nameStart = 0
    + *    nameEnd = 21
    + *    result => false
    + * 
    + *
  8. + *
  9. + *    pattern = "npe"
    + *    patternStart = 0
    + *    patternEnd = 3
    + *    name = NullPointerException
    + *    nameStart = 0
    + *    nameEnd = 20
    + *    result => false
    + * 
    + *
  10. + *
+ * @see CharOperation#camelCaseMatch(char[], int, int, char[], int, int) + * Implementation has been entirely copied from this method except for array lengthes + * which were obviously replaced with calls to {@link String#length()} and + * for array direct access which were replaced with calls to {@link String#charAt(int)}. + * + * @param pattern the given pattern + * @param patternStart the start index of the pattern, inclusive + * @param patternEnd the end index of the pattern, exclusive + * @param name the given name + * @param nameStart the start index of the name, inclusive + * @param nameEnd the end index of the name, exclusive + * @return true if a sub-pattern matches the subpart of the given name, false otherwise + * + */ +public static final boolean camelCaseMatch(String pattern, int patternStart, int patternEnd, String name, int nameStart, int nameEnd) { + if (name == null) + return false; // null name cannot match + if (pattern == null) + return true; // null pattern is equivalent to '*' + if (patternEnd < 0) patternEnd = pattern.length(); + if (nameEnd < 0) nameEnd = name.length(); + + if (patternEnd <= patternStart) return nameEnd <= nameStart; + if (nameEnd <= nameStart) return false; + // check first pattern char + if (name.charAt(nameStart) != pattern.charAt(patternStart)) { + // first char must strictly match (upper/lower) + return false; + } + + char patternChar, nameChar; + int iPattern = patternStart; + int iName = nameStart; + + // Main loop is on pattern characters + while (true) { + + iPattern++; + iName++; + + if (iPattern == patternEnd) { + // We have exhausted pattern, so it's a match + return true; + } + + if (iName == nameEnd){ + // We have exhausted name (and not pattern), so it's not a match + return false; + } + + // For as long as we're exactly matching, bring it on (even if it's a lower case character) + if ((patternChar = pattern.charAt(iPattern)) == name.charAt(iName)) { + continue; + } + + // If characters are not equals, then it's not a match if patternChar is lowercase + if (patternChar < ScannerHelper.MAX_OBVIOUS) { + if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[patternChar] & ScannerHelper.C_UPPER_LETTER) == 0) { + return false; + } + } + else if (Character.isJavaIdentifierPart(patternChar) && !Character.isUpperCase(patternChar)) { + return false; + } + + // patternChar is uppercase, so let's find the next uppercase in name + while (true) { + if (iName == nameEnd){ + // We have exhausted name (and not pattern), so it's not a match + return false; + } + + nameChar = name.charAt(iName); + + if (nameChar < ScannerHelper.MAX_OBVIOUS) { + if ((ScannerHelper.OBVIOUS_IDENT_CHAR_NATURES[nameChar] & (ScannerHelper.C_LOWER_LETTER | ScannerHelper.C_SPECIAL | ScannerHelper.C_DIGIT)) != 0) { + // nameChar is lowercase + iName++; + // nameChar is uppercase... + } else if (patternChar != nameChar) { + //.. and it does not match patternChar, so it's not a match + return false; + } else { + //.. and it matched patternChar. Back to the big loop + break; + } + } + else if (Character.isJavaIdentifierPart(nameChar) && !Character.isUpperCase(nameChar)) { + // nameChar is lowercase + iName++; + // nameChar is uppercase... + } else if (patternChar != nameChar) { + //.. and it does not match patternChar, so it's not a match + return false; + } else { + //.. and it matched patternChar. Back to the big loop + break; + } + } + // At this point, either name has been exhausted, or it is at an uppercase letter. + // Since pattern is also at an uppercase letter + } +} + +/** + * Returns a search pattern that combines the given two patterns into an + * "and" pattern. The search result will match both the left pattern and + * the right pattern. + * + * @param leftPattern the left pattern + * @param rightPattern the right pattern + * @return an "and" pattern + */ +public static SearchPattern createAndPattern(SearchPattern leftPattern, SearchPattern rightPattern) { + return MatchLocator.createAndPattern(leftPattern, rightPattern); +} + +/** + * Field pattern are formed by [declaringType.]name[ type] + * e.g. java.lang.String.serialVersionUID long + * field* + */ +private static SearchPattern createFieldPattern(String patternString, int limitTo, int matchRule,boolean isVar) { + + Scanner scanner = new Scanner(false /*comment*/, true /*whitespace*/, false /*nls*/, ClassFileConstants.JDK1_3/*sourceLevel*/, null /*taskTags*/, null/*taskPriorities*/, true/*taskCaseSensitive*/); + scanner.setSource(patternString.toCharArray()); + final int InsideDeclaringPart = 1; + final int InsideType = 2; + int lastToken = -1; + + String declaringType = null, fieldName = null; + String type = null; + int mode = InsideDeclaringPart; + int token; + try { + token = scanner.getNextToken(); + } catch (InvalidInputException e) { + return null; + } + while (token != TerminalTokens.TokenNameEOF) { + switch(mode) { + // read declaring type and fieldName + case InsideDeclaringPart : + switch (token) { + case TerminalTokens.TokenNameDOT: + if (declaringType == null) { + if (fieldName == null) return null; + declaringType = fieldName; + } else { + String tokenSource = scanner.getCurrentTokenString(); + declaringType += tokenSource + fieldName; + } + fieldName = null; + break; + case TerminalTokens.TokenNameWHITESPACE: + if (!(TerminalTokens.TokenNameWHITESPACE == lastToken || TerminalTokens.TokenNameDOT == lastToken)) + mode = InsideType; + break; + default: // all other tokens are considered identifiers (see bug 21763 Problem in JavaScript search [search]) + if (fieldName == null) + fieldName = scanner.getCurrentTokenString(); + else + fieldName += scanner.getCurrentTokenString(); + } + break; + // read type + case InsideType: + switch (token) { + case TerminalTokens.TokenNameWHITESPACE: + break; + default: // all other tokens are considered identifiers (see bug 21763 Problem in JavaScript search [search]) + if (type == null) + type = scanner.getCurrentTokenString(); + else + type += scanner.getCurrentTokenString(); + } + break; + } + lastToken = token; + try { + token = scanner.getNextToken(); + } catch (InvalidInputException e) { + return null; + } + } + if (fieldName == null) return null; + + char[] fieldNameChars = fieldName.toCharArray(); + if (fieldNameChars.length == 1 && fieldNameChars[0] == '*') fieldNameChars = null; + + char[] declaringTypeQualification = null; + char[] declaringTypeSimpleName = null; + char[] typeQualification = null; + char[] typeSimpleName = null; + + // extract declaring type infos + if (declaringType != null) { + char[] declaringTypePart = declaringType.toCharArray(); + int lastDotPosition = CharOperation.lastIndexOf('.', declaringTypePart); + if (lastDotPosition >= 0) { + declaringTypeQualification = CharOperation.subarray(declaringTypePart, 0, lastDotPosition); + if (declaringTypeQualification.length == 1 && declaringTypeQualification[0] == '*') + declaringTypeQualification = null; + declaringTypeSimpleName = CharOperation.subarray(declaringTypePart, lastDotPosition+1, declaringTypePart.length); + } else { + declaringTypeSimpleName = declaringTypePart; + } + if (declaringTypeSimpleName.length == 1 && declaringTypeSimpleName[0] == '*') { + declaringTypeSimpleName = null; + } + } + // extract type infos + if (type != null) { + char[] typePart = type.toCharArray(); + int lastDotPosition = CharOperation.lastIndexOf('.', typePart); + if (lastDotPosition >= 0) { + typeQualification = CharOperation.subarray(typePart, 0, lastDotPosition); + if (typeQualification.length == 1 && typeQualification[0] == '*') { + typeQualification = null; + } else { + // prefix with a '*' as the full qualification could be bigger (because of an import) + typeQualification = CharOperation.concat(IIndexConstants.ONE_STAR, typeQualification); + } + typeSimpleName = CharOperation.subarray(typePart, lastDotPosition+1, typePart.length); + } else { + typeSimpleName = typePart; + } + if (typeSimpleName.length == 1 && typeSimpleName[0] == '*') + typeSimpleName = null; + } + // Create field pattern + boolean findDeclarations = false; + boolean readAccess = false; + boolean writeAccess = false; + switch (limitTo) { + case IJavaScriptSearchConstants.DECLARATIONS : + findDeclarations = true; + break; + case IJavaScriptSearchConstants.REFERENCES : + case IJavaScriptSearchConstants.READ_ACCESSES : + readAccess = true; + break; + case IJavaScriptSearchConstants.WRITE_ACCESSES : + writeAccess = true; + break; + case IJavaScriptSearchConstants.ALL_OCCURRENCES : + findDeclarations = true; + readAccess = true; + writeAccess = true; + break; + } + return new FieldPattern( + findDeclarations, + readAccess, + writeAccess, + isVar, + fieldNameChars, + declaringTypeQualification, + declaringTypeSimpleName, + typeQualification, + typeSimpleName, + matchRule,null); +} + +/** + * Method pattern are formed by:
+ * [declaringType '.'] ['<' typeArguments '>'] selector ['(' parameterTypes ')'] [returnType] + *
e.g.
    + *
  • java.lang.Runnable.run() void
  • + *
  • main(*)
  • + *
  • <String>toArray(String[])
  • + *
+ * Constructor pattern are formed by:
+ * [declaringQualification '.'] ['<' typeArguments '>'] type ['(' parameterTypes ')'] + *
e.g.
    + *
  • java.lang.Object()
  • + *
  • Main(*)
  • + *
  • <Exception>Sample(Exception)
  • + *
+ * Type arguments have the same pattern that for type patterns + * @see #createTypePattern(String,int,int,char) + */ +private static SearchPattern createMethodOrConstructorPattern(String patternString, int limitTo, int matchRule, boolean isConstructor, boolean isFunction) { + + Scanner scanner = new Scanner(false /*comment*/, true /*whitespace*/, false /*nls*/, ClassFileConstants.JDK1_3/*sourceLevel*/, null /*taskTags*/, null/*taskPriorities*/, true/*taskCaseSensitive*/); + scanner.setSource(patternString.toCharArray()); + final int InsideSelector = 1; + final int InsideTypeArguments = 2; + final int InsideParameter = 3; + final int InsideReturnType = 4; + int lastToken = -1; + + String declaringType = null, selector = null, parameterType = null; + String[] parameterTypes = null; + String typeArgumentsString = null; + int parameterCount = -1; + String returnType = null; + boolean foundClosingParenthesis = false; + int mode = InsideSelector; + int token, argCount = 0; + try { + token = scanner.getNextToken(); + } catch (InvalidInputException e) { + return null; + } + while (token != TerminalTokens.TokenNameEOF) { + switch(mode) { + // read declaring type and selector + case InsideSelector : + if (argCount == 0) { + switch (token) { + case TerminalTokens.TokenNameLESS: + argCount++; + if (selector == null || lastToken == TerminalTokens.TokenNameDOT) { + if (typeArgumentsString != null) return null; // invalid syntax + typeArgumentsString = scanner.getCurrentTokenString(); + mode = InsideTypeArguments; + break; + } + if (declaringType == null) { + declaringType = selector; + } else { + declaringType += '.' + selector; + } + declaringType += scanner.getCurrentTokenString(); + selector = null; + break; + case TerminalTokens.TokenNameDOT: + if (typeArgumentsString != null) return null; // invalid syntax + if (declaringType == null) { + if (selector == null) return null; // invalid syntax + declaringType = selector; + } else if (selector != null) { + declaringType += scanner.getCurrentTokenString() + selector; + } + selector = null; + break; + case TerminalTokens.TokenNameLPAREN: + parameterTypes = new String[5]; + parameterCount = 0; + mode = InsideParameter; + break; + case TerminalTokens.TokenNameWHITESPACE: + switch (lastToken) { + case TerminalTokens.TokenNameWHITESPACE: + case TerminalTokens.TokenNameDOT: + case TerminalTokens.TokenNameGREATER: + case TerminalTokens.TokenNameRIGHT_SHIFT: + case TerminalTokens.TokenNameUNSIGNED_RIGHT_SHIFT: + break; + default: + mode = InsideReturnType; + break; + } + break; + default: // all other tokens are considered identifiers (see bug 21763 Problem in JavaScript search [search]) + if (selector == null) + selector = scanner.getCurrentTokenString(); + else + selector += scanner.getCurrentTokenString(); + break; + } + } else { + if (declaringType == null) return null; // invalid syntax + switch (token) { + case TerminalTokens.TokenNameGREATER: + case TerminalTokens.TokenNameRIGHT_SHIFT: + case TerminalTokens.TokenNameUNSIGNED_RIGHT_SHIFT: + argCount--; + break; + case TerminalTokens.TokenNameLESS: + argCount++; + break; + } + declaringType += scanner.getCurrentTokenString(); + } + break; + // read type arguments + case InsideTypeArguments: + if (typeArgumentsString == null) return null; // invalid syntax + typeArgumentsString += scanner.getCurrentTokenString(); + switch (token) { + case TerminalTokens.TokenNameGREATER: + case TerminalTokens.TokenNameRIGHT_SHIFT: + case TerminalTokens.TokenNameUNSIGNED_RIGHT_SHIFT: + argCount--; + if (argCount == 0) { + mode = InsideSelector; + } + break; + case TerminalTokens.TokenNameLESS: + argCount++; + break; + } + break; + // read parameter types + case InsideParameter : + if (argCount == 0) { + switch (token) { + case TerminalTokens.TokenNameWHITESPACE: + break; + case TerminalTokens.TokenNameCOMMA: + if (parameterType == null) return null; + if (parameterTypes != null) { + if (parameterTypes.length == parameterCount) + System.arraycopy(parameterTypes, 0, parameterTypes = new String[parameterCount*2], 0, parameterCount); + parameterTypes[parameterCount++] = parameterType; + } + parameterType = null; + break; + case TerminalTokens.TokenNameRPAREN: + foundClosingParenthesis = true; + if (parameterType != null && parameterTypes != null) { + if (parameterTypes.length == parameterCount) + System.arraycopy(parameterTypes, 0, parameterTypes = new String[parameterCount*2], 0, parameterCount); + parameterTypes[parameterCount++] = parameterType; + } + mode = isConstructor ? InsideTypeArguments : InsideReturnType; + break; + case TerminalTokens.TokenNameLESS: + argCount++; + if (parameterType == null) return null; // invalid syntax + //$FALL-THROUGH$ next case to add token + default: // all other tokens are considered identifiers (see bug 21763 Problem in JavaScript search [search]) + if (parameterType == null) + parameterType = scanner.getCurrentTokenString(); + else + parameterType += scanner.getCurrentTokenString(); + } + } else { + if (parameterType == null) return null; // invalid syntax + switch (token) { + case TerminalTokens.TokenNameGREATER: + case TerminalTokens.TokenNameRIGHT_SHIFT: + case TerminalTokens.TokenNameUNSIGNED_RIGHT_SHIFT: + argCount--; + break; + case TerminalTokens.TokenNameLESS: + argCount++; + break; + } + parameterType += scanner.getCurrentTokenString(); + } + break; + // read return type + case InsideReturnType: + if (argCount == 0) { + switch (token) { + case TerminalTokens.TokenNameWHITESPACE: + break; + case TerminalTokens.TokenNameLPAREN: + parameterTypes = new String[5]; + parameterCount = 0; + mode = InsideParameter; + break; + case TerminalTokens.TokenNameLESS: + argCount++; + if (returnType == null) return null; // invalid syntax + //$FALL-THROUGH$ next case to add token + default: // all other tokens are considered identifiers (see bug 21763 Problem in JavaScript search [search]) + if (returnType == null) + returnType = scanner.getCurrentTokenString(); + else + returnType += scanner.getCurrentTokenString(); + } + } else { + if (returnType == null) return null; // invalid syntax + switch (token) { + case TerminalTokens.TokenNameGREATER: + case TerminalTokens.TokenNameRIGHT_SHIFT: + case TerminalTokens.TokenNameUNSIGNED_RIGHT_SHIFT: + argCount--; + break; + case TerminalTokens.TokenNameLESS: + argCount++; + break; + } + returnType += scanner.getCurrentTokenString(); + } + break; + } + lastToken = token; + try { + token = scanner.getNextToken(); + } catch (InvalidInputException e) { + return null; + } + } + // parenthesis mismatch + if (parameterCount>0 && !foundClosingParenthesis) return null; + // type arguments mismatch + if (argCount > 0) return null; + + char[] selectorChars = null; + if (isConstructor) { + // retrieve type for constructor patterns + if (declaringType == null) + declaringType = selector; + else if (selector != null) + declaringType += '.' + selector; + } else { + // get selector chars + if (selector == null) return null; + selectorChars = selector.toCharArray(); + if (selectorChars.length == 1 && selectorChars[0] == '*') + selectorChars = null; + } + + char[] declaringTypeQualification = null, declaringTypeSimpleName = null; + char[] returnTypeQualification = null, returnTypeSimpleName = null; + char[][] parameterTypeQualifications = null, parameterTypeSimpleNames = null; + // Signatures + String[] parameterTypeSignatures = null; + + // extract declaring type infos + if (declaringType != null) { + // get declaring type part and signature + char[] declaringTypePart = null; + try { + declaringTypePart = declaringType.toCharArray(); + } + catch (IllegalArgumentException iae) { + // declaring type is invalid + return null; + } + int lastDotPosition = CharOperation.lastIndexOf('.', declaringTypePart); + if (lastDotPosition >= 0) { + declaringTypeQualification = CharOperation.subarray(declaringTypePart, 0, lastDotPosition); + if (declaringTypeQualification.length == 1 && declaringTypeQualification[0] == '*') + declaringTypeQualification = null; + declaringTypeSimpleName = CharOperation.subarray(declaringTypePart, lastDotPosition+1, declaringTypePart.length); + } else { + declaringTypeSimpleName = declaringTypePart; + } + if (declaringTypeSimpleName.length == 1 && declaringTypeSimpleName[0] == '*') + declaringTypeSimpleName = null; + } + // extract parameter types infos + if (parameterCount >= 0) { + parameterTypeQualifications = new char[parameterCount][]; + parameterTypeSimpleNames = new char[parameterCount][]; + parameterTypeSignatures = new String[parameterCount]; + for (int i = 0; i < parameterCount; i++) { + // get parameter type part and signature + char[] parameterTypePart = null; + try { + if (parameterTypes != null) { + parameterTypeSignatures[i] = Signature.createTypeSignature(parameterTypes[i], false); + parameterTypePart = parameterTypes[i].toCharArray(); + } + } + catch (IllegalArgumentException iae) { + // string is not a valid type syntax + return null; + } + int lastDotPosition = parameterTypePart==null ? -1 : CharOperation.lastIndexOf('.', parameterTypePart); + if (parameterTypePart != null && lastDotPosition >= 0) { + parameterTypeQualifications[i] = CharOperation.subarray(parameterTypePart, 0, lastDotPosition); + if (parameterTypeQualifications[i].length == 1 && parameterTypeQualifications[i][0] == '*') { + parameterTypeQualifications[i] = null; + } else { + // prefix with a '*' as the full qualification could be bigger (because of an import) + parameterTypeQualifications[i] = CharOperation.concat(IIndexConstants.ONE_STAR, parameterTypeQualifications[i]); + } + parameterTypeSimpleNames[i] = CharOperation.subarray(parameterTypePart, lastDotPosition+1, parameterTypePart.length); + } else { + parameterTypeQualifications[i] = null; + parameterTypeSimpleNames[i] = parameterTypePart; + } + if (parameterTypeSimpleNames[i].length == 1 && parameterTypeSimpleNames[i][0] == '*') + parameterTypeSimpleNames[i] = null; + } + } + // extract return type infos + if (returnType != null) { + // get return type part and signature + char[] returnTypePart = null; + try { + returnTypePart = returnType.toCharArray(); + } + catch (IllegalArgumentException iae) { + // declaring type is invalid + return null; + } + int lastDotPosition = CharOperation.lastIndexOf('.', returnTypePart); + if (lastDotPosition >= 0) { + returnTypeQualification = CharOperation.subarray(returnTypePart, 0, lastDotPosition); + if (returnTypeQualification.length == 1 && returnTypeQualification[0] == '*') { + returnTypeQualification = null; + } else { + // because of an import + returnTypeQualification = CharOperation.concat(IIndexConstants.ONE_STAR, returnTypeQualification); + } + returnTypeSimpleName = CharOperation.subarray(returnTypePart, lastDotPosition+1, returnTypePart.length); + } else { + returnTypeSimpleName = returnTypePart; + } + if (returnTypeSimpleName.length == 1 && returnTypeSimpleName[0] == '*') + returnTypeSimpleName = null; + } + // Create method/constructor pattern + boolean findDeclarations = true; + boolean findReferences = true; + switch (limitTo) { + case IJavaScriptSearchConstants.DECLARATIONS : + findReferences = false; + break; + case IJavaScriptSearchConstants.REFERENCES : + findDeclarations = false; + break; + case IJavaScriptSearchConstants.ALL_OCCURRENCES : + break; + } + if (isConstructor) { + return new ConstructorPattern(patternString.toCharArray(), matchRule, findDeclarations, findReferences); + } else { + return new MethodPattern( + findDeclarations, + findReferences, + isFunction, + selectorChars, + parameterTypeQualifications, + parameterTypeSimpleNames, + returnTypeQualification, + returnTypeSimpleName, + declaringTypeQualification, + declaringTypeSimpleName, + matchRule); + } +} + +/** + * Returns a search pattern that combines the given two patterns into an + * "or" pattern. The search result will match either the left pattern or the + * right pattern. + * + * @param leftPattern the left pattern + * @param rightPattern the right pattern + * @return an "or" pattern + */ +public static SearchPattern createOrPattern(SearchPattern leftPattern, SearchPattern rightPattern) { + return new OrPattern(leftPattern, rightPattern); +} + +private static SearchPattern createPackagePattern(String patternString, int limitTo, int matchRule) { + switch (limitTo) { + case IJavaScriptSearchConstants.DECLARATIONS : + return new PackageDeclarationPattern(patternString.toCharArray(), matchRule); + case IJavaScriptSearchConstants.REFERENCES : + return new PackageReferencePattern(patternString.toCharArray(), matchRule); + case IJavaScriptSearchConstants.ALL_OCCURRENCES : + return new OrPattern( + new PackageDeclarationPattern(patternString.toCharArray(), matchRule), + new PackageReferencePattern(patternString.toCharArray(), matchRule) + ); + } + return null; +} + +/** + * Returns a search pattern based on a given string pattern. The string patterns support '*' wild-cards. + * The remaining parameters are used to narrow down the type of expected results. + * + *
+ * Examples: + *
    + *
  • search for case insensitive references to Object: + * createSearchPattern("Object", TYPE, REFERENCES, false);
  • + *
  • search for case sensitive references to exact Object() constructor: + * createSearchPattern("java.lang.Object()", CONSTRUCTOR, REFERENCES, true);
  • + *
  • search for implementers of java.lang.Runnable: + * createSearchPattern("java.lang.Runnable", TYPE, IMPLEMENTORS, true);
  • + *
+ * @param stringPattern the given pattern + * @param searchFor determines the nature of the searched elements + *
    + *
  • {@link IJavaScriptSearchConstants#CLASS}: only look for classes
  • + *
  • {@link IJavaScriptSearchConstants#INTERFACE}: only look for interfaces
  • + *
  • {@link IJavaScriptSearchConstants#ENUM}: only look for enumeration
  • + *
  • {@link IJavaScriptSearchConstants#ANNOTATION_TYPE}: only look for annotation type
  • + *
  • {@link IJavaScriptSearchConstants#CLASS_AND_ENUM}: only look for classes and enumerations
  • + *
  • {@link IJavaScriptSearchConstants#CLASS_AND_INTERFACE}: only look for classes and interfaces
  • + *
  • {@link IJavaScriptSearchConstants#TYPE}: look for all types (ie. classes, interfaces, enum and annotation types)
  • + *
  • {@link IJavaScriptSearchConstants#FIELD}: look for fields
  • + *
  • {@link IJavaScriptSearchConstants#METHOD}: look for methods
  • + *
  • {@link IJavaScriptSearchConstants#CONSTRUCTOR}: look for constructors
  • + *
  • {@link IJavaScriptSearchConstants#PACKAGE}: look for packages
  • + *
+ * @param limitTo determines the nature of the expected matches + *
    + *
  • {@link IJavaScriptSearchConstants#DECLARATIONS}: will search declarations matching + * with the corresponding element. In case the element is a method, declarations of matching + * methods in subtypes will also be found, allowing to find declarations of abstract methods, etc.
    + * Note that additional flags {@link IJavaScriptSearchConstants#IGNORE_DECLARING_TYPE} and + * {@link IJavaScriptSearchConstants#IGNORE_RETURN_TYPE} are ignored for string patterns. + * This is due to the fact that client may omit to define them in string pattern to have same behavior. + *
  • + *
  • {@link IJavaScriptSearchConstants#REFERENCES}: will search references to the given element.
  • + *
  • {@link IJavaScriptSearchConstants#ALL_OCCURRENCES}: will search for either declarations or + * references as specified above. + *
  • + *
  • {@link IJavaScriptSearchConstants#IMPLEMENTORS}: for types, will find all types + * which directly implement/extend a given interface. + * Note that types may be only classes or only interfaces if {@link IJavaScriptSearchConstants#CLASS } or + * {@link IJavaScriptSearchConstants#INTERFACE} is respectively used instead of {@link IJavaScriptSearchConstants#TYPE}. + *
  • + *
+ * @param matchRule one of {@link #R_EXACT_MATCH}, {@link #R_PREFIX_MATCH}, {@link #R_PATTERN_MATCH}, + * {@link #R_REGEXP_MATCH}, {@link #R_CAMELCASE_MATCH} combined with one of following values: + * {@link #R_CASE_SENSITIVE}, {@link #R_ERASURE_MATCH} or {@link #R_EQUIVALENT_MATCH}. + * e.g. {@link #R_EXACT_MATCH} | {@link #R_CASE_SENSITIVE} if an exact and case sensitive match is requested, + * {@link #R_PREFIX_MATCH} if a prefix non case sensitive match is requested or {@link #R_EXACT_MATCH} | {@link #R_ERASURE_MATCH} + * if a non case sensitive and erasure match is requested.
+ * Note that {@link #R_ERASURE_MATCH} or {@link #R_EQUIVALENT_MATCH} have no effect + * on non-generic types/methods search.
+ * Note also that default behavior for generic types/methods search is to find exact matches. + * @return a search pattern on the given string pattern, or null if the string pattern is ill-formed + */ +public static SearchPattern createPattern(String stringPattern, int searchFor, int limitTo, int matchRule) { + if (stringPattern == null || stringPattern.length() == 0) return null; + + if ((matchRule = validateMatchRule(stringPattern, matchRule)) == -1) { + return null; + } + + // Ignore additional nature flags + limitTo &= ~(IJavaScriptSearchConstants.IGNORE_DECLARING_TYPE+IJavaScriptSearchConstants.IGNORE_RETURN_TYPE); + + switch (searchFor) { + case IJavaScriptSearchConstants.CLASS: + return createTypePattern(stringPattern, limitTo, matchRule, IIndexConstants.CLASS_SUFFIX); + case IJavaScriptSearchConstants.TYPE: + return createTypePattern(stringPattern, limitTo, matchRule, IIndexConstants.TYPE_SUFFIX); + case IJavaScriptSearchConstants.FUNCTION: + return createMethodOrConstructorPattern(stringPattern, limitTo, matchRule, false/*not a constructor*/,true); + case IJavaScriptSearchConstants.METHOD: + return createMethodOrConstructorPattern(stringPattern, limitTo, matchRule, false/*not a constructor*/,false); + case IJavaScriptSearchConstants.CONSTRUCTOR: + return createMethodOrConstructorPattern(stringPattern, limitTo, matchRule, true/*constructor*/,false); + case IJavaScriptSearchConstants.FIELD: + return createFieldPattern(stringPattern, limitTo, matchRule,false); + case IJavaScriptSearchConstants.VAR: + return createFieldPattern(stringPattern, limitTo, matchRule,true); + case IJavaScriptSearchConstants.PACKAGE: + return createPackagePattern(stringPattern, limitTo, matchRule); + } + return null; +} + +/** + * Returns a search pattern based on a given JavaScript element. + * The pattern is used to trigger the appropriate search. + *
+ * Note that for generic searches, the returned pattern consider {@link #R_ERASURE_MATCH} matches. + * If other kind of generic matches (ie. {@link #R_EXACT_MATCH} or {@link #R_EQUIVALENT_MATCH}) + * are expected, {@link #createPattern(IJavaScriptElement, int, int)} method need to be used instead with + * the explicit match rule specified. + *
+ * The pattern can be parameterized as follows: + * + * @param element the JavaScript element the search pattern is based on + * @param limitTo determines the nature of the expected matches + *
    + *
  • {@link IJavaScriptSearchConstants#DECLARATIONS}: will search declarations matching + * with the corresponding element. In case the element is a method, declarations of matching + * methods in subtypes will also be found, allowing to find declarations of abstract methods, etc. + * Some additional flags may be specified while searching declaration: + *
      + *
    • {@link IJavaScriptSearchConstants#IGNORE_DECLARING_TYPE}: declaring type will be ignored + * during the search.
      + * For example using following test case: + *
      + *                  class A { A method() { return null; } }
      + *                  class B extends A { B method() { return null; } }
      + *                  class C { A method() { return null; } }
      + *					
      + * search for method declaration with this flag + * will return 2 matches: in A and in C + *
    • + *
    • {@link IJavaScriptSearchConstants#IGNORE_RETURN_TYPE}: return type will be ignored + * during the search.
      + * Using same example, search for method declaration with this flag + * will return 2 matches: in A and in B. + *
    • + *
    + * Note that these two flags may be combined and both declaring and return types can be ignored + * during the search. Then, using same example, search for method declaration + * with these 2 flags will return 3 matches: in A, in B and in C + *
  • + *
  • {@link IJavaScriptSearchConstants#REFERENCES}: will search references to the given element.
  • + *
  • {@link IJavaScriptSearchConstants#ALL_OCCURRENCES}: will search for either declarations or + * references as specified above. + *
  • + *
  • {@link IJavaScriptSearchConstants#IMPLEMENTORS}: for types, will find all types + * which directly implement/extend a given interface. + *
  • + *
+ * @return a search pattern for a JavaScript element or null if the given element is ill-formed + */ +public static SearchPattern createPattern(IJavaScriptElement element, int limitTo) { + return createPattern(element, limitTo, R_EXACT_MATCH | R_CASE_SENSITIVE | R_ERASURE_MATCH); +} + +/** + * Returns a search pattern based on a given JavaScript element. + * The pattern is used to trigger the appropriate search, and can be parameterized as follows: + * + * @param element the JavaScript element the search pattern is based on + * @param limitTo determines the nature of the expected matches + *
    + *
  • {@link IJavaScriptSearchConstants#DECLARATIONS}: will search declarations matching + * with the corresponding element. In case the element is a method, declarations of matching + * methods in subtypes will also be found, allowing to find declarations of abstract methods, etc. + * Some additional flags may be specified while searching declaration: + *
      + *
    • {@link IJavaScriptSearchConstants#IGNORE_DECLARING_TYPE}: declaring type will be ignored + * during the search.
      + * For example using following test case: + *
      + *                  class A { A method() { return null; } }
      + *                  class B extends A { B method() { return null; } }
      + *                  class C { A method() { return null; } }
      + *					
      + * search for method declaration with this flag + * will return 2 matches: in A and in C + *
    • + *
    • {@link IJavaScriptSearchConstants#IGNORE_RETURN_TYPE}: return type will be ignored + * during the search.
      + * Using same example, search for method declaration with this flag + * will return 2 matches: in A and in B. + *
    • + *
    + * Note that these two flags may be combined and both declaring and return types can be ignored + * during the search. Then, using same example, search for method declaration + * with these 2 flags will return 3 matches: in A, in B and in C + *
  • + *
  • {@link IJavaScriptSearchConstants#REFERENCES}: will search references to the given element.
  • + *
  • {@link IJavaScriptSearchConstants#ALL_OCCURRENCES}: will search for either declarations or + * references as specified above. + *
  • + *
  • {@link IJavaScriptSearchConstants#IMPLEMENTORS}: for types, will find all types + * which directly implement/extend a given interface. + *
  • + *
+ * @param matchRule one of {@link #R_EXACT_MATCH}, {@link #R_PREFIX_MATCH}, {@link #R_PATTERN_MATCH}, + * {@link #R_REGEXP_MATCH}, {@link #R_CAMELCASE_MATCH} combined with one of following values: + * {@link #R_CASE_SENSITIVE}, {@link #R_ERASURE_MATCH} or {@link #R_EQUIVALENT_MATCH}. + * e.g. {@link #R_EXACT_MATCH} | {@link #R_CASE_SENSITIVE} if an exact and case sensitive match is requested, + * {@link #R_PREFIX_MATCH} if a prefix non case sensitive match is requested or {@link #R_EXACT_MATCH} |{@link #R_ERASURE_MATCH} + * if a non case sensitive and erasure match is requested.
+ * Note that {@link #R_ERASURE_MATCH} or {@link #R_EQUIVALENT_MATCH} have no effect on non-generic types + * or methods search.
+ * Note also that default behavior for generic types or methods is to find exact matches. + * @return a search pattern for a JavaScript element or null if the given element is ill-formed + * + */ +public static SearchPattern createPattern(IJavaScriptElement element, int limitTo, int matchRule) { + SearchPattern searchPattern = null; + int lastDot; + boolean ignoreDeclaringType = false; + boolean ignoreReturnType = false; + int maskedLimitTo = limitTo & ~(IJavaScriptSearchConstants.IGNORE_DECLARING_TYPE+IJavaScriptSearchConstants.IGNORE_RETURN_TYPE); + if (maskedLimitTo == IJavaScriptSearchConstants.DECLARATIONS || maskedLimitTo == IJavaScriptSearchConstants.ALL_OCCURRENCES) { + ignoreDeclaringType = (limitTo & IJavaScriptSearchConstants.IGNORE_DECLARING_TYPE) != 0; + ignoreReturnType = (limitTo & IJavaScriptSearchConstants.IGNORE_RETURN_TYPE) != 0; + } + char[] declaringSimpleName = null; + char[] declaringQualification = null; + boolean isVar=false; + boolean isFunction=false; + switch (element.getElementType()) { + case IJavaScriptElement.FIELD : + IField field = (IField) element; + IType declaringClassForField = field.getDeclaringType(); + isVar=(declaringClassForField==null); + if (!ignoreDeclaringType) { + if (declaringClassForField!=null) + { + declaringSimpleName = declaringClassForField.getElementName().toCharArray(); + declaringQualification= declaringClassForField.getPackageFragment().getElementName().toCharArray(); + char[][] enclosingNames = enclosingTypeNames(declaringClassForField); + if (enclosingNames.length > 0) { + declaringQualification = CharOperation.concat(declaringQualification, CharOperation.concatWith(enclosingNames, '.'), '.'); + } + } + } + char[] name = field.getElementName().toCharArray(); + char[] typeSimpleName = null; + char[] typeQualification = null; + String typeSignature = null; + if (!ignoreReturnType) { + try { + typeSignature = field.getTypeSignature(); + char[] signature = typeSignature.toCharArray(); + char[] typeErasure = Signature.toCharArray(signature); + if ((lastDot = CharOperation.lastIndexOf('.', typeErasure)) == -1) { + typeSimpleName = typeErasure; + } else { + typeSimpleName = CharOperation.subarray(typeErasure, lastDot + 1, typeErasure.length); + typeQualification = CharOperation.subarray(typeErasure, 0, lastDot); + if (!field.isBinary()) { + // prefix with a '*' as the full qualification could be bigger (because of an import) + typeQualification = CharOperation.concat(IIndexConstants.ONE_STAR, typeQualification); + } + } + } catch (JavaScriptModelException e) { + return null; + } + } + + // Create field pattern + boolean findDeclarations = false; + boolean readAccess = false; + boolean writeAccess = false; + switch (maskedLimitTo) { + case IJavaScriptSearchConstants.DECLARATIONS : + findDeclarations = true; + break; + case IJavaScriptSearchConstants.REFERENCES : + case IJavaScriptSearchConstants.READ_ACCESSES : + readAccess = true; + break; + case IJavaScriptSearchConstants.WRITE_ACCESSES : + writeAccess = true; + break; + case IJavaScriptSearchConstants.ALL_OCCURRENCES : + findDeclarations = true; + readAccess = true; + writeAccess = true; + break; + } + searchPattern = + new FieldPattern( + findDeclarations, + readAccess, + writeAccess, + isVar, + name, + declaringQualification, + declaringSimpleName, + typeQualification, + typeSimpleName, + matchRule,field); + break; + case IJavaScriptElement.IMPORT_DECLARATION : + String elementName = element.getElementName(); + lastDot = elementName.lastIndexOf('.'); + if (lastDot == -1) return null; // invalid import declaration + IImportDeclaration importDecl = (IImportDeclaration)element; + if (importDecl.isOnDemand()) { + searchPattern = createPackagePattern(elementName.substring(0, lastDot), maskedLimitTo, matchRule); + } else { + searchPattern = + createTypePattern( + elementName.substring(lastDot+1).toCharArray(), + elementName.substring(0, lastDot).toCharArray(), + null, + null, + null, + maskedLimitTo, + matchRule); + } + break; + case IJavaScriptElement.LOCAL_VARIABLE : + LocalVariable localVar = (LocalVariable) element; + boolean findVarDeclarations = false; + boolean findVarReadAccess = false; + boolean findVarWriteAccess = false; + switch (maskedLimitTo) { + case IJavaScriptSearchConstants.DECLARATIONS : + findVarDeclarations = true; + break; + case IJavaScriptSearchConstants.REFERENCES : + findVarReadAccess = true; + findVarWriteAccess = true; + break; + case IJavaScriptSearchConstants.READ_ACCESSES : + findVarReadAccess = true; + break; + case IJavaScriptSearchConstants.WRITE_ACCESSES : + findVarWriteAccess = true; + break; + case IJavaScriptSearchConstants.ALL_OCCURRENCES : + findVarDeclarations = true; + findVarReadAccess = true; + findVarWriteAccess = true; + break; + } + searchPattern = + new LocalVariablePattern( + findVarDeclarations, + findVarReadAccess, + findVarWriteAccess, + localVar, + matchRule); + break; + case IJavaScriptElement.METHOD : + IFunction method = (IFunction) element; + boolean isConstructor; + try { + isConstructor = method.isConstructor(); + } catch (JavaScriptModelException e) { + return null; + } + IType declaringClass = method.getDeclaringType(); + + if (declaringClass!=null) { + if (ignoreDeclaringType) { + if (isConstructor) + declaringSimpleName = declaringClass.getElementName().toCharArray(); + } else { + declaringSimpleName = declaringClass.getElementName().toCharArray(); + declaringQualification = declaringClass.getPackageFragment().getElementName().toCharArray(); + char[][] enclosingNames = enclosingTypeNames(declaringClass); + if (enclosingNames.length > 0) { + declaringQualification = CharOperation.concat( + declaringQualification, CharOperation.concatWith(enclosingNames, '.'), '.'); + } + } + } + else + isFunction=true; + char[] selector = method.getElementName().toCharArray(); + char[] returnSimpleName = null; + char[] returnQualification = null; + String returnSignature = null; + if (!ignoreReturnType) { + try { + returnSignature = method.getReturnType(); + char[] signature = returnSignature.toCharArray(); + char[] returnErasure = Signature.toCharArray(signature); + if ((lastDot = CharOperation.lastIndexOf('.', returnErasure)) == -1) { + returnSimpleName = returnErasure; + } else { + returnSimpleName = CharOperation.subarray(returnErasure, lastDot + 1, returnErasure.length); + returnQualification = CharOperation.subarray(returnErasure, 0, lastDot); + if (!method.isBinary()) { + // prefix with a '*' as the full qualification could be bigger (because of an import) + CharOperation.concat(IIndexConstants.ONE_STAR, returnQualification); + } + } + } catch (JavaScriptModelException e) { + return null; + } + } + String[] parameterTypes = method.getParameterTypes(); + int paramCount = parameterTypes.length; + char[][] parameterSimpleNames = new char[paramCount][]; + char[][] parameterQualifications = new char[paramCount][]; + String[] parameterSignatures = new String[paramCount]; + for (int i = 0; i < paramCount; i++) { + parameterSignatures[i] = parameterTypes[i]; + char[] signature = parameterSignatures[i].toCharArray(); + char[] paramErasure = Signature.toCharArray(signature); + if ((lastDot = CharOperation.lastIndexOf('.', paramErasure)) == -1) { + parameterSimpleNames[i] = paramErasure; + parameterQualifications[i] = null; + } else { + parameterSimpleNames[i] = CharOperation.subarray(paramErasure, lastDot + 1, paramErasure.length); + parameterQualifications[i] = CharOperation.subarray(paramErasure, 0, lastDot); + if (!method.isBinary()) { + // prefix with a '*' as the full qualification could be bigger (because of an import) + CharOperation.concat(IIndexConstants.ONE_STAR, parameterQualifications[i]); + } + } + } + + // Create method/constructor pattern + boolean findMethodDeclarations = true; + boolean findMethodReferences = true; + switch (maskedLimitTo) { + case IJavaScriptSearchConstants.DECLARATIONS : + findMethodReferences = false; + break; + case IJavaScriptSearchConstants.REFERENCES : + findMethodDeclarations = false; + break; + case IJavaScriptSearchConstants.ALL_OCCURRENCES : + break; + } + if (isConstructor) { + searchPattern = + new ConstructorPattern( + findMethodDeclarations, + findMethodReferences, + parameterQualifications, + parameterSimpleNames, + declaringSimpleName, + declaringQualification, + matchRule); + } else { + searchPattern = + new MethodPattern( + findMethodDeclarations, + findMethodReferences, + isFunction, + selector, + parameterQualifications, + parameterSimpleNames, + returnQualification, + returnSimpleName, + declaringQualification, + declaringSimpleName, + matchRule); + } + break; + case IJavaScriptElement.TYPE : + IType type = (IType)element; + searchPattern = createTypePattern( + type.getElementName().toCharArray(), + type.getPackageFragment().getElementName().toCharArray(), + ignoreDeclaringType ? null : enclosingTypeNames(type), + null, + type, + maskedLimitTo, + matchRule); + break; + case IJavaScriptElement.PACKAGE_FRAGMENT : + searchPattern = createPackagePattern(element.getElementName(), maskedLimitTo, matchRule); + break; + } + if (searchPattern != null) + MatchLocator.setFocus(searchPattern, element); + return searchPattern; +} + +private static SearchPattern createTypePattern(char[] simpleName, char[] packageName, char[][] enclosingTypeNames, String typeSignature, IType type, int limitTo, int matchRule) { + switch (limitTo) { + case IJavaScriptSearchConstants.DECLARATIONS : + return new TypeDeclarationPattern( + packageName, + simpleName, + enclosingTypeNames, + matchRule); + case IJavaScriptSearchConstants.REFERENCES : + if (type != null) { + return new TypeReferencePattern( + CharOperation.concatWith(packageName, enclosingTypeNames, '.'), + simpleName, + type, + matchRule); + } + return new TypeReferencePattern( + CharOperation.concatWith(packageName, enclosingTypeNames, '.'), + simpleName, + typeSignature, + matchRule); + case IJavaScriptSearchConstants.IMPLEMENTORS : + return new SuperTypeReferencePattern( + QualificationHelpers.createFullyQualifiedName(packageName, simpleName), + matchRule); + case IJavaScriptSearchConstants.ALL_OCCURRENCES : + return new OrPattern( + new TypeDeclarationPattern( + packageName, + simpleName, + enclosingTypeNames, + matchRule), + (type != null) + ? new TypeReferencePattern( + CharOperation.concatWith(packageName, enclosingTypeNames, '.'), + simpleName, + type, + matchRule) + : new TypeReferencePattern( + CharOperation.concatWith(packageName, enclosingTypeNames, '.'), + simpleName, + typeSignature, + matchRule) + ); + } + return null; +} +/** + * Type pattern are formed by [qualification '.']type [typeArguments]. + * e.g. java.lang.Object + * Runnable + * List<String> + */ +private static SearchPattern createTypePattern(String patternString, int limitTo, int matchRule, char indexSuffix) { + + Scanner scanner = new Scanner(false /*comment*/, true /*whitespace*/, false /*nls*/, ClassFileConstants.JDK1_3/*sourceLevel*/, null /*taskTags*/, null/*taskPriorities*/, true/*taskCaseSensitive*/); + scanner.setSource(patternString.toCharArray()); + String type = null; + int token; + try { + token = scanner.getNextToken(); + } catch (InvalidInputException e) { + return null; + } + int argCount = 0; + while (token != TerminalTokens.TokenNameEOF) { + if (argCount == 0) { + switch (token) { + case TerminalTokens.TokenNameWHITESPACE: + break; + case TerminalTokens.TokenNameLESS: + argCount++; + // fall through default case to add token to type + default: // all other tokens are considered identifiers (see bug 21763 Problem in JavaScript search [search]) + if (type == null) + type = scanner.getCurrentTokenString(); + else + type += scanner.getCurrentTokenString(); + } + } else { + switch (token) { + case TerminalTokens.TokenNameGREATER: + case TerminalTokens.TokenNameRIGHT_SHIFT: + case TerminalTokens.TokenNameUNSIGNED_RIGHT_SHIFT: + argCount--; + break; + case TerminalTokens.TokenNameLESS: + argCount++; + break; + } + if (type == null) return null; // invalid syntax + type += scanner.getCurrentTokenString(); + } + try { + token = scanner.getNextToken(); + } catch (InvalidInputException e) { + return null; + } + } + if (type == null) return null; + String typeSignature = null; + char[] qualificationChars = null, typeChars = null; + + // get type part and signature + char[] typePart = null; + try { + typeSignature = Signature.createTypeSignature(type, false); + typePart = type.toCharArray(); + } + catch (IllegalArgumentException iae) { + // string is not a valid type syntax + return null; + } + + // get qualification name + int lastDotPosition = CharOperation.lastIndexOf('.', typePart); + if (lastDotPosition >= 0) { + qualificationChars = CharOperation.subarray(typePart, 0, lastDotPosition); + if (qualificationChars.length == 1 && qualificationChars[0] == '*') + qualificationChars = null; + typeChars = CharOperation.subarray(typePart, lastDotPosition+1, typePart.length); + } else { + typeChars = typePart; + } + if (typeChars.length == 1 && typeChars[0] == '*') { + typeChars = null; + } + switch (limitTo) { + case IJavaScriptSearchConstants.DECLARATIONS : // cannot search for explicit member types + return new TypeDeclarationPattern(typePart, matchRule); + case IJavaScriptSearchConstants.REFERENCES : + return new TypeReferencePattern(qualificationChars, typeChars, typeSignature, matchRule); + case IJavaScriptSearchConstants.IMPLEMENTORS : + return new SuperTypeReferencePattern(QualificationHelpers.createFullyQualifiedName(qualificationChars, typeChars), matchRule); + case IJavaScriptSearchConstants.ALL_OCCURRENCES : + return new OrPattern( + new TypeDeclarationPattern(typePart, matchRule),// cannot search for explicit member types + new TypeReferencePattern(qualificationChars, typeChars, matchRule)); + } + return null; +} +/** + * Returns the enclosing type names of the given type. + */ +private static char[][] enclosingTypeNames(IType type) { + IJavaScriptElement parent = type.getParent(); + switch (parent.getElementType()) { + case IJavaScriptElement.CLASS_FILE: + // For a binary type, the parent is not the enclosing type, but the declaring type is. + // (see bug 20532 Declaration of member binary type not found) + IType declaringType = type.getDeclaringType(); + if (declaringType == null) return CharOperation.NO_CHAR_CHAR; + return CharOperation.arrayConcat( + enclosingTypeNames(declaringType), + declaringType.getElementName().toCharArray()); + case IJavaScriptElement.JAVASCRIPT_UNIT: + return CharOperation.NO_CHAR_CHAR; + case IJavaScriptElement.FIELD: + case IJavaScriptElement.INITIALIZER: + case IJavaScriptElement.METHOD: + IType declaringClass = ((IMember) parent).getDeclaringType(); + if (declaringClass!=null) + return CharOperation.arrayConcat( + enclosingTypeNames(declaringClass), + new char[][] {declaringClass.getElementName().toCharArray(), IIndexConstants.ONE_STAR}); + else + return CharOperation.NO_CHAR_CHAR; + case IJavaScriptElement.TYPE: + return CharOperation.arrayConcat( + enclosingTypeNames((IType)parent), + parent.getElementName().toCharArray()); + default: + return null; + } +} + +/** + * Decode the given index key in this pattern. The decoded index key is used by + * {@link #matchesDecodedKey(SearchPattern)} to find out if the corresponding index entry + * should be considered. + *

+ * This method should be re-implemented in subclasses that need to decode an index key. + *

+ * + * @param key the given index key + */ +public void decodeIndexKey(char[] key) { + // called from findIndexMatches(), override as necessary +} +/** + * Returns a blank pattern that can be used as a record to decode an index key. + *

+ * Implementors of this method should return a new search pattern that is going to be used + * to decode index keys. + *

+ * + * @return a new blank pattern + * @see #decodeIndexKey(char[]) + */ +public abstract SearchPattern getBlankPattern(); +/** + * Returns a key to find in relevant index categories, if null then all index entries are matched. + * The key will be matched according to some match rule. These potential matches + * will be further narrowed by the match locator, but precise match locating can be expensive, + * and index query should be as accurate as possible so as to eliminate obvious false hits. + *

+ * This method should be re-implemented in subclasses that need to narrow down the + * index query. + *

+ * + * @return an index key from this pattern, or null if all index entries are matched. + */ +public char[] getIndexKey() { + return null; // called from queryIn(), override as necessary +} +/** + * Returns an array of index categories to consider for this index query. + * These potential matches will be further narrowed by the match locator, but precise + * match locating can be expensive, and index query should be as accurate as possible + * so as to eliminate obvious false hits. + *

+ * This method should be re-implemented in subclasses that need to narrow down the + * index query. + *

+ * + * @return an array of index categories + */ +public char[][] getIndexCategories() { + return CharOperation.NO_CHAR_CHAR; // called from queryIn(), override as necessary +} +/** + * Returns the rule to apply for matching index keys. Can be exact match, prefix match, pattern match or regexp match. + * Rule can also be combined with a case sensitivity flag. + * + * @return one of R_EXACT_MATCH, R_PREFIX_MATCH, R_PATTERN_MATCH, R_REGEXP_MATCH combined with R_CASE_SENSITIVE, + * e.g. R_EXACT_MATCH | R_CASE_SENSITIVE if an exact and case sensitive match is requested, + * or R_PREFIX_MATCH if a prefix non case sensitive match is requested. + */ +public final int getMatchRule() { + return this.matchRule; +} +/** + * Returns whether this pattern matches the given pattern (representing a decoded index key). + *

+ * This method should be re-implemented in subclasses that need to narrow down the + * index query. + *

+ * + * @param decodedPattern a pattern representing a decoded index key + * @return whether this pattern matches the given pattern + */ +public boolean matchesDecodedKey(SearchPattern decodedPattern) { + return true; // called from findIndexMatches(), override as necessary if index key is encoded +} + +/** + * Returns whether the given name matches the given pattern. + *

+ * This method should be re-implemented in subclasses that need to define how + * a name matches a pattern. + *

+ * + * @param pattern the given pattern, or null to represent "*" + * @param name the given name + * @return whether the given name matches the given pattern + */ +public boolean matchesName(char[] pattern, char[] name) { + if (pattern == null) return true; // null is as if it was "*" + if (name != null) { + boolean isCaseSensitive = (this.matchRule & R_CASE_SENSITIVE) != 0; + boolean isCamelCase = (this.matchRule & R_CAMELCASE_MATCH) != 0; + int matchMode = this.matchRule & MODE_MASK; + boolean emptyPattern = pattern.length == 0; + if (matchMode == R_PREFIX_MATCH && emptyPattern) return true; + boolean sameLength = pattern.length == name.length; + boolean canBePrefix = name.length >= pattern.length; + boolean matchFirstChar = !isCaseSensitive || emptyPattern || (name.length > 0 && pattern[0] == name[0]); + if (isCamelCase && matchFirstChar && CharOperation.camelCaseMatch(pattern, name)) { + return true; + } + switch (matchMode) { + case R_EXACT_MATCH : + case R_FULL_MATCH : + if (!isCamelCase) { + if (sameLength && matchFirstChar) { + return CharOperation.equals(pattern, name, isCaseSensitive); + } + break; + } + //$FALL-THROUGH$ next case to match as prefix if camel case failed + case R_PREFIX_MATCH : + if (canBePrefix && matchFirstChar) { + return CharOperation.prefixEquals(pattern, name, isCaseSensitive); + } + break; + + case R_PATTERN_MATCH : + if (!isCaseSensitive) + pattern = CharOperation.toLowerCase(pattern); + return CharOperation.match(pattern, name, isCaseSensitive); + + case R_REGEXP_MATCH : { + int flags = 0; + if(!isCaseSensitive) { + flags = Pattern.CASE_INSENSITIVE; + } + return Pattern.compile(new String(pattern), flags).matcher(new String(name)).matches(); + } + } + } + return false; +} + +/** + *

Returns whether this pattern's prefix qualifier matches the other patterns qualified name. + * This pattern's qualifier must have a match rule of pattern match for a match to occur.

+ * + * @param thisQualifiedName this qualifier pattern to inspect + * @param otherQualifiedName other qualifier pattern to inspect + * @param isCaseSensitive whether this qualifier pattern is case sensitive + * @return whether this pattern's prefix qualifier matches the other patterns qualified name + */ +public static boolean matchesQualificationPattern(char[] thisQualifiedName, char[] otherQualifiedName, boolean isCaseSensitive) { + if (thisQualifiedName != null && isPatternMatch(String.valueOf(thisQualifiedName))) { + if (otherQualifiedName != null && otherQualifiedName.length > 0) { + if (!isCaseSensitive) + thisQualifiedName = CharOperation.toLowerCase(thisQualifiedName); + return CharOperation.match(thisQualifiedName, otherQualifiedName, isCaseSensitive); + } + } + return false; +} + +/** + * Validate compatibility between given string pattern and match rule. + *
+ * Optimized (ie. returned match rule is modified) combinations are: + *
    + *
  • {@link #R_PATTERN_MATCH} without any '*' or '?' in string pattern: + * pattern match bit is unset, + *
  • + *
  • {@link #R_PATTERN_MATCH} and {@link #R_PREFIX_MATCH} bits simultaneously set: + * prefix match bit is unset, + *
  • + *
  • {@link #R_PATTERN_MATCH} and {@link #R_CAMELCASE_MATCH} bits simultaneously set: + * camel case match bit is unset, + *
  • + *
  • {@link #R_CAMELCASE_MATCH} with invalid combination of uppercase and lowercase characters: + * camel case match bit is unset and replaced with prefix match pattern, + *
  • + *
  • {@link #R_CAMELCASE_MATCH} combined with {@link #R_PREFIX_MATCH} and {@link #R_CASE_SENSITIVE} + * bits is reduced to only {@link #R_CAMELCASE_MATCH} as Camel Case search is already prefix and case sensitive, + *
  • + *
+ *
+ * Rejected (ie. returned match rule -1) combinations are: + *
    + *
  • {@link #R_REGEXP_MATCH} with any other match mode bit set, + *
  • + *
+ * + * @param stringPattern The string pattern + * @param matchRule The match rule + * @return Optimized valid match rule or -1 if an incompatibility was detected. + * + */ +public static int validateMatchRule(String stringPattern, int matchRule) { + + // Verify Regexp match rule + if ((matchRule & R_REGEXP_MATCH) != 0) { + if ((matchRule & R_PATTERN_MATCH) != 0 || (matchRule & R_PREFIX_MATCH) != 0 || (matchRule & R_CAMELCASE_MATCH) != 0) { + return -1; + } + } + + // Verify Pattern match rule + int starIndex = stringPattern.indexOf('*'); + int questionIndex = stringPattern.indexOf('?'); + if (starIndex < 0 && questionIndex < 0) { + // reset pattern match bit if any + matchRule &= ~R_PATTERN_MATCH; + } else { + // force Pattern rule + matchRule |= R_PATTERN_MATCH; + } + if ((matchRule & R_PATTERN_MATCH) != 0) { + // remove Camel Case and Prefix match bits if any + matchRule &= ~R_CAMELCASE_MATCH; + matchRule &= ~R_PREFIX_MATCH; + } + + // Verify Camel Case match rule + if ((matchRule & R_CAMELCASE_MATCH) != 0) { + // Verify sting pattern validity + int length = stringPattern.length(); + boolean validCamelCase = true; + boolean uppercase = false; + for (int i=0; i=0) - name=name.substring(0,index); + return name.substring(0,index); return ""; } @@ -108,6 +108,16 @@ public String getSimpleTypeName() { return name; } +/** + * Returns the stored super type names. + * + * @return the stored super type names, or null. + * @since 1.2 + */ +public char[][] getSuperTypeNames() { + return null; +} + /** * Returns a javascript model type handle. * This handle may exist or not, but is not supposed to be null. diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/CompletionEngine.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/CompletionEngine.java index f0406b4e..ed9d51d9 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/CompletionEngine.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/CompletionEngine.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -26,10 +26,10 @@ import org.eclipse.wst.jsdt.core.IJavaScriptProject; import org.eclipse.wst.jsdt.core.IType; import org.eclipse.wst.jsdt.core.JavaScriptModelException; import org.eclipse.wst.jsdt.core.Signature; -import org.eclipse.wst.jsdt.core.UnimplementedException; import org.eclipse.wst.jsdt.core.compiler.CategorizedProblem; import org.eclipse.wst.jsdt.core.compiler.CharOperation; import org.eclipse.wst.jsdt.core.compiler.IProblem; +import org.eclipse.wst.jsdt.core.infer.IInferEngine; import org.eclipse.wst.jsdt.core.infer.InferredMethod; import org.eclipse.wst.jsdt.core.infer.InferredType; import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants; @@ -97,12 +97,9 @@ import org.eclipse.wst.jsdt.internal.compiler.ast.MessageSend; import org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration; import org.eclipse.wst.jsdt.internal.compiler.ast.OperatorExpression; import org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds; -import org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedTypeReference; import org.eclipse.wst.jsdt.internal.compiler.ast.ReturnStatement; import org.eclipse.wst.jsdt.internal.compiler.ast.SingleNameReference; -import org.eclipse.wst.jsdt.internal.compiler.ast.SingleTypeReference; import org.eclipse.wst.jsdt.internal.compiler.ast.SuperReference; -import org.eclipse.wst.jsdt.internal.compiler.ast.SwitchStatement; import org.eclipse.wst.jsdt.internal.compiler.ast.TryStatement; import org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.wst.jsdt.internal.compiler.ast.TypeReference; @@ -125,6 +122,7 @@ import org.eclipse.wst.jsdt.internal.compiler.lookup.FieldBinding; import org.eclipse.wst.jsdt.internal.compiler.lookup.FunctionTypeBinding; import org.eclipse.wst.jsdt.internal.compiler.lookup.ImportBinding; import org.eclipse.wst.jsdt.internal.compiler.lookup.InvocationSite; +import org.eclipse.wst.jsdt.internal.compiler.lookup.LocalFunctionBinding; import org.eclipse.wst.jsdt.internal.compiler.lookup.LocalVariableBinding; import org.eclipse.wst.jsdt.internal.compiler.lookup.LookupEnvironment; import org.eclipse.wst.jsdt.internal.compiler.lookup.MetatdataTypeBinding; @@ -161,6 +159,8 @@ import org.eclipse.wst.jsdt.internal.core.SourceMethod; import org.eclipse.wst.jsdt.internal.core.SourceMethodElementInfo; import org.eclipse.wst.jsdt.internal.core.SourceType; import org.eclipse.wst.jsdt.internal.core.SourceTypeElementInfo; +import org.eclipse.wst.jsdt.internal.core.search.indexing.IIndexConstants; +import org.eclipse.wst.jsdt.internal.core.util.QualificationHelpers; import org.eclipse.wst.jsdt.internal.oaametadata.ClassData; import org.eclipse.wst.jsdt.internal.oaametadata.Method; @@ -172,7 +172,7 @@ import org.eclipse.wst.jsdt.internal.oaametadata.Method; public final class CompletionEngine extends Engine implements ISearchRequestor, TypeConstants , TerminalTokens , RelevanceConstants, SuffixConstants { - + public class CompletionProblemFactory extends DefaultProblemFactory { private int lastErrorStart; @@ -386,12 +386,6 @@ public final class CompletionEngine HashtableOfObject knownPkgs = new HashtableOfObject(10); HashtableOfObject knownTypes = new HashtableOfObject(10); Scanner nameScanner; - - /** - *

Constructors accepted by {@link #acceptConstructor(int, char[], int, char[], char[][], char[][], String, AccessRestriction)} - * to be processed by {@link #acceptConstructors(Scope)}

- */ - private ObjectVector acceptedConstructors; static final char[] classField = "class".toCharArray(); //$NON-NLS-1$ static final char[] lengthField = "length".toCharArray(); //$NON-NLS-1$ @@ -479,15 +473,20 @@ public final class CompletionEngine int modifiers, AccessRestriction accessRestriction) { - if (this.options.checkDeprecation && (modifiers & ClassFileConstants.AccDeprecated) != 0) return; + if (this.options.checkDeprecation && (modifiers & ClassFileConstants.AccDeprecated) != 0) { + return; + } + + //ignore types with no simple name and anonymous types + if(simpleTypeName == null || + CharOperation.indexOf(IInferEngine.ANONYMOUS_PREFIX, simpleTypeName, false) == 0) { + return; + } if (this.options.checkVisibility) { if((modifiers & ClassFileConstants.AccPublic) == 0) { if((modifiers & ClassFileConstants.AccPrivate) != 0) return; - - //char[] currentPackage = CharOperation.concatWith(this.unitScope.getDefaultPackage().compoundName, '.'); - //if(!CharOperation.equals(packageName, currentPackage)) return; } } @@ -675,18 +674,49 @@ public final class CompletionEngine } /** - * @see org.eclipse.wst.jsdt.internal.codeassist.ISearchRequestor#acceptConstructor( - * int, char[], int, char[][], char[][], java.lang.String, org.eclipse.wst.jsdt.internal.compiler.env.AccessRestriction) + * @see org.eclipse.wst.jsdt.internal.codeassist.ISearchRequestor#acceptFunction(char[], char[][], char[][], char[], char[], char[], char[], int, java.lang.String) + */ + public void acceptFunction(char[] signature, + char[][] parameterFullyQualifiedTypeNames, + char[][] parameterNames, char[] returnQualification, + char[] returnSimpleName, char[] declaringQualification, + char[] declaringSimpleName, int modifiers, String path) { + + if(!this.requestor.isIgnored(CompletionProposal.METHOD_REF) && (this.assistNodeInJavadoc & CompletionOnJavadoc.ONLY_INLINE_TAG) == 0) { + + this.proposeFunction(signature, parameterFullyQualifiedTypeNames, parameterNames, + returnQualification, returnSimpleName, declaringQualification, declaringSimpleName, modifiers); + } + } + + /** + * @see org.eclipse.wst.jsdt.internal.codeassist.ISearchRequestor#acceptVariable(char[], char[], char[], char[], char[], int, java.lang.String) + */ + public void acceptVariable(char[] signature, + char[] typeQualification, + char[] typeSimpleName, char[] declaringQualification, + char[] declaringSimpleName, int modifiers, String path) { + + this.proposeField(signature, typeQualification, typeSimpleName, declaringQualification, declaringSimpleName, modifiers); + } + + /** + * @see org.eclipse.wst.jsdt.internal.codeassist.ISearchRequestor#acceptConstructor(int, char[], char[][], char[][], java.lang.String, org.eclipse.wst.jsdt.internal.compiler.env.AccessRestriction) */ public void acceptConstructor( int modifiers, char[] typeName, - int parameterCount, char[][] parameterTypes, char[][] parameterNames, String path, AccessRestriction accessRestriction) { + //ignore constructors with no type name and anonymous types + if(typeName == null || + CharOperation.indexOf(IInferEngine.ANONYMOUS_PREFIX, typeName, false) == 0) { + return; + } + int accessibility = IAccessRule.K_ACCESSIBLE; if(accessRestriction != null) { switch (accessRestriction.getProblemId()) { @@ -704,44 +734,17 @@ public final class CompletionEngine break; } } - - if(this.acceptedConstructors == null) { - this.acceptedConstructors = new ObjectVector(); - } - this.acceptedConstructors.add( - new AcceptedConstructor( - modifiers, - typeName, - parameterCount, - parameterTypes, - parameterNames, - accessibility)); - } - - /** - *

Creates proposals for all of the constructors accepted by - * {@link #acceptConstructor(int, char[], int, char[][], char[][], String, AccessRestriction)}.

- * - * @see #acceptConstructor(int, char[], int, char[][], char[][], String, AccessRestriction) - */ - private void acceptConstructors() { - int length; - if(this.acceptedConstructors != null && (length = this.acceptedConstructors.size()) > 0) { - for (int i = 0; i < length; i++) { - AcceptedConstructor acceptedConstructor = (AcceptedConstructor)this.acceptedConstructors.elementAt(i); - - //decide if constructor should be proposed based on visibility rules - boolean proposeConstructor = true; - if (this.options.checkVisibility) { - final int modifiers = acceptedConstructor.modifiers; - proposeConstructor = !(((modifiers & ClassFileConstants.AccPublic) == 0) && - ((modifiers & ClassFileConstants.AccPrivate) != 0)); - } - if (proposeConstructor) { - proposeConstructor(acceptedConstructor); - } - } + //decide if constructor should be proposed based on visibility rules + boolean proposeConstructor = true; + if (this.options.checkVisibility) { + proposeConstructor = !(((modifiers & ClassFileConstants.AccPublic) == 0) && + ((modifiers & ClassFileConstants.AccPrivate) != 0)); + } + + if (proposeConstructor) { + proposeConstructor(typeName, parameterTypes, parameterNames, + modifiers, accessibility); } } @@ -756,8 +759,8 @@ public final class CompletionEngine if(!CompletionEngine.this.requestor.isIgnored(CompletionProposal.LOCAL_VARIABLE_REF)) { CompletionProposal proposal = CompletionEngine.this.createProposal(CompletionProposal.LOCAL_VARIABLE_REF, CompletionEngine.this.actualCompletionPosition); proposal.setSignature(JAVA_LANG_OBJECT_SIGNATURE); - proposal.setPackageName(JAVA_LANG_NAME); - proposal.setTypeName(OBJECT); + proposal.setReturnQualification(JAVA_LANG_NAME); + proposal.setReturnSimpleName(OBJECT); proposal.setName(name); proposal.setCompletion(name); proposal.setFlags(Flags.AccDefault); @@ -770,627 +773,134 @@ public final class CompletionEngine } } - /** - *

When doing an index search for bindings this is where the results end up.

- * - * @param name the name of the binding - * @param exactMatch true if an exact match is needed, false otherwise - * @param prefixRequired + * One result of the search consists of a new package. + * + * NOTE - All package names are presented in their readable form: + * Package names are in the form "a.b.c". + * The default package is represented by an empty array. */ - private void acceptBindings(char[] name,boolean exactMatch, boolean prefixRequired) { - - if(this.acceptedBindings == null) return; + public void acceptPackage(char[] packageName) { - int length = this.acceptedBindings.size(); + if (this.knownPkgs.containsKey(packageName)) return; - if(length == 0) return; + this.knownPkgs.put(packageName, this); + int relevance = computeBaseRelevance(); + relevance += computeRelevanceForResolution(); + relevance += computeRelevanceForInterestingProposal(); + relevance += computeRelevanceForCaseMatching(this.qualifiedCompletionToken == null ? this.completionToken : this.qualifiedCompletionToken, packageName); + if(!this.resolvingImports) { + relevance += computeRelevanceForQualification(true); + } + relevance += computeRelevanceForRestrictions(IAccessRule.K_ACCESSIBLE); - for (int i = 0; i < length; i++) { - AcceptedBinding acceptedType = (AcceptedBinding)this.acceptedBindings.elementAt(i); - char[] packageName = acceptedType.packageName; - char[] bindingName = acceptedType.simpleTypeName; - char[][] enclosingTypeNames = acceptedType.enclosingTypeNames; - int modifiers = acceptedType.modifiers; - if (packageName==null) - packageName=new char[0]; + this.noProposal = false; + } + private void buildContext( + ASTNode astNode, + ASTNode astNodeParent, + Binding qualifiedBinding, + Scope scope) { + CompletionContext context = new CompletionContext(); - Binding binding1 = this.unitScope.getBinding(packageName, Binding.PACKAGE, FakeInvocationSite, false); - Binding binding2=null; - if (binding1 instanceof PackageBinding) { - PackageBinding packageBinding = (PackageBinding) binding1; - binding2 = packageBinding.getBinding(bindingName, acceptedType.bindingType); - if (binding2==null) - continue; + // build expected types context + if (this.expectedTypesPtr > -1) { + int length = this.expectedTypesPtr + 1; + char[][] expTypes = new char[length][]; + char[][] expKeys = new char[length][]; + for (int i = 0; i < length; i++) { + expTypes[i] = getSignature(this.expectedTypes[i]); + expKeys[i] = this.expectedTypes[i].computeUniqueKey(); } + context.setExpectedTypesSignatures(expTypes); + context.setExpectedTypesKeys(expKeys); + } - switch (acceptedType.bindingType) - { - case Binding.METHOD: - { - char[] completion = bindingName; - if (!exactMatch) { - if (this.source != null - && this.source.length > this.endPosition - && this.source[this.endPosition] == '(') - completion = bindingName; - else - completion = CharOperation.concat(bindingName, new char[] { '(', ')' }); - } else { - if(prefixRequired && (this.source != null)) { - completion = CharOperation.subarray(this.source, this.startPosition, this.endPosition); - } else { - this.startPosition = this.endPosition; - } - } - - if (binding2 instanceof MethodBinding && binding2.isValidBinding()) { - MethodBinding method = (MethodBinding) binding2; - - - int relevance = computeBaseRelevance(); - relevance += computeRelevanceForInterestingProposal(); - if (name != null) relevance += computeRelevanceForCaseMatching(name, bindingName); - relevance += computeRelevanceForExpectingType(method.returnType); - relevance += computeRelevanceForQualification(prefixRequired); - relevance += computeRelevanceForRestrictions(IAccessRule.K_ACCESSIBLE); - - //figure out the parameters - int parametersLength=method.original().parameters.length; - char[][] parameterPackageNames = new char[parametersLength][]; - char[][] parameterFullTypeNames = new char[parametersLength][]; - for (int j = 0; j < parametersLength; j++) { - TypeBinding type = method.parameters[j]; - parameterPackageNames[j] = type.qualifiedPackageName(); - parameterFullTypeNames[j] = type.qualifiedSourceName(); - } - char[][] parameterNames = findMethodParameterNames(method, parameterFullTypeNames); - - this.noProposal = false; - // Standard proposal - if(!this.requestor.isIgnored(CompletionProposal.METHOD_REF) && (this.assistNodeInJavadoc & CompletionOnJavadoc.ONLY_INLINE_TAG) == 0) { - CompletionProposal proposal = this.createProposal(CompletionProposal.METHOD_REF, this.actualCompletionPosition); - proposal.setDeclarationSignature(getSignature(method.declaringClass)); - proposal.setSignature(getSignature(method)); - MethodBinding original = method.original(); - if(original != method) { - proposal.setOriginalSignature(getSignature(original)); - } - proposal.setDeclarationPackageName(packageName); - proposal.setDeclarationTypeName(method.declaringClass.qualifiedSourceName()); - proposal.setParameterPackageNames(parameterPackageNames); - proposal.setParameterTypeNames(parameterFullTypeNames); - - if(method.returnType!=null) { - proposal.setPackageName(method.returnType.qualifiedPackageName()); - proposal.setTypeName(method.returnType.qualifiedSourceName()); - }else { - proposal.setTypeName(null); - } + context.setOffset(this.actualCompletionPosition + 1 - this.offset); + // Set javadoc info + if (astNode instanceof CompletionOnJavadoc) { + this.assistNodeInJavadoc = ((CompletionOnJavadoc)astNode).getCompletionFlags(); + context.setJavadoc(this.assistNodeInJavadoc); + } - proposal.setName(bindingName); - proposal.setCompletion(completion); - proposal.setFlags(modifiers); - proposal.setReplaceRange(this.startPosition - this.offset, this.endPosition - this.offset); - proposal.setRelevance(relevance); - if(parameterNames != null) proposal.setParameterNames(parameterNames); - proposal.setIsContructor(method.isConstructor()); - this.requestor.accept(proposal); - if(DEBUG) { - this.printDebug(proposal); - } - } + if (!(astNode instanceof CompletionOnJavadoc)) { + CompletionScanner scanner = (CompletionScanner)this.parser.scanner; + context.setToken(scanner.completionIdentifier); + context.setTokenRange( + scanner.completedIdentifierStart - this.offset, + scanner.completedIdentifierEnd - this.offset, + scanner.endOfEmptyToken - this.offset); + } else if(astNode instanceof CompletionOnJavadocTag) { + CompletionOnJavadocTag javadocTag = (CompletionOnJavadocTag) astNode; + context.setToken(CharOperation.concat(new char[]{'@'}, javadocTag.token)); + context.setTokenRange( + javadocTag.tagSourceStart - this.offset, + javadocTag.tagSourceEnd - this.offset, + ((CompletionScanner)this.parser.javadocParser.scanner).endOfEmptyToken - this.offset); + } else { + CompletionScanner scanner = (CompletionScanner)this.parser.javadocParser.scanner; + context.setToken(scanner.completionIdentifier); + context.setTokenRange( + scanner.completedIdentifierStart - this.offset, + scanner.completedIdentifierEnd - this.offset, + scanner.endOfEmptyToken - this.offset); + } - // Javadoc proposal - if ((this.assistNodeInJavadoc & CompletionOnJavadoc.TEXT) != 0 && !this.requestor.isIgnored(CompletionProposal.JSDOC_METHOD_REF)) { - char[] javadocCompletion = inlineTagCompletion(completion, JavadocTagConstants.TAG_LINK); - CompletionProposal proposal = this.createProposal(CompletionProposal.JSDOC_METHOD_REF, this.actualCompletionPosition); - proposal.setDeclarationSignature(getSignature(method.declaringClass)); - proposal.setSignature(getSignature(method)); - MethodBinding original = method.original(); - if(original != method) { - proposal.setOriginalSignature(getSignature(original)); - } - proposal.setDeclarationPackageName(method.declaringClass.qualifiedPackageName()); - proposal.setDeclarationTypeName(method.declaringClass.qualifiedSourceName()); - proposal.setParameterPackageNames(parameterPackageNames); - proposal.setParameterTypeNames(parameterFullTypeNames); - proposal.setPackageName(method.returnType.qualifiedPackageName()); - proposal.setTypeName(method.returnType.qualifiedSourceName()); - proposal.setName(bindingName); - proposal.setCompletion(javadocCompletion); - proposal.setFlags( modifiers); - int start = (this.assistNodeInJavadoc & CompletionOnJavadoc.REPLACE_TAG) != 0 ? this.javadocTagPosition : this.startPosition; - proposal.setReplaceRange(start - this.offset, this.endPosition - this.offset); - proposal.setRelevance(relevance+R_INLINE_TAG); - if(parameterNames != null) proposal.setParameterNames(parameterNames); - proposal.setIsContructor(method.isConstructor()); - this.requestor.accept(proposal); - if(DEBUG) { - this.printDebug(proposal); - } - } - }//end if method binding - else - { - int relevance = computeBaseRelevance(); - relevance += computeRelevanceForInterestingProposal(); - if (name != null) relevance += computeRelevanceForCaseMatching(name, bindingName); - relevance += computeRelevanceForQualification(prefixRequired); - relevance += computeRelevanceForRestrictions(IAccessRule.K_ACCESSIBLE); + if(astNode instanceof CompletionOnStringLiteral) { + context.setTokenKind(CompletionContext.TOKEN_KIND_STRING_LITERAL); + } else { + context.setTokenKind(CompletionContext.TOKEN_KIND_NAME); + } - char [] defaultSignature={'(',')','V'}; - this.noProposal = false; - // Standard proposal - if(!this.requestor.isIgnored(CompletionProposal.METHOD_REF) && (this.assistNodeInJavadoc & CompletionOnJavadoc.ONLY_INLINE_TAG) == 0) { - CompletionProposal proposal = this.createProposal(CompletionProposal.METHOD_REF, this.actualCompletionPosition); - proposal.setSignature(defaultSignature); - proposal.setDeclarationPackageName(packageName); - proposal.setName(bindingName); - proposal.setCompletion(completion); - proposal.setFlags(modifiers); - proposal.setReplaceRange(this.startPosition - this.offset, this.endPosition - this.offset); - proposal.setRelevance(relevance); - if(enclosingTypeNames != null) proposal.setParameterNames(enclosingTypeNames); - this.requestor.accept(proposal); - if(DEBUG) { - this.printDebug(proposal); - } - } + if(DEBUG) { + System.out.println(context.toString()); + } + this.requestor.acceptContext(context); + } - // Javadoc proposal - if ((this.assistNodeInJavadoc & CompletionOnJavadoc.TEXT) != 0 && !this.requestor.isIgnored(CompletionProposal.JSDOC_METHOD_REF)) { - char[] javadocCompletion = inlineTagCompletion(completion, JavadocTagConstants.TAG_LINK); - CompletionProposal proposal = this.createProposal(CompletionProposal.JSDOC_METHOD_REF, this.actualCompletionPosition); - proposal.setName(bindingName); - proposal.setCompletion(javadocCompletion); - proposal.setFlags( modifiers); - int start = (this.assistNodeInJavadoc & CompletionOnJavadoc.REPLACE_TAG) != 0 ? this.javadocTagPosition : this.startPosition; - proposal.setReplaceRange(start - this.offset, this.endPosition - this.offset); - proposal.setRelevance(relevance+R_INLINE_TAG); - if(enclosingTypeNames != null) proposal.setParameterNames(enclosingTypeNames); - this.requestor.accept(proposal); - if(DEBUG) { - this.printDebug(proposal); - } - } + private boolean complete(ASTNode astNode, ASTNode astNodeParent, Binding qualifiedBinding, Scope scope, boolean insideTypeAnnotation) { - } + setSourceRange(astNode.sourceStart, astNode.sourceEnd); - } - break; - case Binding.VARIABLE: - case Binding.LOCAL: - case Binding.FIELD: - { - char[] completion = bindingName; + scope = computeForbiddenBindings(astNode, astNodeParent, scope); + computeUninterestingBindings(astNodeParent, scope); + if(astNodeParent != null) { + if(!isValidParent(astNodeParent, astNode, scope)) return false; + computeExpectedTypes(astNodeParent, astNode, scope); + } - if (binding2 instanceof LocalVariableBinding && binding2.isValidBinding()) { - LocalVariableBinding variableBinding = (LocalVariableBinding) binding2; + buildContext(astNode, astNodeParent, qualifiedBinding, scope); - int relevance = computeBaseRelevance(); - relevance += computeRelevanceForInterestingProposal(variableBinding); - if (name != null) relevance += computeRelevanceForCaseMatching(name, variableBinding.name); - relevance += computeRelevanceForExpectingType(variableBinding.type); - relevance += computeRelevanceForQualification(prefixRequired); - relevance += computeRelevanceForRestrictions(IAccessRule.K_ACCESSIBLE); + if (astNode instanceof CompletionOnFieldType) { - this.noProposal = false; - // Standard proposal - if (!this.requestor.isIgnored(CompletionProposal.FIELD_REF) && (this.assistNodeInJavadoc & CompletionOnJavadoc.ONLY_INLINE_TAG) == 0) { - CompletionProposal proposal = this.createProposal(CompletionProposal.FIELD_REF, this.actualCompletionPosition); - if (variableBinding.declaringScope instanceof CompilationUnitScope) { - CompilationUnitScope compilationUnitScope = (CompilationUnitScope) variableBinding.declaringScope; + CompletionOnFieldType field = (CompletionOnFieldType) astNode; + CompletionOnSingleTypeReference type = (CompletionOnSingleTypeReference) field.type; + this.completionToken = type.token; + setSourceRange(type.sourceStart, type.sourceEnd); - proposal.setDeclarationSignature(getSignature(compilationUnitScope.referenceContext.compilationUnitBinding)); - } - proposal.setSignature(getSignature(variableBinding.type)); - proposal.setDeclarationTypeName(packageName); - proposal.setPackageName(variableBinding.type.qualifiedPackageName()); - proposal.setTypeName(variableBinding.type.qualifiedSourceName()); - proposal.setName(variableBinding.name); - proposal.setCompletion(completion); - proposal.setFlags(variableBinding.modifiers); - proposal.setReplaceRange(this.startPosition - this.offset, this.endPosition - this.offset); - proposal.setRelevance(relevance); - this.requestor.accept(proposal); - if(DEBUG) { - this.printDebug(proposal); - } - } + findTypesAndPackages(this.completionToken, scope, new ObjectVector()); + if (!this.requestor.isIgnored(CompletionProposal.KEYWORD)) { + findKeywordsForMember(this.completionToken, field.modifiers); + } - // Javadoc completions - if ((this.assistNodeInJavadoc & CompletionOnJavadoc.TEXT) != 0 && !this.requestor.isIgnored(CompletionProposal.JSDOC_FIELD_REF)) { - char[] javadocCompletion = inlineTagCompletion(completion, JavadocTagConstants.TAG_LINK); - CompletionProposal proposal = this.createProposal(CompletionProposal.JSDOC_FIELD_REF, this.actualCompletionPosition); - proposal.setSignature(getSignature(variableBinding.type)); - proposal.setDeclarationPackageName(packageName); - proposal.setPackageName(variableBinding.type.qualifiedPackageName()); - proposal.setTypeName(variableBinding.type.qualifiedSourceName()); - proposal.setName(variableBinding.name); - proposal.setCompletion(javadocCompletion); - proposal.setFlags(variableBinding.modifiers); - int start = (this.assistNodeInJavadoc & CompletionOnJavadoc.REPLACE_TAG) != 0 ? this.javadocTagPosition : this.startPosition; - proposal.setReplaceRange(start - this.offset, this.endPosition - this.offset); - proposal.setRelevance(relevance+R_INLINE_TAG); - this.requestor.accept(proposal); - if(DEBUG) { - this.printDebug(proposal); - } + if (!field.isLocalVariable && field.modifiers == ClassFileConstants.AccDefault) { + SourceTypeBinding enclosingType = scope.enclosingSourceType(); + + if (!this.requestor.isIgnored(CompletionProposal.METHOD_DECLARATION)) { + findMethods(this.completionToken,null,null,enclosingType,scope,new ObjectVector(),false,false,true,null,null,false,false,true,null, null, null, false); } - } else { - if (binding2!=null) - //TODO: implement - throw new UnimplementedException(); + if (!this.requestor.isIgnored(CompletionProposal.POTENTIAL_METHOD_DECLARATION)) { + proposeNewMethod(this.completionToken, enclosingType); } - } - break; - } - } - this.acceptedBindings = null; // reset - } - - - - - // this code is derived from FunctionBinding#areParametersCompatibleWith(TypeBinding[]) - private final boolean areParametersCompatibleWith(TypeBinding[] parameters, TypeBinding[] arguments, boolean isVarargs) { - int paramLength = parameters.length; - int argLength = arguments.length; - int lastIndex = argLength; - if (isVarargs) { - lastIndex = paramLength - 1; - if (paramLength == argLength) { // accept X[] but not X or X[][] - TypeBinding varArgType = parameters[lastIndex]; // is an ArrayBinding by definition - TypeBinding lastArgument = arguments[lastIndex]; - if (varArgType != lastArgument && !lastArgument.isCompatibleWith(varArgType)) - return false; - } else if (paramLength < argLength) { // all remainig argument types must be compatible with the elementsType of varArgType - TypeBinding varArgType = ((ArrayBinding) parameters[lastIndex]).elementsType(); - for (int i = lastIndex; i < argLength; i++) - if (varArgType != arguments[i] && !arguments[i].isCompatibleWith(varArgType)) - return false; - } else if (lastIndex != argLength) { // can call foo(int i, X ... x) with foo(1) but NOT foo(); - return false; - } - // now compare standard arguments from 0 to lastIndex - } else { - if(paramLength != argLength) - return false; - } - for (int i = 0; i < lastIndex; i++) - if (parameters[i] != arguments[i] && !arguments[i].isCompatibleWith(parameters[i])) - return false; - return true; - } - - /** - *

Propose a constructor based on an {@link AcceptedConstructor}.

- * - * @param acceptedConstructor {@link AcceptedConstructor} to create a proposal for - */ - private void proposeConstructor(AcceptedConstructor acceptedConstructor) { - proposeConstructor( - acceptedConstructor.typeName, - acceptedConstructor.parameterCount, - acceptedConstructor.parameterTypes, - acceptedConstructor.parameterNames, - acceptedConstructor.modifiers, - acceptedConstructor.accessibility); - } - - /** - *

Create a constructor proposal based on the given information.

- * - * @param typeName Name of the type the constructor is for - * @param parameterCount Number of parameters for the constructor, or -1 for a default constructor - * @param parameterTypes Type names of the parameters, should be same length as parameterCount - * @param parameterNames Type names of the parameters, should be same length as parameterCount - * @param modifiers Type names of the parameters, should be same length as parameterCount - * @param accessibility Accessibility of the constructor - * - * @see Flags - * @see IAccessRule - */ - private void proposeConstructor( - char[] typeName, - int parameterCount, - char[][] parameterTypes, - char[][] parameterNames, - int modifiers, - int accessibility) { - - int relevance = computeBaseRelevance(); - relevance += computeRelevanceForResolution(); - relevance += computeRelevanceForInterestingProposal(); - relevance += computeRelevanceForRestrictions(accessibility); - relevance += computeRelevanceForCaseMatching(this.completionToken, typeName); - relevance += computeRelevanceForClass(); - relevance += computeRelevanceForException(typeName); - - char[] completion; - if (this.source != null - && this.source.length > this.endPosition - && this.source[this.endPosition] == '(') { - completion = CharOperation.NO_CHAR; - } else { - completion = new char[] { '(', ')' }; - } - - //NOTE: currently all constructors are assumed to be public - int flags = modifiers; - flags |= Flags.AccPublic; - - switch (parameterCount) { - case -1: {// default constructor - flags = Flags.AccPublic; - this.noProposal = false; - if(!isIgnored(CompletionProposal.CONSTRUCTOR_INVOCATION, CompletionProposal.TYPE_REF)) { - CompletionProposal proposal = createProposal(CompletionProposal.CONSTRUCTOR_INVOCATION, this.actualCompletionPosition); - proposal.setDeclarationSignature(createNonGenericTypeSignature(typeName)); - proposal.setDeclarationTypeName(typeName); - proposal.setParameterPackageNames(CharOperation.NO_CHAR_CHAR); - proposal.setParameterTypeNames(CharOperation.NO_CHAR_CHAR); - proposal.setParameterNames(CharOperation.NO_CHAR_CHAR); - proposal.setName(typeName); - proposal.setIsContructor(true); - proposal.setCompletion(completion); - proposal.setFlags(flags); - proposal.setReplaceRange(this.startPosition - this.offset, this.endPosition - this.offset); - proposal.setRelevance(relevance); - this.requestor.accept(proposal); - } - break; - } - case 0: {// constructor with no parameter - this.noProposal = false; - if(!isIgnored(CompletionProposal.CONSTRUCTOR_INVOCATION, CompletionProposal.TYPE_REF)) { - CompletionProposal proposal = createProposal(CompletionProposal.CONSTRUCTOR_INVOCATION, this.actualCompletionPosition); - proposal.setDeclarationSignature(createNonGenericTypeSignature(typeName)); - proposal.setDeclarationTypeName(typeName); - proposal.setParameterPackageNames(CharOperation.NO_CHAR_CHAR); - proposal.setParameterTypeNames(CharOperation.NO_CHAR_CHAR); - proposal.setParameterNames(CharOperation.NO_CHAR_CHAR); - proposal.setName(typeName); - proposal.setIsContructor(true); - proposal.setCompletion(completion); - proposal.setFlags(flags); - proposal.setReplaceRange(this.startPosition - this.offset, this.endPosition - this.offset); - proposal.setRelevance(relevance); - this.requestor.accept(proposal); - - } - break; - } - default: {// constructor with parameter - int parameterNamesLength = parameterNames == null ? 0 : parameterNames.length; - if (parameterCount != parameterNamesLength) { - parameterNames = null; - } - - - this.noProposal = false; - if(!isIgnored(CompletionProposal.CONSTRUCTOR_INVOCATION, CompletionProposal.TYPE_REF)) { - CompletionProposal proposal = createProposal(CompletionProposal.CONSTRUCTOR_INVOCATION, this.actualCompletionPosition); - proposal.setDeclarationSignature(createNonGenericTypeSignature(typeName)); - proposal.setDeclarationTypeName(typeName); - proposal.setParameterPackageNames(CharOperation.NO_CHAR_CHAR); - if(parameterTypes != null) { - proposal.setParameterTypeNames(parameterTypes); - } - if (parameterNames != null) { - proposal.setParameterNames(parameterNames); - } - proposal.setName(typeName); - proposal.setIsContructor(true); - proposal.setCompletion(completion); - proposal.setFlags(flags); - proposal.setReplaceRange(this.startPosition - this.offset, this.endPosition - this.offset); - proposal.setRelevance(relevance); - - this.requestor.accept(proposal); - } - break; - } - } - } - - private void proposeType(char[] packageName, char[] simpleTypeName, int modifiers, int accessibility, char[] typeName, char[] fullyQualifiedName, boolean isQualified, Scope scope) { - char[] completionName = fullyQualifiedName; - if(isQualified) { - if (packageName == null || packageName.length == 0) - if (this.unitScope != null && this.unitScope.getDefaultPackage().compoundName != CharOperation.NO_CHAR_CHAR) - return; // ignore types from the default package from outside it - } else { - completionName = simpleTypeName; - } - - int relevance = computeBaseRelevance(); - relevance += computeRelevanceForResolution(); - relevance += computeRelevanceForInterestingProposal(); - relevance += computeRelevanceForRestrictions(accessibility); - relevance += computeRelevanceForCaseMatching(this.completionToken, simpleTypeName); - relevance += computeRelevanceForExpectingType(packageName, simpleTypeName); - relevance += computeRelevanceForQualification(isQualified); - relevance += computeRelevanceForClass(); - relevance += computeRelevanceForException(simpleTypeName); - - // put proposals that have '_' at the start of their final segment down the list - char[] lastSegment = CharOperation.lastSegment(completionName, '.'); - if(CharOperation.indexOf('_', lastSegment) == 0) { - relevance--; - } - this.noProposal = false; - if(!this.requestor.isIgnored(CompletionProposal.TYPE_REF)) { - createTypeProposal(packageName, typeName, modifiers, accessibility, completionName, relevance); - } - } - - /** - * One result of the search consists of a new package. - * - * NOTE - All package names are presented in their readable form: - * Package names are in the form "a.b.c". - * The default package is represented by an empty array. - */ - public void acceptPackage(char[] packageName) { - - if (this.knownPkgs.containsKey(packageName)) return; - - this.knownPkgs.put(packageName, this); - -// char[] completion; -// if(this.resolvingImports) { -// if(this.resolvingStaticImports) { -// completion = CharOperation.concat(packageName, new char[] { '.' }); -// } else { -// completion = CharOperation.concat(packageName, new char[] { '.', '*', ';' }); -// } -// } else { -// completion = packageName; -// } - - int relevance = computeBaseRelevance(); - relevance += computeRelevanceForResolution(); - relevance += computeRelevanceForInterestingProposal(); - relevance += computeRelevanceForCaseMatching(this.qualifiedCompletionToken == null ? this.completionToken : this.qualifiedCompletionToken, packageName); - if(!this.resolvingImports) { - relevance += computeRelevanceForQualification(true); - } - relevance += computeRelevanceForRestrictions(IAccessRule.K_ACCESSIBLE); - - this.noProposal = false; -// if(!this.requestor.isIgnored(CompletionProposal.PACKAGE_REF)) { -// CompletionProposal proposal = this.createProposal(CompletionProposal.PACKAGE_REF, this.actualCompletionPosition); -// proposal.setDeclarationSignature(packageName); -// proposal.setPackageName(packageName); -// proposal.setCompletion(completion); -// proposal.setReplaceRange(this.startPosition - this.offset, this.endPosition - this.offset); -// proposal.setRelevance(relevance); -// this.requestor.accept(proposal); -// if(DEBUG) { -// this.printDebug(proposal); -// } -// } - } - - private void buildContext( - ASTNode astNode, - ASTNode astNodeParent, - Binding qualifiedBinding, - Scope scope) { - CompletionContext context = new CompletionContext(); - - // build expected types context - if (this.expectedTypesPtr > -1) { - int length = this.expectedTypesPtr + 1; - char[][] expTypes = new char[length][]; - char[][] expKeys = new char[length][]; - for (int i = 0; i < length; i++) { - expTypes[i] = getSignature(this.expectedTypes[i]); - expKeys[i] = this.expectedTypes[i].computeUniqueKey(); - } - context.setExpectedTypesSignatures(expTypes); - context.setExpectedTypesKeys(expKeys); - } - - context.setOffset(this.actualCompletionPosition + 1 - this.offset); - - // Set javadoc info - if (astNode instanceof CompletionOnJavadoc) { - this.assistNodeInJavadoc = ((CompletionOnJavadoc)astNode).getCompletionFlags(); - context.setJavadoc(this.assistNodeInJavadoc); - } - - if (!(astNode instanceof CompletionOnJavadoc)) { - CompletionScanner scanner = (CompletionScanner)this.parser.scanner; - context.setToken(scanner.completionIdentifier); - context.setTokenRange( - scanner.completedIdentifierStart - this.offset, - scanner.completedIdentifierEnd - this.offset, - scanner.endOfEmptyToken - this.offset); - } else if(astNode instanceof CompletionOnJavadocTag) { - CompletionOnJavadocTag javadocTag = (CompletionOnJavadocTag) astNode; - context.setToken(CharOperation.concat(new char[]{'@'}, javadocTag.token)); - context.setTokenRange( - javadocTag.tagSourceStart - this.offset, - javadocTag.tagSourceEnd - this.offset, - ((CompletionScanner)this.parser.javadocParser.scanner).endOfEmptyToken - this.offset); - } else { - CompletionScanner scanner = (CompletionScanner)this.parser.javadocParser.scanner; - context.setToken(scanner.completionIdentifier); - context.setTokenRange( - scanner.completedIdentifierStart - this.offset, - scanner.completedIdentifierEnd - this.offset, - scanner.endOfEmptyToken - this.offset); - } - - if(astNode instanceof CompletionOnStringLiteral) { - context.setTokenKind(CompletionContext.TOKEN_KIND_STRING_LITERAL); - } else { - context.setTokenKind(CompletionContext.TOKEN_KIND_NAME); - } - - if(DEBUG) { - System.out.println(context.toString()); - } - this.requestor.acceptContext(context); - } - - private boolean complete(ASTNode astNode, ASTNode astNodeParent, Binding qualifiedBinding, Scope scope, boolean insideTypeAnnotation) { - - setSourceRange(astNode.sourceStart, astNode.sourceEnd); - - scope = computeForbiddenBindings(astNode, astNodeParent, scope); - computeUninterestingBindings(astNodeParent, scope); - if(astNodeParent != null) { - if(!isValidParent(astNodeParent, astNode, scope)) return false; - computeExpectedTypes(astNodeParent, astNode, scope); - } - - buildContext(astNode, astNodeParent, qualifiedBinding, scope); - - if (astNode instanceof CompletionOnFieldType) { - - CompletionOnFieldType field = (CompletionOnFieldType) astNode; - CompletionOnSingleTypeReference type = (CompletionOnSingleTypeReference) field.type; - this.completionToken = type.token; - setSourceRange(type.sourceStart, type.sourceEnd); - - findTypesAndPackages(this.completionToken, scope, new ObjectVector()); - if (!this.requestor.isIgnored(CompletionProposal.KEYWORD)) { - findKeywordsForMember(this.completionToken, field.modifiers); - } - - if (!field.isLocalVariable && field.modifiers == ClassFileConstants.AccDefault) { - SourceTypeBinding enclosingType = scope.enclosingSourceType(); - - if (!this.requestor.isIgnored(CompletionProposal.METHOD_DECLARATION)) { - findMethods(this.completionToken,null,null,enclosingType,scope,new ObjectVector(),false,false,true,null,null,false,false,true,null, null, null, false); - } - if (!this.requestor.isIgnored(CompletionProposal.POTENTIAL_METHOD_DECLARATION)) { - proposeNewMethod(this.completionToken, enclosingType); - } - } - } else if (astNode instanceof CompletionOnSingleNameReference) { + } else if (astNode instanceof CompletionOnSingleNameReference) { CompletionOnSingleNameReference singleNameReference = (CompletionOnSingleNameReference) astNode; this.completionToken = singleNameReference.token; - SwitchStatement switchStatement = astNodeParent instanceof SwitchStatement ? (SwitchStatement) astNodeParent : null; - if (scope instanceof BlockScope && !this.requestor.isIgnored(CompletionProposal.LOCAL_VARIABLE_REF)) { - char[][] alreadyDefinedName = computeAlreadyDefinedName((BlockScope)scope, singleNameReference); - - findUnresolvedReference( - singleNameReference.sourceStart, - singleNameReference.sourceEnd, - (BlockScope)scope, - alreadyDefinedName); - } findVariablesAndMethods( this.completionToken, scope, @@ -1413,7 +923,7 @@ public final class CompletionEngine findExplicitConstructors(Keywords.THIS, ref, (MethodScope)scope, singleNameReference); } else if (CharOperation.prefixEquals(this.completionToken, Keywords.SUPER, false)) { ReferenceBinding ref = scope.enclosingSourceType(); - findExplicitConstructors(Keywords.SUPER, ref.superclass(), (MethodScope)scope, singleNameReference); + findExplicitConstructors(Keywords.SUPER, ref.getSuperBinding(), (MethodScope)scope, singleNameReference); } } @@ -1714,11 +1224,6 @@ public final class CompletionEngine long completionPosition = access.nameSourcePosition; setSourceRange((int) (completionPosition >>> 32), (int) completionPosition); - - -// this.assistNodeIsClass = true; -// this.assistNodeIsConstructor = true; - // can be the start of a qualified type name if (qualifiedBinding == null) { @@ -1730,13 +1235,14 @@ public final class CompletionEngine } else { this.completionToken = access.token; if (qualifiedBinding.problemId() == ProblemReasons.NotFound) { - // complete method members with missing return type - // class X { - // Missing f() {return null;} - // void foo() { - // f().| - // } - // } + /* complete method members with missing return type + * class X { + * Missing f() {return null;} + * void foo() { + * f().| + * } + * } + */ if (this.assistNodeInJavadoc == 0 && (this.requestor.isAllowingRequiredProposals(CompletionProposal.FIELD_REF, CompletionProposal.TYPE_REF) || this.requestor.isAllowingRequiredProposals(CompletionProposal.METHOD_REF, CompletionProposal.TYPE_REF))) { @@ -1892,7 +1398,7 @@ public final class CompletionEngine excludeNames[i] = fields[i].name; } - this.completionToken = method.selector; + this.completionToken = method.getName(); findVariableNames(this.completionToken, method.returnType, excludeNames, null, FIELD, method.modifiers); } @@ -1960,16 +1466,6 @@ public final class CompletionEngine this.insideQualifiedReference = true; this.completionToken = messageSend.selector; - boolean onlyStatic = false; - TypeBinding receiverType = null; - if(qualifiedBinding instanceof VariableBinding) { - receiverType = ((VariableBinding)qualifiedBinding).type; - } else if(qualifiedBinding instanceof MethodBinding) { - receiverType = ((MethodBinding)qualifiedBinding).returnType; - } else if(qualifiedBinding instanceof ReferenceBinding) { - onlyStatic = true; - receiverType = (TypeBinding)qualifiedBinding; - } } // Completion on Javadoc nodes } else if ((astNode.bits & ASTNode.InsideJavadoc) != 0) { @@ -2419,7 +1915,7 @@ public final class CompletionEngine if (parsedUnit.statements != null) { try { - this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/); + this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/, true); if ((this.unitScope = parsedUnit.scope) != null) { this.source = sourceUnit.getContents(); @@ -2434,7 +1930,6 @@ public final class CompletionEngine parsedUnit.resolve(); } } catch (CompletionNodeFound e) { - // completionNodeFound = true; if (e.astNode != null) { if(DEBUG) { System.out.print("COMPLETION - Completion node : "); //$NON-NLS-1$ @@ -2444,6 +1939,12 @@ public final class CompletionEngine System.out.println(this.parser.assistNodeParent); } } + + //in case completion node found before unit scope set + if(this.unitScope == null && parsedUnit.scope != null) { + this.unitScope = parsedUnit.scope; + } + // if null then we found a problem in the completion node contextAccepted = complete(e.astNode, this.parser.assistNodeParent, e.qualifiedBinding, e.scope, e.insideTypeAnnotation); } @@ -2570,8 +2071,8 @@ public final class CompletionEngine proposal.setSignature(signature); //proposal.setDeclarationPackageName(null); //proposal.setDeclarationTypeName(null); - proposal.setPackageName(CharOperation.concatWith(JAVA_LANG, '.')); - proposal.setTypeName(CLASS); + proposal.setReturnQualification(CharOperation.concatWith(JAVA_LANG, '.')); + proposal.setReturnSimpleName(CLASS); proposal.setName(classField); proposal.setCompletion(classField); proposal.setFlags(Flags.AccStatic | Flags.AccPublic); @@ -2598,10 +2099,10 @@ public final class CompletionEngine if (searchSuperClasses) { ReferenceBinding javaLangThrowable = scope.getJavaLangThrowable(); if (exceptionType != javaLangThrowable) { - ReferenceBinding superClass = exceptionType.superclass(); + ReferenceBinding superClass = exceptionType.getSuperBinding(); while(superClass != null && superClass != javaLangThrowable) { findExceptionFromTryStatement(typeName, superClass, receiverType, invocationType, scope, typesFound, false); - superClass = superClass.superclass(); + superClass = superClass.getSuperBinding(); } } } @@ -2774,7 +2275,7 @@ public final class CompletionEngine InvocationSite invocationSite) { ConstructorDeclaration constructorDeclaration = (ConstructorDeclaration)scope.referenceContext; - MethodBinding enclosingConstructor = constructorDeclaration.binding; + MethodBinding enclosingConstructor = constructorDeclaration.getBinding(); // No visibility checks can be performed without the scope & invocationSite MethodBinding[] methods = currentType.availableMethods(); @@ -2794,11 +2295,9 @@ public final class CompletionEngine TypeBinding[] parameters = constructor.parameters; int paramLength = parameters.length; - char[][] parameterPackageNames = new char[paramLength][]; char[][] parameterTypeNames = new char[paramLength][]; for (int i = 0; i < paramLength; i++) { TypeBinding type = parameters[i]; - parameterPackageNames[i] = type.qualifiedPackageName(); parameterTypeNames[i] = type.qualifiedSourceName(); } char[][] parameterNames = findMethodParameterNames(constructor,parameterTypeNames); @@ -2828,10 +2327,7 @@ public final class CompletionEngine } proposal.setDeclarationPackageName(currentType.qualifiedPackageName()); proposal.setDeclarationTypeName(currentType.qualifiedSourceName()); - proposal.setParameterPackageNames(parameterPackageNames); proposal.setParameterTypeNames(parameterTypeNames); - //proposal.setPackageName(null); - //proposal.setTypeName(null); proposal.setName(name); proposal.setIsContructor(true); proposal.setCompletion(completion); @@ -2886,11 +2382,9 @@ public final class CompletionEngine continue next; } - char[][] parameterPackageNames = new char[paramLength][]; char[][] parameterTypeNames = new char[paramLength][]; for (int i = 0; i < paramLength; i++) { TypeBinding type = parameters[i]; - parameterPackageNames[i] = type.qualifiedPackageName(); parameterTypeNames[i] = type.qualifiedSourceName(); } char[][] parameterNames = findMethodParameterNames(constructor,parameterTypeNames); @@ -2924,10 +2418,7 @@ public final class CompletionEngine proposal.setKey(constructor.computeUniqueKey()); proposal.setDeclarationPackageName(currentType.qualifiedPackageName()); proposal.setDeclarationTypeName(currentType.qualifiedSourceName()); - proposal.setParameterPackageNames(parameterPackageNames); proposal.setParameterTypeNames(parameterTypeNames); - //proposal.setPackageName(null); - //proposal.setTypeName(null); proposal.setCompletion(completion); proposal.setFlags(constructor.modifiers); proposal.setReplaceRange(this.endPosition - this.offset, this.endPosition - this.offset); @@ -3009,7 +2500,6 @@ public final class CompletionEngine } proposal.setDeclarationPackageName(currentType.qualifiedPackageName()); proposal.setDeclarationTypeName(currentType.qualifiedSourceName()); - proposal.setParameterPackageNames(parameterPackageNames); proposal.setParameterTypeNames(parameterTypeNames); proposal.setName(currentType.sourceName()); proposal.setIsContructor(true); @@ -3034,10 +2524,7 @@ public final class CompletionEngine } proposal.setDeclarationPackageName(currentType.qualifiedPackageName()); proposal.setDeclarationTypeName(currentType.qualifiedSourceName()); - proposal.setParameterPackageNames(parameterPackageNames); proposal.setParameterTypeNames(parameterTypeNames); - //proposal.setPackageName(null); - //proposal.setTypeName(null); proposal.setName(currentType.sourceName()); proposal.setIsContructor(true); proposal.setCompletion(javadocCompletion); @@ -3136,103 +2623,8 @@ public final class CompletionEngine } newFieldsFound.add(new Object[]{field, receiverType}); - - char[] completion = field.name; - - if(prefixRequired || this.options.forceImplicitQualification){ - char[] prefix = computePrefix(scope.enclosingSourceType(), invocationScope.enclosingSourceType(), field.isStatic()); - completion = CharOperation.concat(prefix,completion,'.'); - } - - // Special case for javadoc completion - if (this.assistNodeInJavadoc > 0) { - if (invocationSite instanceof CompletionOnJavadocFieldReference) { - CompletionOnJavadocFieldReference fieldRef = (CompletionOnJavadocFieldReference) invocationSite; - if (fieldRef.receiver.isThis()) { - if (fieldRef.completeInText()) { - completion = CharOperation.concat(new char[] { '#' }, field.name); - } - } else if (fieldRef.completeInText()) { - if (fieldRef.receiver instanceof JavadocSingleTypeReference) { - JavadocSingleTypeReference typeRef = (JavadocSingleTypeReference) fieldRef.receiver; - completion = CharOperation.concat(typeRef.token, field.name, '#'); - } else if (fieldRef.receiver instanceof JavadocQualifiedTypeReference) { - JavadocQualifiedTypeReference typeRef = (JavadocQualifiedTypeReference) fieldRef.receiver; - completion = CharOperation.concat(CharOperation.concatWith(typeRef.tokens, '.'), field.name, '#'); - } - } - } - } - - int relevance = computeBaseRelevance(); - relevance += computeRelevanceForResolution(); - relevance += computeRelevanceForInterestingProposal(field); - if (fieldName != null) relevance += computeRelevanceForCaseMatching(fieldName, field.name); - relevance += computeRelevanceForExpectingType(field.type); - relevance += computeRelevanceForStatic(onlyStaticFields, field.isStatic()); - relevance += computeRelevanceForQualification(prefixRequired); - relevance += computeRelevanceForRestrictions(IAccessRule.K_ACCESSIBLE); - if (onlyStaticFields && this.insideQualifiedReference) { - relevance += computeRelevanceForInheritance(receiverType, field.declaringClass); - } - if (missingElements != null) { - relevance += computeRelevanceForMissingElements(missingElementsHaveProblems); - } - - this.noProposal = false; - // Standard proposal - if (!this.isIgnored(CompletionProposal.FIELD_REF, missingElements != null) && (this.assistNodeInJavadoc & CompletionOnJavadoc.ONLY_INLINE_TAG) == 0) { - CompletionProposal proposal = this.createProposal(CompletionProposal.FIELD_REF, this.actualCompletionPosition); - proposal.setDeclarationSignature(getSignature(field.declaringClass)); - proposal.setSignature(getSignature(field.type)); - proposal.setDeclarationPackageName(field.declaringClass.qualifiedPackageName()); - proposal.setDeclarationTypeName(field.declaringClass.qualifiedSourceName()); - proposal.setPackageName(field.type.qualifiedPackageName()); - proposal.setTypeName(field.type.qualifiedSourceName()); - proposal.setName(field.name); - if (missingElements != null) { - CompletionProposal[] subProposals = new CompletionProposal[missingElements.length]; - for (int i = 0; i < missingElements.length; i++) { - subProposals[i] = - createRequiredTypeProposal( - missingElements[i], - missingElementsStarts[i], - missingElementsEnds[i], - relevance); - } - proposal.setRequiredProposals(subProposals); - } - proposal.setCompletion(completion); - proposal.setFlags(field.modifiers); - proposal.setReplaceRange(this.startPosition - this.offset, this.endPosition - this.offset); - proposal.setRelevance(relevance); - this.requestor.accept(proposal); - if(DEBUG) { - this.printDebug(proposal); - } - } - - // Javadoc completions - if ((this.assistNodeInJavadoc & CompletionOnJavadoc.TEXT) != 0 && !this.requestor.isIgnored(CompletionProposal.JSDOC_FIELD_REF)) { - char[] javadocCompletion = inlineTagCompletion(completion, JavadocTagConstants.TAG_LINK); - CompletionProposal proposal = this.createProposal(CompletionProposal.JSDOC_FIELD_REF, this.actualCompletionPosition); - proposal.setDeclarationSignature(getSignature(field.declaringClass)); - proposal.setSignature(getSignature(field.type)); - proposal.setDeclarationPackageName(field.declaringClass.qualifiedPackageName()); - proposal.setDeclarationTypeName(field.declaringClass.qualifiedSourceName()); - proposal.setPackageName(field.type.qualifiedPackageName()); - proposal.setTypeName(field.type.qualifiedSourceName()); - proposal.setName(field.name); - proposal.setCompletion(javadocCompletion); - proposal.setFlags(field.modifiers); - int start = (this.assistNodeInJavadoc & CompletionOnJavadoc.REPLACE_TAG) != 0 ? this.javadocTagPosition : this.startPosition; - proposal.setReplaceRange(start - this.offset, this.endPosition - this.offset); - proposal.setRelevance(relevance+R_INLINE_TAG); - this.requestor.accept(proposal); - if(DEBUG) { - this.printDebug(proposal); - } - } + + this.proposeField(field); } fieldsFound.addAll(newFieldsFound); @@ -3281,7 +2673,7 @@ public final class CompletionEngine missingElementsHaveProblems); } - currentType = currentType.superclass(); + currentType = currentType.getSuperBinding(); } while (notInJavadoc && currentType != null); } @@ -3445,6 +2837,7 @@ public final class CompletionEngine MethodScope methodScope = (MethodScope) currentScope; staticsOnly |= methodScope.isStatic | methodScope.isConstructorCall; + //$FALL-THROUGH$ - fall through is done on purpose case Scope.BLOCK_SCOPE : break; @@ -3500,6 +2893,7 @@ public final class CompletionEngine MethodScope methodScope = (MethodScope) currentScope; staticsOnly |= methodScope.isStatic | methodScope.isConstructorCall; + //$FALL-THROUGH$ - fall through is done on purpose case Scope.BLOCK_SCOPE : break; @@ -3514,9 +2908,9 @@ public final class CompletionEngine for (int i = 0; i < methodsCount; i++) { AbstractMethodDeclaration methodDeclaration = methods[i]; if (methodDeclaration instanceof MethodDeclaration && - CharOperation.equals(methodDeclaration.selector, token)) { + CharOperation.equals(methodDeclaration.getName(), token)) { MethodDeclaration method = (MethodDeclaration) methodDeclaration; - if (methodDeclaration.binding == null) { + if (methodDeclaration.getBinding() == null) { Argument[] parameters = method.arguments; int parametersLength = parameters == null ? 0 : parameters.length; int argumentsLength = arguments == null ? 0 : arguments.length; @@ -3639,7 +3033,7 @@ public final class CompletionEngine int relevance = computeBaseRelevance(); relevance += computeRelevanceForResolution(); relevance += computeRelevanceForInterestingProposal(field); - if (fieldName != null) relevance += computeRelevanceForCaseMatching(fieldName, field.name); + relevance += computeRelevanceForCaseMatching(fieldName, field.name); relevance += computeRelevanceForExpectingType(field.type); relevance += computeRelevanceForStatic(true, true); relevance += computeRelevanceForRestrictions(IAccessRule.K_ACCESSIBLE); @@ -3660,8 +3054,8 @@ public final class CompletionEngine proposal.setSignature(getSignature(field.type)); proposal.setDeclarationPackageName(field.declaringClass.qualifiedPackageName()); proposal.setDeclarationTypeName(field.declaringClass.qualifiedSourceName()); - proposal.setPackageName(field.type.qualifiedPackageName()); - proposal.setTypeName(field.type.qualifiedSourceName()); + proposal.setReturnQualification(field.type.qualifiedPackageName()); + proposal.setReturnSimpleName(field.type.qualifiedSourceName()); proposal.setName(field.name); proposal.setCompletion(completion); proposal.setFlags(field.modifiers); @@ -3676,8 +3070,8 @@ public final class CompletionEngine char[] packageName = receiverType.qualifiedPackageName(); typeImportProposal.setDeclarationSignature(packageName); typeImportProposal.setSignature(getSignature(receiverType)); - typeImportProposal.setPackageName(packageName); - typeImportProposal.setTypeName(receiverType.qualifiedSourceName()); + typeImportProposal.setReturnQualification(packageName); + typeImportProposal.setReturnSimpleName(receiverType.qualifiedSourceName()); typeImportProposal.setCompletion(typeImportCompletion); typeImportProposal.setFlags(receiverType.modifiers); typeImportProposal.setAdditionalFlags(CompletionFlags.Default); @@ -3700,8 +3094,8 @@ public final class CompletionEngine proposal.setSignature(getSignature(field.type)); proposal.setDeclarationPackageName(field.declaringClass.qualifiedPackageName()); proposal.setDeclarationTypeName(field.declaringClass.qualifiedSourceName()); - proposal.setPackageName(field.type.qualifiedPackageName()); - proposal.setTypeName(field.type.qualifiedSourceName()); + proposal.setReturnQualification(field.type.qualifiedPackageName()); + proposal.setReturnSimpleName(field.type.qualifiedSourceName()); proposal.setName(field.name); proposal.setCompletion(completion); proposal.setFlags(field.modifiers); @@ -3715,8 +3109,8 @@ public final class CompletionEngine fieldImportProposal.setSignature(getSignature(field.type)); fieldImportProposal.setDeclarationPackageName(field.declaringClass.qualifiedPackageName()); fieldImportProposal.setDeclarationTypeName(field.declaringClass.qualifiedSourceName()); - fieldImportProposal.setPackageName(field.type.qualifiedPackageName()); - fieldImportProposal.setTypeName(field.type.qualifiedSourceName()); + fieldImportProposal.setReturnQualification(field.type.qualifiedPackageName()); + fieldImportProposal.setReturnSimpleName(field.type.qualifiedSourceName()); fieldImportProposal.setName(field.name); fieldImportProposal.setCompletion(fieldImportCompletion); fieldImportProposal.setFlags(field.modifiers); @@ -4062,7 +3456,6 @@ public final class CompletionEngine SourceTypeBinding typeToIgnore, ObjectVector typesFound) { - ReferenceBinding currentType = receiverType; if (typeName == null) return; @@ -4118,7 +3511,6 @@ public final class CompletionEngine boolean fromStaticImport, ObjectVector typesFound) { - ReferenceBinding currentType = receiverType; if (typeName == null || typeName.length == 0) return; @@ -4205,7 +3597,6 @@ public final class CompletionEngine // Helper method for findMethods(char[], TypeBinding[], ReferenceBinding, Scope, ObjectVector, boolean, boolean, boolean) private void findLocalMethods( char[] methodName, - TypeBinding[] typeArgTypes, TypeBinding[] argTypes, MethodBinding[] methods, int numberMethods, @@ -4229,7 +3620,6 @@ public final class CompletionEngine // No visibility checks can be performed without the scope & invocationSite int methodLength = methodName.length; - int minTypeArgLength = typeArgTypes == null ? 0 : typeArgTypes.length; int minArgLength = argTypes == null ? 0 : argTypes.length; next : for (int f = numberMethods; --f >= 0;) { @@ -4244,9 +3634,6 @@ public final class CompletionEngine !scope.isDefinedInSameUnit(method.declaringClass)) continue next; - //TODO (david) perhaps the relevance of a void method must be lesser than other methods - //if (expectedTypesPtr > -1 && method.returnType == BaseTypes.VoidBinding) continue next; - if (onlyStaticMethods && !method.isStatic()) continue next; if (this.options.checkVisibility @@ -4269,9 +3656,6 @@ public final class CompletionEngine } } - if (minTypeArgLength != 0 && minTypeArgLength != 0) - continue next; - if (minArgLength > method.parameters.length) continue next; @@ -4293,182 +3677,128 @@ public final class CompletionEngine continue next; if (CharOperation.equals(method.selector, otherMethod.selector, true)) { - if (receiverType == otherReceiverType) { - if (lookupEnvironment.methodVerifier().doesMethodOverride(otherMethod, method)) { - continue next; - } - } else { - if (lookupEnvironment.methodVerifier().doesMethodOverride(otherMethod, method)) { - if(receiverType.isAnonymousType()) continue next; - - if(!superCall) { - if(!canBePrefixed) continue next; - - prefixRequired = true; - } - } - } + continue next; } } newMethodsFound.add(new Object[]{method, receiverType}); -// ReferenceBinding superTypeWithSameErasure = (ReferenceBinding)receiverType.findSuperTypeWithSameErasure(method.declaringClass); -// if (method.declaringClass != superTypeWithSameErasure) { -// FunctionBinding[] otherMethods = superTypeWithSameErasure.getMethods(method.selector); -// for (int i = 0; i < otherMethods.length; i++) { -// if(otherMethods[i].original() == method.original()) { -// method = otherMethods[i]; -// } -// } -// } - - int length = method.parameters.length; - char[][] parameterPackageNames = new char[length][]; - char[][] parameterTypeNames = new char[length][]; - - for (int i = 0; i < length; i++) { - TypeBinding type = method.original().parameters[i]; - parameterPackageNames[i] = type.qualifiedPackageName(); - parameterTypeNames[i] = type.qualifiedSourceName(); + // Standard proposal + if(!this.isIgnored(CompletionProposal.METHOD_REF, missingElements != null) && (this.assistNodeInJavadoc & CompletionOnJavadoc.ONLY_INLINE_TAG) == 0) { + this.proposeFunction(method); } - char[][] parameterNames = findMethodParameterNames(method,parameterTypeNames); - - char[] completion = CharOperation.NO_CHAR; + // Javadoc proposal int previousStartPosition = this.startPosition; + if ((this.assistNodeInJavadoc & CompletionOnJavadoc.TEXT) != 0 && !this.requestor.isIgnored(CompletionProposal.JSDOC_METHOD_REF)) { + int length = method.parameters.length; + char[][] parameterTypeNames = new char[length][]; - // Special case for completion in javadoc - if (this.assistNodeInJavadoc > 0) { - Expression receiver = null; - if (invocationSite instanceof CompletionOnJavadocMessageSend) { - CompletionOnJavadocMessageSend msg = (CompletionOnJavadocMessageSend) invocationSite; - receiver = msg.receiver; - } else if (invocationSite instanceof CompletionOnJavadocFieldReference) { - CompletionOnJavadocFieldReference fieldRef = (CompletionOnJavadocFieldReference) invocationSite; - receiver = fieldRef.receiver; - } - if (receiver != null) { - StringBuffer javadocCompletion = new StringBuffer(); - if (receiver.isThis()) { - if ((this.assistNodeInJavadoc & CompletionOnJavadoc.TEXT) != 0) { - javadocCompletion.append('#'); - } - } else if ((this.assistNodeInJavadoc & CompletionOnJavadoc.TEXT) != 0) { - if (receiver instanceof JavadocSingleTypeReference) { - JavadocSingleTypeReference typeRef = (JavadocSingleTypeReference) receiver; - javadocCompletion.append(typeRef.token); - javadocCompletion.append('#'); - } else if (receiver instanceof JavadocQualifiedTypeReference) { - JavadocQualifiedTypeReference typeRef = (JavadocQualifiedTypeReference) receiver; - completion = CharOperation.concat(CharOperation.concatWith(typeRef.tokens, '.'), method.selector, '#'); - for (int t=0,nt =typeRef.tokens.length; t0) javadocCompletion.append('.'); - javadocCompletion.append(typeRef.tokens[t]); + for (int i = 0; i < length; i++) { + //find first none-anonymous parent type + TypeBinding type = method.original().parameters[i]; + while(type != null && type.isAnonymousType() && type instanceof ReferenceBinding) { + type = ((ReferenceBinding)type).getSuperBinding(); + } + + //if ended up with null type, use original + if(type == null) { + type = method.original().parameters[i]; + } + + parameterTypeNames[i] = type.qualifiedSourceName(); + } + + char[] completion = CharOperation.NO_CHAR; + char[][] parameterNames = findMethodParameterNames(method,parameterTypeNames); + + // Special case for completion in javadoc + if (this.assistNodeInJavadoc > 0) { + Expression receiver = null; + if (invocationSite instanceof CompletionOnJavadocMessageSend) { + CompletionOnJavadocMessageSend msg = (CompletionOnJavadocMessageSend) invocationSite; + receiver = msg.receiver; + } else if (invocationSite instanceof CompletionOnJavadocFieldReference) { + CompletionOnJavadocFieldReference fieldRef = (CompletionOnJavadocFieldReference) invocationSite; + receiver = fieldRef.receiver; + } + if (receiver != null) { + StringBuffer javadocCompletion = new StringBuffer(); + if (receiver.isThis()) { + if ((this.assistNodeInJavadoc & CompletionOnJavadoc.TEXT) != 0) { + javadocCompletion.append('#'); + } + } else if ((this.assistNodeInJavadoc & CompletionOnJavadoc.TEXT) != 0) { + if (receiver instanceof JavadocSingleTypeReference) { + JavadocSingleTypeReference typeRef = (JavadocSingleTypeReference) receiver; + javadocCompletion.append(typeRef.token); + javadocCompletion.append('#'); + } else if (receiver instanceof JavadocQualifiedTypeReference) { + JavadocQualifiedTypeReference typeRef = (JavadocQualifiedTypeReference) receiver; + completion = CharOperation.concat(CharOperation.concatWith(typeRef.tokens, '.'), method.selector, '#'); + for (int t=0,nt =typeRef.tokens.length; t0) javadocCompletion.append('.'); + javadocCompletion.append(typeRef.tokens[t]); + } + javadocCompletion.append('#'); } - javadocCompletion.append('#'); } - } - javadocCompletion.append(method.selector); - // Append parameters types - javadocCompletion.append('('); - if (method.parameters != null) { - boolean isVarargs = method.isVarargs(); - for (int p=0, ln=method.parameters.length; p0) javadocCompletion.append(", "); //$NON-NLS-1$ - TypeBinding argTypeBinding = method.parameters[p]; - if (isVarargs && p == ln - 1) { - createVargsType(argTypeBinding, javadocCompletion); - } else { - createType(argTypeBinding, javadocCompletion); + javadocCompletion.append(method.selector); + // Append parameters types + javadocCompletion.append('('); + if (method.parameters != null) { + boolean isVarargs = method.isVarargs(); + for (int p=0, ln=method.parameters.length; p0) javadocCompletion.append(", "); //$NON-NLS-1$ + TypeBinding argTypeBinding = method.parameters[p]; + if (isVarargs && p == ln - 1) { + createVargsType(argTypeBinding, javadocCompletion); + } else { + createType(argTypeBinding, javadocCompletion); + } } } + javadocCompletion.append(')'); + completion = javadocCompletion.toString().toCharArray(); } - javadocCompletion.append(')'); - completion = javadocCompletion.toString().toCharArray(); - } - } else { - // nothing to insert - do not want to replace the existing selector & arguments - if (!exactMatch) { - if (this.source != null - && this.source.length > this.endPosition - && this.source[this.endPosition] == '(') - completion = method.selector; - else - completion = CharOperation.concat(method.selector, new char[] { '(', ')' }); } else { - if(prefixRequired && (this.source != null)) { - completion = CharOperation.subarray(this.source, this.startPosition, this.endPosition); + // nothing to insert - do not want to replace the existing selector & arguments + if (!exactMatch) { + if (this.source != null + && this.source.length > this.endPosition + && this.source[this.endPosition] == '(') + completion = method.selector; + else + completion = CharOperation.concat(method.selector, new char[] { '(', ')' }); } else { - this.startPosition = this.endPosition; + if(prefixRequired && (this.source != null)) { + completion = CharOperation.subarray(this.source, this.startPosition, this.endPosition); + } else { + this.startPosition = this.endPosition; + } } - } - if(prefixRequired || this.options.forceImplicitQualification){ - char[] prefix = computePrefix(scope.enclosingSourceType(), invocationScope.enclosingSourceType(), method.isStatic()); - completion = CharOperation.concat(prefix,completion,'.'); - } - } - - int relevance = computeBaseRelevance(); - relevance += computeRelevanceForResolution(); - relevance += computeRelevanceForInterestingProposal(); - if (methodName != null) relevance += computeRelevanceForCaseMatching(methodName, method.selector); - relevance += computeRelevanceForExpectingType(method.returnType); - relevance += computeRelevanceForStatic(onlyStaticMethods, method.isStatic()); - relevance += computeRelevanceForQualification(prefixRequired); - relevance += computeRelevanceForRestrictions(IAccessRule.K_ACCESSIBLE); - if (onlyStaticMethods && this.insideQualifiedReference) { - relevance += computeRelevanceForInheritance(receiverType, method.declaringClass); - } - if (missingElements != null) { - relevance += computeRelevanceForMissingElements(missingElementsHaveProblems); - } - - this.noProposal = false; - // Standard proposal - if(!this.isIgnored(CompletionProposal.METHOD_REF, missingElements != null) && (this.assistNodeInJavadoc & CompletionOnJavadoc.ONLY_INLINE_TAG) == 0) { - CompletionProposal proposal = this.createProposal(CompletionProposal.METHOD_REF, this.actualCompletionPosition); - proposal.setDeclarationSignature(getSignature(method.declaringClass)); - proposal.setSignature(getSignature(method)); - MethodBinding original = method.original(); - if(original != method) { - proposal.setOriginalSignature(getSignature(original)); + if(prefixRequired || this.options.forceImplicitQualification){ + char[] prefix = computePrefix(scope.enclosingSourceType(), invocationScope.enclosingSourceType(), method.isStatic()); + completion = CharOperation.concat(prefix,completion,'.'); + } } - proposal.setDeclarationPackageName(method.declaringClass.qualifiedPackageName()); - proposal.setDeclarationTypeName(method.declaringClass.qualifiedSourceName()); - proposal.setParameterPackageNames(parameterPackageNames); - proposal.setParameterTypeNames(parameterTypeNames); - proposal.setPackageName(method.returnType.qualifiedPackageName()); - proposal.setTypeName(method.returnType.qualifiedSourceName()); - proposal.setName(method.selector); - proposal.setIsContructor(method.isConstructor()); - if (missingElements != null) { - CompletionProposal[] subProposals = new CompletionProposal[missingElements.length]; - for (int i = 0; i < missingElements.length; i++) { - subProposals[i] = - createRequiredTypeProposal( - missingElements[i], - missingElementsStarts[i], - missingElementsEnds[i], - relevance); - } - proposal.setRequiredProposals(subProposals); + int relevance = computeBaseRelevance(); + relevance += computeRelevanceForResolution(); + relevance += computeRelevanceForInterestingProposal(); + relevance += computeRelevanceForCaseMatching(methodName, method.selector); + relevance += computeRelevanceForExpectingType(method.returnType); + relevance += computeRelevanceForStatic(onlyStaticMethods, method.isStatic()); + relevance += computeRelevanceForQualification(prefixRequired); + relevance += computeRelevanceForRestrictions(IAccessRule.K_ACCESSIBLE); + if (onlyStaticMethods && this.insideQualifiedReference) { + relevance += computeRelevanceForInheritance(receiverType, method.declaringClass); } - proposal.setCompletion(completion); - proposal.setFlags(method.modifiers); - proposal.setReplaceRange(this.startPosition - this.offset, this.endPosition - this.offset); - proposal.setRelevance(relevance); - if(parameterNames != null) proposal.setParameterNames(parameterNames); - this.requestor.accept(proposal); - if(DEBUG) { - this.printDebug(proposal); + if (missingElements != null) { + relevance += computeRelevanceForMissingElements(missingElementsHaveProblems); } - } - - // Javadoc proposal - if ((this.assistNodeInJavadoc & CompletionOnJavadoc.TEXT) != 0 && !this.requestor.isIgnored(CompletionProposal.JSDOC_METHOD_REF)) { + char[] javadocCompletion = inlineTagCompletion(completion, JavadocTagConstants.TAG_LINK); CompletionProposal proposal = this.createProposal(CompletionProposal.JSDOC_METHOD_REF, this.actualCompletionPosition); proposal.setDeclarationSignature(getSignature(method.declaringClass)); @@ -4479,10 +3809,9 @@ public final class CompletionEngine } proposal.setDeclarationPackageName(method.declaringClass.qualifiedPackageName()); proposal.setDeclarationTypeName(method.declaringClass.qualifiedSourceName()); - proposal.setParameterPackageNames(parameterPackageNames); proposal.setParameterTypeNames(parameterTypeNames); - proposal.setPackageName(method.returnType.qualifiedPackageName()); - proposal.setTypeName(method.returnType.qualifiedSourceName()); + proposal.setReturnQualification(method.returnType.qualifiedPackageName()); + proposal.setReturnSimpleName(method.returnType.qualifiedSourceName()); proposal.setName(method.selector); proposal.setCompletion(javadocCompletion); proposal.setFlags(method.modifiers); @@ -4584,12 +3913,10 @@ public final class CompletionEngine } int length = method.parameters.length; - char[][] parameterPackageNames = new char[length][]; char[][] parameterTypeNames = new char[length][]; for (int i = 0; i < length; i++) { TypeBinding type = method.original().parameters[i]; - parameterPackageNames[i] = type.qualifiedPackageName(); parameterTypeNames[i] = type.qualifiedSourceName(); } char[][] parameterNames = findMethodParameterNames(method,parameterTypeNames); @@ -4609,7 +3936,7 @@ public final class CompletionEngine int relevance = computeBaseRelevance(); relevance += computeRelevanceForResolution(); relevance += computeRelevanceForInterestingProposal(); - if (methodName != null) relevance += computeRelevanceForCaseMatching(methodName, method.selector); + relevance += computeRelevanceForCaseMatching(methodName, method.selector); relevance += computeRelevanceForExpectingType(method.returnType); relevance += computeRelevanceForStatic(true, method.isStatic()); relevance += computeRelevanceForQualification(true); @@ -4635,10 +3962,9 @@ public final class CompletionEngine } proposal.setDeclarationPackageName(method.declaringClass.qualifiedPackageName()); proposal.setDeclarationTypeName(method.declaringClass.qualifiedSourceName()); - proposal.setParameterPackageNames(parameterPackageNames); proposal.setParameterTypeNames(parameterTypeNames); - proposal.setPackageName(method.returnType.qualifiedPackageName()); - proposal.setTypeName(method.returnType.qualifiedSourceName()); + proposal.setReturnQualification(method.returnType.qualifiedPackageName()); + proposal.setReturnSimpleName(method.returnType.qualifiedSourceName()); proposal.setName(method.selector); proposal.setCompletion(completion); proposal.setFlags(method.modifiers); @@ -4663,10 +3989,9 @@ public final class CompletionEngine } proposal.setDeclarationPackageName(method.declaringClass.qualifiedPackageName()); proposal.setDeclarationTypeName(method.declaringClass.qualifiedSourceName()); - proposal.setParameterPackageNames(parameterPackageNames); proposal.setParameterTypeNames(parameterTypeNames); - proposal.setPackageName(method.returnType.qualifiedPackageName()); - proposal.setTypeName(method.returnType.qualifiedSourceName()); + proposal.setReturnQualification(method.returnType.qualifiedPackageName()); + proposal.setReturnSimpleName(method.returnType.qualifiedSourceName()); proposal.setName(method.selector); proposal.setCompletion(completion); proposal.setFlags(method.modifiers); @@ -4682,8 +4007,8 @@ public final class CompletionEngine char[] packageName = receiverType.qualifiedPackageName(); typeImportProposal.setDeclarationSignature(packageName); typeImportProposal.setSignature(getSignature(receiverType)); - typeImportProposal.setPackageName(packageName); - typeImportProposal.setTypeName(receiverType.qualifiedSourceName()); + typeImportProposal.setReturnQualification(packageName); + typeImportProposal.setReturnSimpleName(receiverType.qualifiedSourceName()); typeImportProposal.setCompletion(typeImportCompletion); typeImportProposal.setFlags(receiverType.modifiers); typeImportProposal.setAdditionalFlags(CompletionFlags.Default); @@ -4708,10 +4033,9 @@ public final class CompletionEngine } proposal.setDeclarationPackageName(method.declaringClass.qualifiedPackageName()); proposal.setDeclarationTypeName(method.declaringClass.qualifiedSourceName()); - proposal.setParameterPackageNames(parameterPackageNames); proposal.setParameterTypeNames(parameterTypeNames); - proposal.setPackageName(method.returnType.qualifiedPackageName()); - proposal.setTypeName(method.returnType.qualifiedSourceName()); + proposal.setReturnQualification(method.returnType.qualifiedPackageName()); + proposal.setReturnSimpleName(method.returnType.qualifiedSourceName()); proposal.setName(method.selector); proposal.setCompletion(completion); proposal.setFlags(method.modifiers); @@ -4729,10 +4053,9 @@ public final class CompletionEngine } methodImportProposal.setDeclarationPackageName(method.declaringClass.qualifiedPackageName()); methodImportProposal.setDeclarationTypeName(method.declaringClass.qualifiedSourceName()); - methodImportProposal.setParameterPackageNames(parameterPackageNames); methodImportProposal.setParameterTypeNames(parameterTypeNames); - methodImportProposal.setPackageName(method.returnType.qualifiedPackageName()); - methodImportProposal.setTypeName(method.returnType.qualifiedSourceName()); + methodImportProposal.setReturnQualification(method.returnType.qualifiedPackageName()); + methodImportProposal.setReturnSimpleName(method.returnType.qualifiedSourceName()); methodImportProposal.setName(method.selector); methodImportProposal.setCompletion(methodImportCompletion); methodImportProposal.setFlags(method.modifiers); @@ -4767,8 +4090,8 @@ public final class CompletionEngine proposal.completionEngine = this; proposal.setDeclarationSignature(packageName); proposal.setSignature(getSignature(typeBinding)); - proposal.setPackageName(packageName); - proposal.setTypeName(typeName); + proposal.setReturnQualification(packageName); + proposal.setReturnSimpleName(typeName); proposal.setCompletion(fullyQualifiedName); proposal.setFlags(typeBinding.modifiers); proposal.setReplaceRange(start - this.offset, end - this.offset); @@ -4780,7 +4103,7 @@ public final class CompletionEngine proposal = this.createProposal(CompletionProposal.PACKAGE_REF, this.actualCompletionPosition); proposal.setDeclarationSignature(packageName); - proposal.setPackageName(packageName); + proposal.setReturnQualification(packageName); proposal.setCompletion(packageName); proposal.setReplaceRange(start - this.offset, end - this.offset); proposal.setRelevance(relevance); @@ -5014,59 +4337,10 @@ public final class CompletionEngine } newMethodsFound.add(method); - - int length = method.parameters.length; - char[][] parameterPackageNames = new char[length][]; - char[][] parameterFullTypeNames = new char[length][]; - - for (int i = 0; i < length; i++) { - TypeBinding type = method.parameters[i]; - parameterPackageNames[i] = type.qualifiedPackageName(); - parameterFullTypeNames[i] = type.qualifiedSourceName(); - } - - char[][] parameterNames = findMethodParameterNames(method, parameterFullTypeNames); - - StringBuffer completion = new StringBuffer(10); - if (!exactMatch) { - createMethod(method, parameterPackageNames, parameterFullTypeNames, parameterNames, completion); - } - - int relevance = computeBaseRelevance(); - relevance += computeRelevanceForResolution(); - relevance += computeRelevanceForInterestingProposal(); - relevance += computeRelevanceForCaseMatching(methodName, method.selector); - relevance += R_METHOD_OVERIDE; - if(method.isAbstract()) relevance += R_ABSTRACT_METHOD; - relevance += computeRelevanceForRestrictions(IAccessRule.K_ACCESSIBLE); - - this.noProposal = false; + + //propose method if(!this.requestor.isIgnored(CompletionProposal.METHOD_DECLARATION)) { - CompletionProposal proposal = this.createProposal(CompletionProposal.METHOD_DECLARATION, this.actualCompletionPosition); - proposal.setDeclarationSignature(getSignature(method.declaringClass)); - proposal.setDeclarationKey(method.declaringClass.computeUniqueKey()); - proposal.setSignature(getSignature(method)); - MethodBinding original = method.original(); - if(original != method) { - proposal.setOriginalSignature(getSignature(original)); - } - proposal.setKey(method.computeUniqueKey()); - proposal.setDeclarationPackageName(method.declaringClass.qualifiedPackageName()); - proposal.setDeclarationTypeName(method.declaringClass.qualifiedSourceName()); - proposal.setParameterPackageNames(parameterPackageNames); - proposal.setParameterTypeNames(parameterFullTypeNames); - proposal.setPackageName(method.returnType.qualifiedPackageName()); - proposal.setTypeName(method.returnType.qualifiedSourceName()); - proposal.setCompletion(completion.toString().toCharArray()); - proposal.setName(method.selector); - proposal.setFlags(method.modifiers); - proposal.setReplaceRange(this.startPosition - this.offset, this.endPosition - this.offset); - proposal.setRelevance(relevance); - if(parameterNames != null) proposal.setParameterNames(parameterNames); - this.requestor.accept(proposal); - if(DEBUG) { - this.printDebug(proposal); - } + this.proposeFunction(method); } } methodsFound.addAll(newMethodsFound); @@ -5212,7 +4486,7 @@ public final class CompletionEngine if (notInJavadoc) { if (isCompletingDeclaration){ - currentType = receiverType.superclass(); + currentType = receiverType.getSuperBinding(); } } while (currentType != null) { @@ -5230,7 +4504,6 @@ public final class CompletionEngine } else{ findLocalMethods( selector, - typeArgTypes, argTypes, methods, methods.length, @@ -5251,12 +4524,12 @@ public final class CompletionEngine } } - currentType = currentType.superclass(); + currentType = currentType.getSuperBinding(); } } private char[][] findMethodParameterNames(MethodBinding method, char[][] parameterTypeNames){ - TypeBinding erasure = method.declaringClass; + TypeBinding erasure = method.original().declaringClass; if(!(erasure instanceof ReferenceBinding)) return null; char[][] parameterNames = null; @@ -5311,23 +4584,23 @@ public final class CompletionEngine } } } - else - if (sourceType.scope != null){ + else if (sourceType.scope != null) { TypeDeclaration parsedType; AbstractMethodDeclaration methodDecl = null; - if ((parsedType = ((ClassScope)sourceType.scope).referenceContext) != null) - methodDecl = parsedType.declarationOf(method.original()); - else if ( ((ClassScope)sourceType.scope).inferredType != null) - methodDecl = (AbstractMethodDeclaration) ((ClassScope)sourceType.scope).inferredType.declarationOf(method.original()); + if ((parsedType = ((ClassScope)sourceType.scope).referenceContext) != null) { + methodDecl = parsedType.declarationOf(method.original()); + } else if ( ((ClassScope)sourceType.scope).inferredType != null) { + methodDecl = (AbstractMethodDeclaration) ((ClassScope)sourceType.scope).inferredType.declarationOf(method.original()); + } - if (methodDecl != null){ - Argument[] arguments = methodDecl.arguments; - parameterNames = new char[length][]; + if (methodDecl != null){ + Argument[] arguments = methodDecl.arguments; + parameterNames = new char[length][]; - for(int i = 0 ; i < length ; i++){ - parameterNames[i] = arguments[i].name; - } + for(int i = 0 ; i < length ; i++){ + parameterNames[i] = arguments[i].name; } + } } } // look into the model @@ -5594,8 +4867,8 @@ public final class CompletionEngine //search index for constructors that match this.nameEnvironment.findConstructorDeclarations( token, + this.options.camelCaseMatch, this); - acceptConstructors(); } else if (proposeType) { int searchFor = IJavaScriptSearchConstants.TYPE; if(this.assistNodeIsClass) { @@ -5729,8 +5002,9 @@ public final class CompletionEngine boolean insideTypeAnnotation, boolean insideAnnotationAttribute) { - if (token == null) + if (token == null) { return; + } // Should local variables hide fields from the receiver type or any of its enclosing types? // we know its an implicit field/method access... see BlockScope getBinding/getImplicitMethod @@ -5745,54 +5019,67 @@ public final class CompletionEngine Scope currentScope = scope; - if (!this.requestor.isIgnored(CompletionProposal.LOCAL_VARIABLE_REF)) { - done1 : while (true) { // done when a COMPILATION_UNIT_SCOPE is found - LocalVariableBinding arguments = null; - switch (currentScope.kind) { + //loop up the scopes looking for locally defined variables + done1 : while (true) { // done when a COMPILATION_UNIT_SCOPE is found + LocalVariableBinding arguments = null; + switch (currentScope.kind) { - case Scope.METHOD_SCOPE : - // handle the error case inside an explicit constructor call (see MethodScope>>findField) - MethodScope methodScope = (MethodScope) currentScope; - staticsOnly |= methodScope.isStatic | methodScope.isConstructorCall; - arguments = methodScope.argumentsBinding; + case Scope.METHOD_SCOPE : + // handle the error case inside an explicit constructor call (see MethodScope>>findField) + MethodScope methodScope = (MethodScope) currentScope; + staticsOnly |= methodScope.isStatic | methodScope.isConstructorCall; + arguments = methodScope.argumentsBinding; - case Scope.BLOCK_SCOPE : - case Scope.COMPILATION_UNIT_SCOPE : - BlockScope blockScope = (BlockScope) currentScope; - LocalVariableBinding[] localBindings = null; - if(arguments != null) { - localBindings = new LocalVariableBinding[blockScope.locals.length + 1]; - System.arraycopy(blockScope.locals, 0, localBindings, 1, blockScope.locals.length); - localBindings[0] = arguments; - } else { - localBindings = blockScope.locals; - } + //$FALL-THROUGH$ + case Scope.BLOCK_SCOPE : + case Scope.COMPILATION_UNIT_SCOPE : { + BlockScope blockScope = (BlockScope) currentScope; + LocalVariableBinding[] localBindings = null; + if(arguments != null) { + localBindings = new LocalVariableBinding[blockScope.locals.length + 1]; + System.arraycopy(blockScope.locals, 0, localBindings, 1, blockScope.locals.length); + localBindings[0] = arguments; + } else { + localBindings = blockScope.locals; + } + + next : for (int i = 0, length = localBindings.length; i < length; i++) { + LocalVariableBinding local = localBindings[i]; + + if (local == null) + break next; - next : for (int i = 0, length = localBindings.length; i < length; i++) { - LocalVariableBinding local = localBindings[i]; - if (local == null) - break next; - + if (tokenLength > local.name.length) + continue next; - if (tokenLength > local.name.length) - continue next; + if (!CharOperation.prefixEquals(token, local.name, false /* ignore case */) + && !(this.options.camelCaseMatch && CharOperation.camelCaseMatch(token, local.name))) + continue next; - if (!CharOperation.prefixEquals(token, local.name, false /* ignore case */) - && !(this.options.camelCaseMatch && CharOperation.camelCaseMatch(token, local.name))) - continue next; + if (local.isSecret()) + continue next; - if (local.isSecret()) + for (int f = 0; f < localsFound.size; f++) { + LocalVariableBinding otherLocal = + (LocalVariableBinding) localsFound.elementAt(f); + if (CharOperation.equals(otherLocal.name, local.name, true)) continue next; - - for (int f = 0; f < localsFound.size; f++) { - LocalVariableBinding otherLocal = - (LocalVariableBinding) localsFound.elementAt(f); - if (CharOperation.equals(otherLocal.name, local.name, true)) - continue next; - } - localsFound.add(local); - + } + localsFound.add(local); + + /* if completion unit then field completion + * else local completion + */ + int proposalKind; + if(currentScope.kind == Scope.COMPILATION_UNIT_SCOPE) { + proposalKind = CompletionProposal.FIELD_REF; + } else { + proposalKind = CompletionProposal.LOCAL_VARIABLE_REF; + } + + //if kind is not ingored then make proposal + if(!this.requestor.isIgnored(proposalKind)) { int relevance = computeBaseRelevance(); relevance += computeRelevanceForResolution(); relevance += computeRelevanceForInterestingProposal(local); @@ -5801,40 +5088,45 @@ public final class CompletionEngine relevance += computeRelevanceForQualification(false); relevance += computeRelevanceForRestrictions(IAccessRule.K_ACCESSIBLE); // no access restriction for local variable this.noProposal = false; - if(!this.requestor.isIgnored(CompletionProposal.LOCAL_VARIABLE_REF)) { - CompletionProposal proposal = this.createProposal(CompletionProposal.LOCAL_VARIABLE_REF, this.actualCompletionPosition); - proposal.setSignature( - local.type == null - ? createTypeSignature( - CharOperation.NO_CHAR, - local.declaration.getTypeName().toCharArray()) - : getSignature(local.type)); - if(local.type == null) { - //proposal.setPackageName(null); - proposal.setTypeName(local.declaration.getTypeName().toCharArray()); - } else { - proposal.setPackageName(local.type.qualifiedPackageName()); - proposal.setTypeName(local.type.qualifiedSourceName()); - } - proposal.setName(local.name); - proposal.setCompletion(local.name); - proposal.setFlags(local.modifiers); - proposal.setReplaceRange(this.startPosition - this.offset, this.endPosition - this.offset); - proposal.setRelevance(relevance); - this.requestor.accept(proposal); - if(DEBUG) { - this.printDebug(proposal); - } + + CompletionProposal proposal = this.createProposal(proposalKind, this.actualCompletionPosition); + proposal.setSignature( + local.type == null + ? createTypeSignature( + CharOperation.NO_CHAR, + local.declaration.getTypeName().toCharArray()) + : local.type.qualifiedSourceName()); + if(local.type == null) { + proposal.setReturnSimpleName(local.declaration.getTypeName().toCharArray()); + } else { + proposal.setReturnQualification(local.type.qualifiedPackageName()); + proposal.setReturnSimpleName(local.type.qualifiedSourceName()); + } + + //only in the global scope if variable defined at compilation unit level + if(currentScope.kind == Scope.COMPILATION_UNIT_SCOPE) { + proposal.setDeclarationTypeName(IIndexConstants.GLOBAL_SYMBOL); + } + proposal.setName(local.name); + proposal.setCompletion(local.name); + proposal.setFlags(local.modifiers); + proposal.setReplaceRange(this.startPosition - this.offset, this.endPosition - this.offset); + proposal.setRelevance(relevance); + this.requestor.accept(proposal); + if(DEBUG) { + this.printDebug(proposal); } } - - if (currentScope.kind==Scope.COMPILATION_UNIT_SCOPE ) - break done1; - else - break; + } + + if (currentScope.kind==Scope.COMPILATION_UNIT_SCOPE ) { + break done1; + } else { + break; + } } - currentScope = currentScope.parent; } + currentScope = currentScope.parent; } boolean proposeField = !this.requestor.isIgnored(CompletionProposal.FIELD_REF); @@ -5856,7 +5148,6 @@ public final class CompletionEngine findLocalMethods( token, null, - null, methodScope.methods, methodScope.numberMethods, currentScope, @@ -5873,20 +5164,11 @@ public final class CompletionEngine null, null, false); - - } break; -// case Scope.CLASS_SCOPE : case Scope.COMPILATION_UNIT_SCOPE : CompilationUnitScope compilationUnitScope = (CompilationUnitScope) currentScope; -// ClassScope classScope = (ClassScope) currentScope; SourceTypeBinding enclosingType = compilationUnitScope.enclosingCompilationUnit(); - /* if (tokenLength == 0) { // only search inside the type itself if no prefix was provided - findFields(token, enclosingType.fields(), classScope, fieldsFound, staticsOnly); - findMethods(token, enclosingType.methods(), classScope, methodsFound, staticsOnly, false); - break done; - } else { */ if(!insideTypeAnnotation) { if(proposeField) { findFields( @@ -5929,10 +5211,6 @@ public final class CompletionEngine } staticsOnly |= enclosingType.isStatic(); insideTypeAnnotation = false; - // } -// break; - -// case Scope.COMPILATION_UNIT_SCOPE : break done2; } currentScope = currentScope.parent; @@ -5951,25 +5229,33 @@ public final class CompletionEngine } //propose methods from environment if token length is not 0 - if (proposeMethod && token.length > 0) - { - this.nameEnvironment.findBindings( + + //String superTypeName = this.unitScope.referenceContext.compilationResult.compilationUnit.getCommonSuperType().getSuperTypeName(); + + //ArrayList superTypes = this.nameEnvironment.findSuperTypes(superTypeName.toCharArray()); + //char[][] searchInTypes = new char[superTypes.size() + 2][]; + char[][] searchInTypes = new char[1][]; + //searchInTypes[0] = superTypeName.toCharArray(); + searchInTypes[0] = IIndexConstants.GLOBAL_SYMBOL; +// for(int i = 0; i < superTypes.size(); i++) { +// searchInTypes[i+2] = (char[]) superTypes.get(i); +// } + + if (proposeMethod) { + this.nameEnvironment.findFunctions( token, - Binding.METHOD, + searchInTypes, this.options.camelCaseMatch, this); - acceptBindings(token,false,false); } //propose fields from environment if token length is not 0 - if (proposeField && token.length > 0) - { - this.nameEnvironment.findBindings( + if (proposeField) { + this.nameEnvironment.findVariables( token, - Binding.VARIABLE, + searchInTypes, this.options.camelCaseMatch, this); - acceptBindings(token,false,false); } } } @@ -5998,8 +5284,8 @@ public final class CompletionEngine if(!CompletionEngine.this.requestor.isIgnored(CompletionProposal.VARIABLE_DECLARATION)) { CompletionProposal proposal = CompletionEngine.this.createProposal(CompletionProposal.VARIABLE_DECLARATION, CompletionEngine.this.actualCompletionPosition); proposal.setSignature(getSignature(type.resolvedType)); - proposal.setPackageName(type.resolvedType.qualifiedPackageName()); - proposal.setTypeName(type.resolvedType.qualifiedSourceName()); + proposal.setReturnQualification(type.resolvedType.qualifiedPackageName()); + proposal.setReturnSimpleName(type.resolvedType.qualifiedSourceName()); proposal.setName(name); proposal.setCompletion(name); //proposal.setFlags(Flags.AccDefault); @@ -6058,147 +5344,20 @@ public final class CompletionEngine return null; } - private char[][] findUnresolvedReferenceAfter(int from, BlockScope scope, final char[][] discouragedNames) { - final ArrayList proposedNames = new ArrayList(); - - UnresolvedReferenceNameFinder.UnresolvedReferenceNameRequestor nameRequestor = - new UnresolvedReferenceNameFinder.UnresolvedReferenceNameRequestor() { - public void acceptName(char[] name) { - CompletionEngine.this.acceptUnresolvedName(name); - proposedNames.add(name); - } - }; - - ReferenceContext referenceContext = scope.referenceContext(); - if (referenceContext instanceof AbstractMethodDeclaration) { - AbstractMethodDeclaration md = (AbstractMethodDeclaration)referenceContext; - - UnresolvedReferenceNameFinder nameFinder = new UnresolvedReferenceNameFinder(this); - nameFinder.findAfter( - completionToken, - md.scope, - md.scope.classScope(), - from, - md.bodyEnd, - discouragedNames, - nameRequestor); - } else if (referenceContext instanceof TypeDeclaration) { - TypeDeclaration typeDeclaration = (TypeDeclaration) referenceContext; - FieldDeclaration[] fields = typeDeclaration.fields; - if (fields != null) { - done : for (int i = 0; i < fields.length; i++) { - if (fields[i] instanceof Initializer) { - Initializer initializer = (Initializer) fields[i]; - if (initializer.block.sourceStart <= from && - from < initializer.bodyEnd) { - UnresolvedReferenceNameFinder nameFinder = new UnresolvedReferenceNameFinder(this); - nameFinder.findAfter( - completionToken, - typeDeclaration.scope, - typeDeclaration.scope, - from, - initializer.bodyEnd, - discouragedNames, - nameRequestor); - break done; - } - } - } - } - } - - int proposedNamesCount = proposedNames.size(); - if (proposedNamesCount > 0) { - return (char[][])proposedNames.toArray(new char[proposedNamesCount][]); - } - - return null; - } - - private void findUnresolvedReference(int completedNameStart, int completedNameEnd, BlockScope scope, char[][] discouragedNames) { - char[][] foundNames = findUnresolvedReferenceBefore(completedNameStart - 1, completedNameEnd, scope, discouragedNames); - if (foundNames != null && foundNames.length > 1) { - int discouragedNamesLength = discouragedNames.length; - int foundNamesLength = foundNames.length; - int newLength = discouragedNamesLength + foundNamesLength; - System.arraycopy(discouragedNames, 0, discouragedNames = new char[newLength][], 0, discouragedNamesLength); - System.arraycopy(foundNames, 0, discouragedNames, discouragedNamesLength, foundNamesLength); - } - findUnresolvedReferenceAfter(completedNameEnd + 1, scope, discouragedNames); - } - - private char[][] findUnresolvedReferenceBefore(int recordTo, int parseTo, BlockScope scope, final char[][] discouragedNames) { - final ArrayList proposedNames = new ArrayList(); - - UnresolvedReferenceNameFinder.UnresolvedReferenceNameRequestor nameRequestor = - new UnresolvedReferenceNameFinder.UnresolvedReferenceNameRequestor() { - public void acceptName(char[] name) { - CompletionEngine.this.acceptUnresolvedName(name); - proposedNames.add(name); - } - }; - - BlockScope upperScope = scope; - while (upperScope.enclosingMethodScope() != null && upperScope.enclosingMethodScope()!=upperScope) { - upperScope = upperScope.enclosingMethodScope(); - } - if (upperScope.enclosingMethodScope()==null) - upperScope=scope.compilationUnitScope(); - - ReferenceContext referenceContext = upperScope.referenceContext(); - if (referenceContext instanceof AbstractMethodDeclaration) { - AbstractMethodDeclaration md = (AbstractMethodDeclaration)referenceContext; - - UnresolvedReferenceNameFinder nameFinder = new UnresolvedReferenceNameFinder(this); - nameFinder.findBefore( - completionToken, - md.scope, - md.scope.classScope(), - md.bodyStart, - recordTo, - parseTo, - discouragedNames, - nameRequestor); - } else if (referenceContext instanceof TypeDeclaration) { - TypeDeclaration typeDeclaration = (TypeDeclaration) referenceContext; - - - done : { - FieldDeclaration[] fields = typeDeclaration.fields; - if (fields != null) { - for (int i = 0; i < fields.length; i++) { - if (fields[i] instanceof Initializer) { - Initializer initializer = (Initializer) fields[i]; - if (initializer.block.sourceStart <= recordTo && - recordTo < initializer.bodyEnd) { - - UnresolvedReferenceNameFinder nameFinder = new UnresolvedReferenceNameFinder(this); - nameFinder.findBefore( - completionToken, - typeDeclaration.scope, - typeDeclaration.scope, - initializer.block.sourceStart, - recordTo, - parseTo, - discouragedNames, - nameRequestor); - break done; - } - } - } - } - } - } - - int proposedNamesCount = proposedNames.size(); - if (proposedNamesCount > 0) { - return (char[][])proposedNames.toArray(new char[proposedNamesCount][]); - } - - return null; - } - - // Helper method for private void findVariableNames(char[] name, TypeReference type ) + /** + * Helper method for private void findVariableNames(char[] name, TypeReference type ) + * + * @param token + * @param qualifiedPackageName + * @param qualifiedSourceName + * @param sourceName + * @param typeBinding + * @param discouragedNames + * @param forbiddenNames + * @param dim + * @param kind + * @param modifiers + */ private void findVariableName( char[] token, char[] qualifiedPackageName, @@ -6268,8 +5427,8 @@ public final class CompletionEngine if(!CompletionEngine.this.requestor.isIgnored(CompletionProposal.VARIABLE_DECLARATION)) { CompletionProposal proposal = CompletionEngine.this.createProposal(CompletionProposal.VARIABLE_DECLARATION, CompletionEngine.this.actualCompletionPosition); proposal.setSignature(getSignature(typeBinding)); - proposal.setPackageName(q); - proposal.setTypeName(displayName); + proposal.setReturnQualification(q); + proposal.setReturnSimpleName(displayName); proposal.setName(name); proposal.setCompletion(name); //proposal.setFlags(Flags.AccDefault); @@ -6383,8 +5542,6 @@ public final class CompletionEngine } } - boolean isStatic = true; - ImportReference importReference = new ImportReference( compoundName, @@ -6429,15 +5586,15 @@ public final class CompletionEngine private void setSourceRange(int start, int end, boolean emptyTokenAdjstment) { this.startPosition = start; - if (emptyTokenAdjstment) { - int endOfEmptyToken = ((CompletionScanner) this.parser.scanner).endOfEmptyToken; + if(emptyTokenAdjstment) { + int endOfEmptyToken = ((CompletionScanner)this.parser.scanner).endOfEmptyToken; if (end == 0) { this.endPosition = 0; } - else { + else this.endPosition = endOfEmptyToken > end ? endOfEmptyToken + 1 : end + 1; - } - } + } + else { this.endPosition = end + 1; } @@ -6460,6 +5617,7 @@ public final class CompletionEngine MethodScope methodScope = (MethodScope) currentScope; staticsOnly |= methodScope.isStatic | methodScope.isConstructorCall; + //$FALL-THROUGH$ - fall through is done on purpose case Scope.BLOCK_SCOPE : BlockScope blockScope = (BlockScope) currentScope; @@ -6518,7 +5676,7 @@ public final class CompletionEngine invocationSite, result); } - currentType = currentType.superclass(); + currentType = currentType.getSuperBinding(); } while ( currentType != null); } @@ -6575,7 +5733,7 @@ public final class CompletionEngine } } else if(parent instanceof ReturnStatement) { if(scope.methodScope().referenceContext instanceof AbstractMethodDeclaration) { - MethodBinding methodBinding = ((AbstractMethodDeclaration) scope.methodScope().referenceContext).binding; + MethodBinding methodBinding = ((AbstractMethodDeclaration) scope.methodScope().referenceContext).getBinding(); TypeBinding binding = methodBinding == null ? null : methodBinding.returnType; if(binding != null) { addExpectedType(binding, scope); @@ -6597,7 +5755,7 @@ public final class CompletionEngine scope, messageSend, isStatic); - binding = binding.superclass(); + binding = binding.getSuperBinding(); } } } else if(parent instanceof AllocationExpression) { @@ -6644,13 +5802,6 @@ public final class CompletionEngine addExpectedType(TypeBinding.ANY, scope); break; } - BinaryExpression binaryExpression = (BinaryExpression) parent; - if(operator == OperatorIds.LESS) { - if(binaryExpression.left instanceof SingleNameReference){ - SingleNameReference name = (SingleNameReference) binaryExpression.left; - Binding b = scope.getBinding(name.token, Binding.VARIABLE | Binding.TYPE, name, false); - } - } } else if(parent instanceof UnaryExpression) { switch(operator) { case OperatorIds.NOT : @@ -6897,7 +6048,7 @@ public final class CompletionEngine proposal.setDeclarationTypeName(reference.qualifiedSourceName()); //proposal.setPackageName(null); - proposal.setTypeName(VOID); + proposal.setReturnSimpleName(VOID); proposal.setName(token); //proposal.setParameterPackageNames(null); //proposal.setParameterTypeNames(null); @@ -6942,11 +6093,6 @@ public final class CompletionEngine int length = name.length; for (int i = length -1; i >= 0; i--) { switch (name[i]) { - case '.': - if (depth == 0 && name[i - 1] != '>') { - name[i] = '$'; - } - break; case '<': depth--; break; @@ -6968,7 +6114,7 @@ public final class CompletionEngine : Signature.createCharArrayTypeSignature( CharOperation.concat( returnPackagename, - CharOperation.replaceOnCopy(returnTypeName, '.', '$'), '.'), true); + returnTypeName, '.'), true); return createMethodSignature( parameterPackageNames, @@ -6983,7 +6129,7 @@ public final class CompletionEngine Signature.createCharArrayTypeSignature( CharOperation.concat( parameterPackageNames[i], - CharOperation.replaceOnCopy(parameterTypeNames[i], '.', '$'), '.'), true); + parameterTypeNames[i], '.'), true); } return Signature.createMethodSignature( @@ -7010,8 +6156,8 @@ public final class CompletionEngine proposal.completionEngine = this; proposal.setDeclarationSignature(packageName); proposal.setSignature(createNonGenericTypeSignature(typeName)); - proposal.setPackageName(packageName); - proposal.setTypeName(typeName); + proposal.setReturnQualification(packageName); + proposal.setReturnSimpleName(typeName); proposal.setCompletion(completionName); proposal.setFlags(modifiers); proposal.setReplaceRange(this.startPosition - this.offset, this.endPosition - this.offset); @@ -7031,8 +6177,8 @@ public final class CompletionEngine proposal.completionEngine = this; proposal.setDeclarationSignature(packageName); proposal.setSignature(createNonGenericTypeSignature(typeName)); - proposal.setPackageName(packageName); - proposal.setTypeName(typeName); + proposal.setReturnQualification(packageName); + proposal.setReturnSimpleName(typeName); proposal.setCompletion(javadocCompletion); proposal.setFlags(modifiers); int start = (this.assistNodeInJavadoc & CompletionOnJavadoc.REPLACE_TAG) != 0 ? this.javadocTagPosition : this.startPosition; @@ -7058,8 +6204,8 @@ public final class CompletionEngine proposal.completionEngine = this; proposal.setDeclarationSignature(refBinding.qualifiedPackageName()); proposal.setSignature(getSignature(refBinding)); - proposal.setPackageName(refBinding.qualifiedPackageName()); - proposal.setTypeName(typeName); + proposal.setReturnQualification(refBinding.qualifiedPackageName()); + proposal.setReturnSimpleName(typeName); proposal.setCompletion(completionName); proposal.setFlags(refBinding.modifiers); proposal.setReplaceRange(this.startPosition - this.offset, this.endPosition - this.offset); @@ -7078,8 +6224,8 @@ public final class CompletionEngine proposal.completionEngine = this; proposal.setDeclarationSignature(refBinding.qualifiedPackageName()); proposal.setSignature(getSignature(refBinding)); - proposal.setPackageName(refBinding.qualifiedPackageName()); - proposal.setTypeName(typeName); + proposal.setReturnQualification(refBinding.qualifiedPackageName()); + proposal.setReturnSimpleName(typeName); proposal.setCompletion(javadocCompletion); proposal.setFlags(refBinding.modifiers); int start = (this.assistNodeInJavadoc & CompletionOnJavadoc.REPLACE_TAG) != 0 ? this.javadocTagPosition : this.startPosition; @@ -7272,9 +6418,9 @@ public final class CompletionEngine while (typeBinding != null && typeBinding.isAnonymousType()) { // why not just use ReferenceBinding here? if (typeBinding instanceof SourceTypeBinding) - typeBinding = ((SourceTypeBinding) typeBinding).superclass(); + typeBinding = ((SourceTypeBinding) typeBinding).getSuperBinding(); else if (typeBinding instanceof BinaryTypeBinding) - typeBinding = ((BinaryTypeBinding) typeBinding).superclass(); + typeBinding = ((BinaryTypeBinding) typeBinding).getSuperBinding(); // must avoid endless loop else typeBinding = null; @@ -7360,223 +6506,494 @@ public final class CompletionEngine } } - typesFound.add(refBinding); - - boolean inSameUnit = this.unitScope.isDefinedInSameUnit(refBinding); - - // top level types of the current unit are already proposed. - if(!inSameUnit || (inSameUnit && refBinding.isMemberType())) { - char[] packageName = refBinding.qualifiedPackageName(); - char[] typeName = refBinding.sourceName(); - char[] completionName = typeName; - - boolean isQualified = false; - if (!this.insideQualifiedReference && !refBinding.isMemberType()) { - if (mustQualifyType(packageName, typeName, null, refBinding.modifiers)) { - if (packageName == null || packageName.length == 0) - if (this.unitScope != null && this.unitScope.fPackage.compoundName != CharOperation.NO_CHAR_CHAR) - continue next; // ignore types from the default package from outside it - completionName = CharOperation.concat(packageName, typeName, '.'); - isQualified = true; - } - } - - if(this.assistNodeIsClass) { - if(!refBinding.isClass()) continue next; - } - - int relevance = computeBaseRelevance(); - relevance += computeRelevanceForResolution(); - relevance += computeRelevanceForInterestingProposal(); - relevance += computeRelevanceForCaseMatching(token, typeName); - relevance += computeRelevanceForExpectingType(refBinding); - relevance += computeRelevanceForQualification(isQualified); - relevance += computeRelevanceForRestrictions(accessibility); - - if(refBinding.isClass()) { - relevance += computeRelevanceForClass(); - relevance += computeRelevanceForException(typeName); - } - - if (proposeType && !this.assistNodeIsConstructor) { - this.noProposal = false; - if(!this.requestor.isIgnored(CompletionProposal.TYPE_REF)) { - CompletionProposal proposal = createProposal(CompletionProposal.TYPE_REF, this.actualCompletionPosition); - proposal.setDeclarationSignature(packageName); - proposal.setSignature(getSignature(refBinding)); - proposal.setPackageName(packageName); - proposal.setTypeName(typeName); - proposal.setCompletion(completionName); - proposal.setFlags(refBinding.modifiers); - proposal.setReplaceRange(this.startPosition - this.offset, this.endPosition - this.offset); - proposal.setRelevance(relevance); - proposal.setAccessibility(accessibility); - this.requestor.accept(proposal); - if(DEBUG) { - this.printDebug(proposal); - } - } - } - - if (proposeConstructor) { - findConstructors( - refBinding, - null, - scope, - FakeInvocationSite, - isQualified); - } + typesFound.add(refBinding); + + boolean inSameUnit = this.unitScope.isDefinedInSameUnit(refBinding); + + // top level types of the current unit are already proposed. + if(!inSameUnit || (inSameUnit && refBinding.isMemberType())) { + char[] packageName = refBinding.qualifiedPackageName(); + char[] typeName = refBinding.sourceName(); + char[] completionName = typeName; + + boolean isQualified = false; + if (!this.insideQualifiedReference && !refBinding.isMemberType()) { + if (mustQualifyType(packageName, typeName, null, refBinding.modifiers)) { + if (packageName == null || packageName.length == 0) + if (this.unitScope != null && this.unitScope.fPackage.compoundName != CharOperation.NO_CHAR_CHAR) + continue next; // ignore types from the default package from outside it + completionName = CharOperation.concat(packageName, typeName, '.'); + isQualified = true; + } + } + + if(this.assistNodeIsClass) { + if(!refBinding.isClass()) continue next; + } + + int relevance = computeBaseRelevance(); + relevance += computeRelevanceForResolution(); + relevance += computeRelevanceForInterestingProposal(); + relevance += computeRelevanceForCaseMatching(token, typeName); + relevance += computeRelevanceForExpectingType(refBinding); + relevance += computeRelevanceForQualification(isQualified); + relevance += computeRelevanceForRestrictions(accessibility); + + if(refBinding.isClass()) { + relevance += computeRelevanceForClass(); + relevance += computeRelevanceForException(typeName); + } + + if (proposeType && !this.assistNodeIsConstructor) { + this.noProposal = false; + if(!this.requestor.isIgnored(CompletionProposal.TYPE_REF)) { + CompletionProposal proposal = createProposal(CompletionProposal.TYPE_REF, this.actualCompletionPosition); + proposal.setDeclarationSignature(packageName); + proposal.setSignature(getSignature(refBinding)); + proposal.setReturnQualification(packageName); + proposal.setReturnSimpleName(typeName); + proposal.setCompletion(completionName); + proposal.setFlags(refBinding.modifiers); + proposal.setReplaceRange(this.startPosition - this.offset, this.endPosition - this.offset); + proposal.setRelevance(relevance); + proposal.setAccessibility(accessibility); + this.requestor.accept(proposal); + if(DEBUG) { + this.printDebug(proposal); + } + } + } + + if (proposeConstructor) { + findConstructors( + refBinding, + null, + scope, + FakeInvocationSite, + isQualified); + } + } + } + } + } + } + + /** + *

Create a constructor proposal based on the given information.

+ * + * @param typeName Name of the type the constructor is for + * @param parameterTypes Type names of the parameters, should be same length as parameterCount + * @param parameterNames Type names of the parameters, should be same length as parameterCount + * @param modifiers Type names of the parameters, should be same length as parameterCount + * @param accessibility Accessibility of the constructor + * + * @see Flags + * @see IAccessRule + */ + private void proposeConstructor( + char[] typeName, + char[][] parameterTypes, + char[][] parameterNames, + int modifiers, + int accessibility) { + + int relevance = computeBaseRelevance(); + relevance += computeRelevanceForResolution(); + relevance += computeRelevanceForInterestingProposal(); + relevance += computeRelevanceForRestrictions(accessibility); + relevance += computeRelevanceForCaseMatching(this.completionToken, typeName); + relevance += computeRelevanceForClass(); + relevance += computeRelevanceForException(typeName); + + char[] completion; + if (this.source != null + && this.source.length > this.endPosition + && this.source[this.endPosition] == '(') { + completion = CharOperation.NO_CHAR; + } else { + completion = new char[] { '(', ')' }; + } + + //NOTE: currently all constructors are assumed to be public + int flags = modifiers; + flags |= Flags.AccPublic; + + switch (parameterNames.length) { + case -1: {// default constructor + flags = Flags.AccPublic; + this.noProposal = false; + if(!isIgnored(CompletionProposal.CONSTRUCTOR_INVOCATION, CompletionProposal.TYPE_REF)) { + CompletionProposal proposal = createProposal(CompletionProposal.CONSTRUCTOR_INVOCATION, this.actualCompletionPosition); + proposal.setDeclarationSignature(createNonGenericTypeSignature(typeName)); + proposal.setDeclarationTypeName(typeName); + proposal.setParameterTypeNames(CharOperation.NO_CHAR_CHAR); + proposal.setParameterNames(CharOperation.NO_CHAR_CHAR); + proposal.setName(typeName); + proposal.setIsContructor(true); + proposal.setCompletion(completion); + proposal.setFlags(flags); + proposal.setReplaceRange(this.startPosition - this.offset, this.endPosition - this.offset); + proposal.setRelevance(relevance); + this.requestor.accept(proposal); + } + break; + } + case 0: {// constructor with no parameter + this.noProposal = false; + if(!isIgnored(CompletionProposal.CONSTRUCTOR_INVOCATION, CompletionProposal.TYPE_REF)) { + CompletionProposal proposal = createProposal(CompletionProposal.CONSTRUCTOR_INVOCATION, this.actualCompletionPosition); + proposal.setDeclarationSignature(createNonGenericTypeSignature(typeName)); + proposal.setDeclarationTypeName(typeName); + proposal.setParameterTypeNames(CharOperation.NO_CHAR_CHAR); + proposal.setParameterNames(CharOperation.NO_CHAR_CHAR); + proposal.setName(typeName); + proposal.setIsContructor(true); + proposal.setCompletion(completion); + proposal.setFlags(flags); + proposal.setReplaceRange(this.startPosition - this.offset, this.endPosition - this.offset); + proposal.setRelevance(relevance); + this.requestor.accept(proposal); + + } + break; + } + default: {// constructor with parameter + this.noProposal = false; + if(!isIgnored(CompletionProposal.CONSTRUCTOR_INVOCATION, CompletionProposal.TYPE_REF)) { + CompletionProposal proposal = createProposal(CompletionProposal.CONSTRUCTOR_INVOCATION, this.actualCompletionPosition); + proposal.setDeclarationSignature(createNonGenericTypeSignature(typeName)); + proposal.setDeclarationTypeName(typeName); + if(parameterTypes != null) { + proposal.setParameterTypeNames(parameterTypes); } + proposal.setParameterNames(parameterNames); + proposal.setName(typeName); + proposal.setIsContructor(true); + proposal.setCompletion(completion); + proposal.setFlags(flags); + proposal.setReplaceRange(this.startPosition - this.offset, this.endPosition - this.offset); + proposal.setRelevance(relevance); + + this.requestor.accept(proposal); } + break; } } } - - private char[] getResolvedSignature(char[][] parameterTypes, char[] fullyQualifiedTypeName, int parameterCount, Scope scope) { - char[][] cn = CharOperation.splitOn('.', fullyQualifiedTypeName); - TypeReference ref; - if (cn.length == 1) { - ref = new SingleTypeReference(cn[0], 0); + private void proposeType(char[] packageName, char[] simpleTypeName, int modifiers, int accessibility, char[] typeName, char[] fullyQualifiedName, boolean isQualified, Scope scope) { + char[] completionName = fullyQualifiedName; + if(isQualified) { + if (packageName == null || packageName.length == 0) + if (this.unitScope != null && this.unitScope.getDefaultPackage().compoundName != CharOperation.NO_CHAR_CHAR) + return; // ignore types from the default package from outside it } else { - ref = new QualifiedTypeReference(cn,new long[cn.length]); + completionName = simpleTypeName; } + + int relevance = computeBaseRelevance(); + relevance += computeRelevanceForResolution(); + relevance += computeRelevanceForInterestingProposal(); + relevance += computeRelevanceForRestrictions(accessibility); + relevance += computeRelevanceForCaseMatching(this.completionToken, simpleTypeName); + relevance += computeRelevanceForExpectingType(packageName, simpleTypeName); + relevance += computeRelevanceForQualification(isQualified); + relevance += computeRelevanceForClass(); + relevance += computeRelevanceForException(simpleTypeName); + relevance += computeRelevanceForName(simpleTypeName); - TypeBinding guessedType = null; - switch (scope.kind) { - case Scope.COMPILATION_UNIT_SCOPE: - case Scope.METHOD_SCOPE : - case Scope.BLOCK_SCOPE : - guessedType = ref.resolveType((BlockScope)scope); - break; - case Scope.CLASS_SCOPE : - guessedType = ref.resolveType((ClassScope)scope); - break; + + // put proposals that have '_' at the start of their final segment down the list + char[] lastSegment = CharOperation.lastSegment(completionName, '.'); + if(CharOperation.indexOf('_', lastSegment) == 0) { + relevance--; + } + this.noProposal = false; + if(!this.requestor.isIgnored(CompletionProposal.TYPE_REF)) { + createTypeProposal(packageName, typeName, modifiers, accessibility, completionName, relevance); } + } - - if (guessedType != null && guessedType.isValidBinding()) { - if (guessedType instanceof SourceTypeBinding) { - SourceTypeBinding refBinding = (SourceTypeBinding) guessedType; + /** + *

Creates a function proposal based on all of the given information

+ * + * @param name + * @param parameterQualifications + * @param parameterFullyQualifiedTypeNames + * @param parameterNames + * @param returnQualification + * @param returnSimpleName + * @param declaringQualification + * @param declaringSimpleName + * @param modifiers + */ + private void proposeFunction(char[] name, + char[][] parameterFullyQualifiedTypeNames, + char[][] parameterNames, + char[] returnQualification, + char[] returnSimpleName, + char[] declaringQualification, + char[] declaringSimpleName, + int modifiers) { + + //compute completion + char[] completion; + if (this.source != null + && this.source.length > this.endPosition + && this.source[this.endPosition] == '(') { + + completion = name; + } else { + completion = CharOperation.concat(name, new char[] { '(', ')' }); + } + + //compute relevance + int relevance = computeBaseRelevance(); + relevance += computeRelevanceForInterestingProposal(); + if (this.completionToken != null) relevance += computeRelevanceForCaseMatching(this.completionToken, name); + relevance += computeRelevanceForExpectingType(returnQualification, returnSimpleName); + relevance += computeRelevanceForQualification(false); + relevance += computeRelevanceForRestrictions(IAccessRule.K_ACCESSIBLE); + relevance += RelevanceConstants.R_FUNCTION; + relevance += computeRelevanceForName(name); + + this.noProposal = false; + // create proposal + CompletionProposal proposal = this.createProposal(CompletionProposal.METHOD_REF, this.actualCompletionPosition); + proposal.setDeclarationSignature(QualificationHelpers.createFullyQualifiedName(declaringQualification, declaringSimpleName)); + proposal.setDeclarationPackageName(declaringQualification); + proposal.setDeclarationTypeName(declaringSimpleName); + proposal.setParameterTypeNames(parameterFullyQualifiedTypeNames); + proposal.setReturnQualification(returnQualification); + proposal.setReturnSimpleName(returnSimpleName); + proposal.setName(name); + proposal.setCompletion(completion); + proposal.setFlags(modifiers | Flags.AccPublic ); + proposal.setReplaceRange(this.startPosition - this.offset, this.endPosition - this.offset); + proposal.setRelevance(relevance); + if(parameterNames != null) proposal.setParameterNames(parameterNames); + proposal.setIsContructor(false); + this.requestor.accept(proposal); + if(DEBUG) { + this.printDebug(proposal); + } + } + + /** + *

Proposes a function content assist completion based on a {@link MethodBinding}.

+ * + * @param method {@link MethodBinding} to base a function content assist completion proposal on + */ + private void proposeFunction(MethodBinding method) { + if(method != null && method.selector != null) { + //get parameter info + int parametersLength = method.parameters != null ? method.parameters.length : 0; + char[][] parameterFullyQualifiedTypeNames = new char[parametersLength][]; + + //get parameter types + for (int i = 0; i < parametersLength; i++) { + //find first none-anonymous parent type and use that for argument type name + TypeBinding parameterType = method.original().parameters[i]; + while(parameterType != null && parameterType.isAnonymousType() && parameterType instanceof ReferenceBinding) { + parameterType = ((ReferenceBinding)parameterType).getSuperBinding(); + } - if (refBinding.scope == null || refBinding.classScope.referenceContext == null) return null; + //if ended up with null type, use original + if(parameterType == null) { + parameterType = method.original().parameters[i]; + } - TypeDeclaration typeDeclaration = refBinding.classScope.referenceContext; - AbstractMethodDeclaration[] methods = typeDeclaration.methods; + //do not display anonymous types + if(!parameterType.isAnonymousType()) { + parameterFullyQualifiedTypeNames[i] = parameterType.qualifiedSourceName(); + } + } + + //get parameter names + char[][] parameterNames = findMethodParameterNames(method, parameterFullyQualifiedTypeNames); + + //get return type info + char[] returnQualification = null; + char[] returnSimpleName = null; + if(method.returnType != null) { + char[][] seperatedReturnTypeName = + QualificationHelpers.seperateFullyQualifedName(method.returnType.qualifiedSourceName()); + returnQualification = seperatedReturnTypeName[QualificationHelpers.QULIFIERS_INDEX]; + returnSimpleName = seperatedReturnTypeName[QualificationHelpers.SIMPLE_NAMES_INDEX]; + } + + //get declaring type info + char[] declaringQualification = null; + char[] declaringSimpleName = null; + + /* determine the declaring type name, + * local function bindings do not have declaring type unless their declaring class is not a compilation unit + * + * IE: + * function() { + * foo.bar = function() {}; + * }*/ + if(method.declaringClass != null && + (!(method instanceof LocalFunctionBinding) || !(method.declaringClass instanceof CompilationUnitBinding)) ) { - next : for (int i = 0; i < methods.length; i++) { - AbstractMethodDeclaration method = methods[i]; - - if (!method.isConstructor()) continue next; - - Argument[] arguments = method.arguments; - int argumentsLength = arguments == null ? 0 : arguments.length; - - if (parameterCount != argumentsLength) continue next; - - for (int j = 0; j < argumentsLength; j++) { - char[] argumentTypeName = getTypeName(arguments[j].type); - - if (!CharOperation.equals(argumentTypeName, parameterTypes[j])) { - continue next; - } - } - - refBinding.resolveTypesFor(method.binding); // force resolution - if (method.binding == null) continue next; - return getSignature(method.binding); + /* if declaring type is a compilation unit, then use global type + * else use function declaring type */ + if(method.declaringClass instanceof CompilationUnitBinding) { + declaringSimpleName = IIndexConstants.GLOBAL_SYMBOL; + } else if(method.declaringClass != null) { + char[][] seperatedDeclaringTypeName = + QualificationHelpers.seperateFullyQualifedName(method.declaringClass.qualifiedSourceName()); + declaringQualification = seperatedDeclaringTypeName[QualificationHelpers.QULIFIERS_INDEX]; + declaringSimpleName = seperatedDeclaringTypeName[QualificationHelpers.SIMPLE_NAMES_INDEX]; } } + + this.proposeFunction(method.selector, parameterFullyQualifiedTypeNames, parameterNames, + returnQualification, returnSimpleName, + declaringQualification, declaringSimpleName, + method.modifiers); } - - return null; } - private static char[] getTypeName(TypeReference typeReference) { - char[] typeName = CharOperation.concatWith(typeReference.getTypeName(), '.'); - int dims = typeReference.dimensions(); - if (dims > 0) { - int length = typeName.length; - int newLength = length + (dims*2); - System.arraycopy(typeName, 0, typeName = new char[newLength], 0, length); - for (int k = length; k < newLength; k += 2) { - typeName[k] = '['; - typeName[k+1] = ']'; + /** + *

+ * Creates a field proposal using the given {@link FieldBinding}. + *

+ * + * @param field + * create a field proposal from this {@link FieldBinding} + */ + private void proposeField(FieldBinding field) { + this.proposeField(field.name, field.type.qualifiedPackageName(), field.type.qualifiedSourceName(), + field.declaringClass.qualifiedPackageName(), field.declaringClass.qualifiedSourceName(), + field.modifiers); + } + + /** + *

Creates a variable proposal based on all of the given information

+ * + * @param name + * @param typeQualification + * @param typeSimpleName + * @param declaringQualification + * @param declaringSimpleName + * @param modifiers + */ + private void proposeField(char[] name, + char[] typeQualification, + char[] typeSimpleName, + char[] declaringQualification, + char[] declaringSimpleName, + int modifiers) { + + char[] completion = name; + + int relevance = computeBaseRelevance(); + relevance += computeRelevanceForInterestingProposal(); + if (this.completionToken != null) relevance += computeRelevanceForCaseMatching(this.completionToken, name); + relevance += computeRelevanceForExpectingType(typeQualification, typeSimpleName); + relevance += computeRelevanceForQualification(false); + relevance += computeRelevanceForRestrictions(IAccessRule.K_ACCESSIBLE); + relevance += RelevanceConstants.R_FIELD; + relevance += computeRelevanceForName(name); + + this.noProposal = false; + // Standard proposal + if (!this.requestor.isIgnored(CompletionProposal.FIELD_REF) && (this.assistNodeInJavadoc & CompletionOnJavadoc.ONLY_INLINE_TAG) == 0) { + CompletionProposal proposal = this.createProposal(CompletionProposal.FIELD_REF, this.actualCompletionPosition); + proposal.setDeclarationPackageName(declaringQualification); + proposal.setDeclarationTypeName(declaringSimpleName); + proposal.setReturnQualification(typeQualification); + proposal.setReturnSimpleName(typeSimpleName); + proposal.setName(name); + proposal.setCompletion(completion); + proposal.setFlags(modifiers); + proposal.setReplaceRange(this.startPosition - this.offset, this.endPosition - this.offset); + proposal.setRelevance(relevance); + this.requestor.accept(proposal); + if(DEBUG) { + this.printDebug(proposal); } } - return typeName; + // Javadoc completions + if ((this.assistNodeInJavadoc & CompletionOnJavadoc.TEXT) != 0 && !this.requestor.isIgnored(CompletionProposal.JSDOC_FIELD_REF)) { + char[] javadocCompletion = inlineTagCompletion(completion, JavadocTagConstants.TAG_LINK); + CompletionProposal proposal = this.createProposal(CompletionProposal.JSDOC_FIELD_REF, this.actualCompletionPosition); + proposal.setDeclarationPackageName(declaringQualification); + proposal.setDeclarationTypeName(declaringSimpleName); + proposal.setReturnQualification(typeQualification); + proposal.setReturnSimpleName(typeSimpleName); + proposal.setName(name); + proposal.setCompletion(javadocCompletion); + proposal.setFlags(modifiers); + int start = (this.assistNodeInJavadoc & CompletionOnJavadoc.REPLACE_TAG) != 0 ? this.javadocTagPosition : this.startPosition; + proposal.setReplaceRange(start - this.offset, this.endPosition - this.offset); + proposal.setRelevance(relevance+R_INLINE_TAG); + this.requestor.accept(proposal); + if(DEBUG) { + this.printDebug(proposal); + } + } } /** - *

Represents a constructor accepted from the index.

+ *

+ * Computes the relevance of a given name. The name could be for a type, + * field, or function. + *

+ * + * @param name + * compute the relevance of this type, field, or function name + * + * @return relevance of the given type, field, or function name */ - private static class AcceptedConstructor { - /** - *

Modifiers to the constructor such as public/private

- * - * @see Flags - */ - public int modifiers; - - /**

Name of the type the constructor is for

*/ - public char[] typeName; - - /**

Number of parameters for the constructor, or -1 for a default constructor

*/ - public int parameterCount; + private static int computeRelevanceForName(char[] name) { + int relevance = 0; - /**

Type names of the parameters, should be same length as parameterCount

*/ - public char[][] parameterTypes; - - /**

Names of the parameters, should be same length as parameterCount

*/ - public char[][] parameterNames; - - /** - *

Accessibility of the constructor

- * - * @see IAccessRule - */ - public int accessibility; - - /** - *

Constructor

- * - * @param modifiers Modifiers to the constructor such as public/private - * @param typeName Name of the type the constructor is for - * @param parameterCount Number of parameters for the constructor, or -1 for a default constructor - * @param parameterTypes Type names of the parameters, should be same length as parameterCount - * @param parameterNames Names of the parameters, should be same length as parameterCount - * @param accessibility Accessibility of the constructor - * - * @see Flags - * @see IAccessRule - */ - private AcceptedConstructor( - int modifiers, - char[] typeName, - int parameterCount, - char[][] parameterTypes, - char[][] parameterNames, - int accessibility) { - - this.modifiers = modifiers; - this.typeName = typeName; - this.parameterCount = parameterCount; - this.parameterTypes = parameterTypes; - this.parameterNames = parameterNames; - this.accessibility = accessibility; + //higher relevance if name does not start with an underscore + if(name != null && name.length > 0 && name[0] != '_') { + relevance = RelevanceConstants.R_NOT_UNDERSCORE; } - - /** - * @see java.lang.Object#toString() - */ - public String toString() { - StringBuffer buffer = new StringBuffer(); - buffer.append('{'); - buffer.append(','); - buffer.append(this.typeName); - buffer.append('}'); - return buffer.toString(); + + return relevance; + } + + /** + *

NOTE: This code is derived from FunctionBinding#areParametersCompatibleWith(TypeBinding[])

+ * + * @param parameters + * @param arguments + * @param isVarargs + * @return + */ + private static boolean areParametersCompatibleWith(TypeBinding[] parameters, TypeBinding[] arguments, boolean isVarargs) { + int paramLength = parameters.length; + int argLength = arguments.length; + int lastIndex = argLength; + if (isVarargs) { + lastIndex = paramLength - 1; + if (paramLength == argLength) { // accept X[] but not X or X[][] + TypeBinding varArgType = parameters[lastIndex]; // is an ArrayBinding by definition + TypeBinding lastArgument = arguments[lastIndex]; + if (varArgType != lastArgument && !lastArgument.isCompatibleWith(varArgType)) + return false; + } else if (paramLength < argLength) { // all remainig argument types must be compatible with the elementsType of varArgType + TypeBinding varArgType = ((ArrayBinding) parameters[lastIndex]).elementsType(); + for (int i = lastIndex; i < argLength; i++) + if (varArgType != arguments[i] && !arguments[i].isCompatibleWith(varArgType)) + return false; + } else if (lastIndex != argLength) { // can call foo(int i, X ... x) with foo(1) but NOT foo(); + return false; + } + // now compare standard arguments from 0 to lastIndex + } else { + if(paramLength != argLength) + return false; } + for (int i = 0; i < lastIndex; i++) + if (parameters[i] != arguments[i] && !arguments[i].isCompatibleWith(parameters[i])) + return false; + return true; } } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/ISearchRequestor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/ISearchRequestor.java index d9a0c987..bf5562b0 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/ISearchRequestor.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/ISearchRequestor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -47,7 +47,6 @@ public interface ISearchRequestor { * * @param modifiers Modifiers to the constructor such as public/private * @param typeName Name of the type the constructor is for - * @param parameterCount Number of parameters for the constructor, or -1 for a default constructor * @param parameterTypes Type names of the parameters, should be same length as parameterCount * @param parameterNames Names of the parameters, should be same length as parameterCount * @param path to the document containing the constructor match @@ -59,9 +58,50 @@ public interface ISearchRequestor { public void acceptConstructor( int modifiers, char[] typeName, - int parameterCount, char[][] parameterTypes, char[][] parameterNames, String path, AccessRestriction access); + + /** + *

Accept a function defined with all of the given information

+ * + * @param signature + * @param parameterFullyQualifedTypeNames + * @param parameterNames + * @param returnQualification + * @param returnSimpleName + * @param declaringQualification + * @param declaringSimpleName + * @param modifiers + * @param path + */ + public void acceptFunction(char[] signature, + char[][] parameterFullyQualifedTypeNames, + char[][] parameterNames, + char[] returnQualification, + char[] returnSimpleName, + char[] declaringQualification, + char[] declaringSimpleName, + int modifiers, + String path); + + /** + *

Accept a variable defined with all of the given information

+ * + * @param signature + * @param typeQualification + * @param typeSimpleName + * @param declaringQualification + * @param declaringSimpleName + * @param modifiers + * @param path + */ + public void acceptVariable(char[] signature, + char[] typeQualification, + char[] typeSimpleName, + char[] declaringQualification, + char[] declaringSimpleName, + int modifiers, + String path); } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/InternalCompletionProposal.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/InternalCompletionProposal.java index 35e732bf..e23aaf05 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/InternalCompletionProposal.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/InternalCompletionProposal.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2004, 2008 IBM Corporation and others. + * Copyright (c) 2004, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -41,9 +41,8 @@ public class InternalCompletionProposal { protected char[] declarationPackageName; protected char[] declarationTypeName; - protected char[] packageName; - protected char[] typeName; - protected char[][] parameterPackageNames; + protected char[] returnQualification; + protected char[] returnSimpleName; protected char[][] parameterTypeNames; protected char[] originalSignature; @@ -143,19 +142,14 @@ public class InternalCompletionProposal { return this.declarationTypeName; } - protected char[] getPackageName() { - return this.packageName; + protected char[] getReturnQualification() { + return this.returnQualification; } - protected char[] getTypeName() { - return this.typeName; + protected char[] getReturnSimpleName() { + return this.returnSimpleName; } - protected char[][] getParameterPackageNames() { - return this.parameterPackageNames; - } - - protected char[][] getParameterTypeNames() { return this.parameterTypeNames; } @@ -168,16 +162,12 @@ public class InternalCompletionProposal { this.declarationTypeName = declarationTypeName; } - protected void setPackageName(char[] packageName) { - this.packageName = packageName; - } - - protected void setTypeName(char[] typeName) { - this.typeName = typeName; + protected void setReturnQualification(char[] packageName) { + this.returnQualification = packageName; } - protected void setParameterPackageNames(char[][] parameterPackageNames) { - this.parameterPackageNames = parameterPackageNames; + protected void setReturnSimpleName(char[] typeName) { + this.returnSimpleName = typeName; } protected void setParameterTypeNames(char[][] parameterTypeNames) { diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/MissingTypesGuesser.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/MissingTypesGuesser.java index b38679cd..e3171b40 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/MissingTypesGuesser.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/MissingTypesGuesser.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2011 IBM Corporation and others. + * Copyright (c) 2007, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -325,15 +325,35 @@ public class MissingTypesGuesser extends ASTVisitor { /** * @see org.eclipse.wst.jsdt.internal.codeassist.ISearchRequestor#acceptConstructor( - * int, char[], int, char[][], char[][], java.lang.String, org.eclipse.wst.jsdt.internal.compiler.env.AccessRestriction) + * int, char[], char[][], char[][], java.lang.String, org.eclipse.wst.jsdt.internal.compiler.env.AccessRestriction) */ public void acceptConstructor(int modifiers, char[] typeName, - int parameterCount, char[][] parameterTypes, char[][] parameterNames, + char[][] parameterTypes, char[][] parameterNames, String path, AccessRestriction access) { //do nothing } - + + /** + * @see org.eclipse.wst.jsdt.internal.codeassist.ISearchRequestor#acceptFunction(char[], char[][], char[][], char[], char[], char[], char[], int, java.lang.String) + */ + public void acceptFunction(char[] signature, char[][] parameterFullyQualifedTypeNames, + char[][] parameterNames, char[] returnQualification, char[] returnSimpleName, + char[] declaringQualification, char[] declaringSimpleName, int modifiers, String path) { + + //do nothing + } + + /** + * @see org.eclipse.wst.jsdt.internal.codeassist.ISearchRequestor#acceptVariable(char[], char[], char[], char[], char[], int, java.lang.String) + */ + public void acceptVariable(char[] signature, + char[] typeQualification, char[] typeSimpleName, + char[] declaringQualification, char[] declaringSimpleName, + int modifiers, String path) { + + //do nothing + } }; nameEnvironment.findExactTypes(missingSimpleName, true, IJavaScriptSearchConstants.TYPE, storage); if(results.size() == 0) return null; diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/RelevanceConstants.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/RelevanceConstants.java index ce267f1c..3db7c004 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/RelevanceConstants.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/RelevanceConstants.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -39,4 +39,13 @@ public interface RelevanceConstants { int R_NO_PROBLEMS = 1; int R_RESOLVED = 1; int R_TARGET = 5; -} + + /** Relevance for any name that does not start with an underscore */ + int R_NOT_UNDERSCORE = 20; + + /** Relevance for functions */ + int R_FUNCTION = 60; + + /** Relevance for fields */ + int R_FIELD = 30; +} \ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/SelectionEngine.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/SelectionEngine.java index 69577239..0716b564 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/SelectionEngine.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/SelectionEngine.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -294,15 +294,36 @@ public final class SelectionEngine extends Engine implements ISearchRequestor { /** * @see org.eclipse.wst.jsdt.internal.codeassist.ISearchRequestor#acceptConstructor( - * int, char[], int, char[][], char[][], java.lang.String, org.eclipse.wst.jsdt.internal.compiler.env.AccessRestriction) + * int, char[], char[][], char[][], java.lang.String, org.eclipse.wst.jsdt.internal.compiler.env.AccessRestriction) */ public void acceptConstructor(int modifiers, char[] typeName, - int parameterCount, char[][] parameterTypes, + char[][] parameterTypes, char[][] parameterNames, String path, AccessRestriction access) { // do nothing } + + /** + * @see org.eclipse.wst.jsdt.internal.codeassist.ISearchRequestor#acceptFunction(char[], char[][], char[][], char[], char[], char[], char[], int, java.lang.String) + */ + public void acceptFunction(char[] signature, char[][] parameterFullyQualifedTypeNames, + char[][] parameterNames, char[] returnQualification, char[] returnSimpleName, + char[] declaringQualification, char[] declaringSimpleName, int modifiers, String path) { + + //do nothing + } + + /** + * @see org.eclipse.wst.jsdt.internal.codeassist.ISearchRequestor#acceptVariable(char[], char[], char[], char[], char[], int, java.lang.String) + */ + public void acceptVariable(char[] signature, + char[] typeQualification, char[] typeSimpleName, + char[] declaringQualification, char[] declaringSimpleName, + int modifiers, String path) { + + //do nothing + } private void acceptQualifiedTypes() { if(this.acceptedClasses != null){ @@ -667,9 +688,9 @@ public final class SelectionEngine extends Engine implements ISearchRequestor { // check for inferred types declared with their names in the selection this.parser.inferTypes(parsedUnit, this.compilerOptions); - for (int i = 0; i < parsedUnit.inferredTypes.length; i++) { - if (parsedUnit.inferredTypes[i] != null && parsedUnit.inferredTypes[i].isDefinition && parsedUnit.inferredTypes[i].getNameStart() <= selectionSourceEnd && selectionSourceStart <= parsedUnit.inferredTypes[i].getNameStart() + parsedUnit.inferredTypes[i].getName().length) { - this.requestor.acceptType(CharOperation.NO_CHAR, sourceUnit.getFileName(), parsedUnit.inferredTypes[i].getName(), 0, parsedUnit.inferredTypes[i].isDefinition, CharOperation.NO_CHAR, parsedUnit.inferredTypes[i].sourceStart, parsedUnit.inferredTypes[i].sourceEnd); + for (int i = 0; i < parsedUnit.numberInferredTypes; i++) { + if (parsedUnit.inferredTypes[i] != null && parsedUnit.inferredTypes[i].isDefinition() && parsedUnit.inferredTypes[i].getNameStart() <= selectionSourceEnd && selectionSourceStart <= parsedUnit.inferredTypes[i].getNameStart() + parsedUnit.inferredTypes[i].getName().length) { + this.requestor.acceptType(CharOperation.NO_CHAR, sourceUnit.getFileName(), parsedUnit.inferredTypes[i].getName(), 0, parsedUnit.inferredTypes[i].isDefinition(), CharOperation.NO_CHAR, parsedUnit.inferredTypes[i].sourceStart, parsedUnit.inferredTypes[i].sourceEnd); } } // scan the package & import statements first @@ -726,9 +747,12 @@ public final class SelectionEngine extends Engine implements ISearchRequestor { if (parsedUnit.statements != null || parsedUnit.isPackageInfo()) { if(selectDeclaration(parsedUnit)) return; - this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/); - if ((this.unitScope = parsedUnit.scope) != null) { - try { + try { + /* We must build bindings to be able to resolve a reference (might not + * require completing), however this may itself cause SelectionNodeFound + * to be thrown */ + this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/, true); + if ((this.unitScope = parsedUnit.scope) != null) { this.lookupEnvironment.completeTypeBindings(parsedUnit, true); parsedUnit.scope.faultInTypes(); ASTNode node = null; @@ -742,15 +766,15 @@ public final class SelectionEngine extends Engine implements ISearchRequestor { if (node != null) { selectLocalDeclaration(node); } - } catch (SelectionNodeFound e) { - if (e.binding != null) { - if(DEBUG) { - System.out.println("SELECTION - Selection binding:"); //$NON-NLS-1$ - System.out.println(e.binding.toString()); - } - // if null then we found a problem in the selection node - selectFrom(e.binding, parsedUnit, e.isDeclaration); + } + } catch (SelectionNodeFound e) { + if (e.binding != null) { + if(DEBUG) { + System.out.println("SELECTION - Selection binding:"); //$NON-NLS-1$ + System.out.println(e.binding.toString()); } + // if null then we found a problem in the selection node + selectFrom(e.binding, parsedUnit, e.isDeclaration); } } } @@ -852,7 +876,7 @@ public final class SelectionEngine extends Engine implements ISearchRequestor { ((SelectionRequestor)this.requestor).acceptLocalMethod(methodBinding); } else { this.requestor.acceptMethod( - /*declaringClass.qualifiedPackageName()*/ new char[0], + /*declaringClass.qualifiedPackageName()*/ CharOperation.NO_CHAR, declaringClass.getFileName(), declaringClass.qualifiedSourceName(), declaringClass.enclosingType() == null ? null : new String(getSignature(declaringClass.enclosingType())), @@ -930,12 +954,12 @@ public final class SelectionEngine extends Engine implements ISearchRequestor { class Visitor extends ASTVisitor { public boolean visit(ConstructorDeclaration constructorDeclaration, ClassScope scope) { - if (constructorDeclaration.selector == assistIdentifier){ - if (constructorDeclaration.binding != null) { - throw new SelectionNodeFound(constructorDeclaration.binding); + if (constructorDeclaration.getName() == assistIdentifier){ + if (constructorDeclaration.getBinding() != null) { + throw new SelectionNodeFound(constructorDeclaration.getBinding()); } else { - if (constructorDeclaration.scope != null) { - throw new SelectionNodeFound(new MethodBinding(constructorDeclaration.modifiers, constructorDeclaration.selector, null, null, constructorDeclaration.scope.referenceType().binding)); + if (constructorDeclaration.getScope() != null) { + throw new SelectionNodeFound(new MethodBinding(constructorDeclaration.modifiers, constructorDeclaration.getName(), null, null, constructorDeclaration.getScope().referenceType().binding)); } } } @@ -960,12 +984,12 @@ public final class SelectionEngine extends Engine implements ISearchRequestor { return true; } public boolean visit(MethodDeclaration methodDeclaration, Scope scope) { - if (methodDeclaration.selector == assistIdentifier){ - if (methodDeclaration.binding != null) { - throw new SelectionNodeFound(methodDeclaration.binding); + if (methodDeclaration.getName() == assistIdentifier){ + if (methodDeclaration.getBinding() != null) { + throw new SelectionNodeFound(methodDeclaration.getBinding()); } else { - if (methodDeclaration.scope != null) { - throw new SelectionNodeFound(new MethodBinding(methodDeclaration.modifiers, methodDeclaration.selector, null, null, methodDeclaration.scope.referenceType().binding)); + if (methodDeclaration.getScope() != null) { + throw new SelectionNodeFound(new MethodBinding(methodDeclaration.modifiers, methodDeclaration.getName(), null, null, methodDeclaration.getScope().referenceType().binding)); } } } @@ -1154,7 +1178,7 @@ public final class SelectionEngine extends Engine implements ISearchRequestor { { AbstractMethodDeclaration method = (AbstractMethodDeclaration)statements[i]; - if (method.selector == assistIdentifier){ + if (method.getName() == assistIdentifier){ char[] qualifiedSourceName = compilationUnit.getFileName(); this.requestor.acceptMethod( @@ -1162,14 +1186,14 @@ public final class SelectionEngine extends Engine implements ISearchRequestor { compilationUnit.getFileName(), qualifiedSourceName, null, // SelectionRequestor does not need of declaring type signature for method declaration - method.selector, + method.getName(), null, // SelectionRequestor does not need of parameters type for method declaration null, // SelectionRequestor does not need of parameters type for method declaration null, // SelectionRequestor does not need of parameters type for method declaration null,null, method.isConstructor(), true, - method.binding != null ? method.binding.computeUniqueKey() : null, + method.hasBinding() ? method.getBinding().computeUniqueKey() : null, this.actualSelectionStart, this.actualSelectionEnd); @@ -1243,7 +1267,7 @@ public final class SelectionEngine extends Engine implements ISearchRequestor { for (int i = 0, length = methods == null ? 0 : methods.length; i < length; i++){ AbstractMethodDeclaration method = methods[i]; - if (method.selector == assistIdentifier){ + if (method.getName() == assistIdentifier){ char[] qualifiedSourceName = null; TypeDeclaration enclosingType = typeDeclaration; @@ -1257,7 +1281,7 @@ public final class SelectionEngine extends Engine implements ISearchRequestor { null, qualifiedSourceName, null, // SelectionRequestor does not need of declaring type signature for method declaration - method.selector, + method.getName(), null, // SelectionRequestor does not need of parameters type for method declaration null, // SelectionRequestor does not need of parameters type for method declaration null, // SelectionRequestor does not need of parameters type for method declaration @@ -1265,7 +1289,7 @@ public final class SelectionEngine extends Engine implements ISearchRequestor { null, // SelectionRequestor does not need of type parameters bounds for method declaration method.isConstructor(), true, - method.binding != null ? method.binding.computeUniqueKey() : null, + method.hasBinding() ? method.getBinding().computeUniqueKey() : null, this.actualSelectionStart, this.actualSelectionEnd); @@ -1287,15 +1311,8 @@ public final class SelectionEngine extends Engine implements ISearchRequestor { localParser.inferTypes(parsedUnit,this.compilerOptions); return parsedUnit; } catch (AbortCompilationUnit e) { -// // at this point, currentCompilationUnitResult may not be sourceUnit, but some other -// // one requested further along to resolve sourceUnit. -// if (unitResult.compilationUnit == sourceUnit) { // only report once -// requestor.acceptResult(unitResult.tagAsAccepted()); -// } else { - throw e; // want to abort enclosing request to compile -// } + throw e; // want to abort enclosing request to compile } } - } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/UnresolvedReferenceNameFinder.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/UnresolvedReferenceNameFinder.java index c7c3744f..f5ed3d8a 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/UnresolvedReferenceNameFinder.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/UnresolvedReferenceNameFinder.java @@ -95,8 +95,8 @@ public class UnresolvedReferenceNameFinder extends ASTVisitor { char[][] discouragedNames, UnresolvedReferenceNameRequestor nameRequestor) { MethodDeclaration fakeMethod = - this.findAfter(startWith, methodDeclaration.scope, from, methodDeclaration.bodyEnd, MAX_LINE_COUNT, false, discouragedNames, nameRequestor); - if (fakeMethod != null) fakeMethod.traverse(this, methodDeclaration.scope.classScope()); + this.findAfter(startWith, methodDeclaration.getScope(), from, methodDeclaration.bodyEnd, MAX_LINE_COUNT, false, discouragedNames, nameRequestor); + if (fakeMethod != null) fakeMethod.traverse(this, methodDeclaration.getScope().classScope()); } public void findAfter( diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnExplicitConstructorCall.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnExplicitConstructorCall.java index 51dbdaad..e5da8e1c 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnExplicitConstructorCall.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnExplicitConstructorCall.java @@ -74,7 +74,7 @@ public class CompletionOnExplicitConstructorCall extends ExplicitConstructorCall if (this.accessMode != This && receiverType != null) { if (receiverType.isHierarchyInconsistent()) throw new CompletionNodeFound(); - receiverType = receiverType.superclass(); + receiverType = receiverType.getSuperBinding(); } if (receiverType == null) throw new CompletionNodeFound(); diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnImportReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnImportReference.java index 154a632d..4faae947 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnImportReference.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnImportReference.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnKeyword2.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnKeyword2.java index 1f889fc4..0750b020 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnKeyword2.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnKeyword2.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnMessageSend.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnMessageSend.java index 0bbee917..04c3da6d 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnMessageSend.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnMessageSend.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnSingleNameReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnSingleNameReference.java index af472945..60380cbf 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnSingleNameReference.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionOnSingleNameReference.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionParser.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionParser.java index ad21bd1a..9d8302de 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionParser.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/complete/CompletionParser.java @@ -1865,7 +1865,7 @@ protected void consumeMethodHeaderName(boolean isAnnotationMethod) { CompletionOnMethodName md = new CompletionOnMethodName(this.compilationUnit.compilationResult); //name - md.selector = identifierStack[identifierPtr]; + md.setSelector(identifierStack[identifierPtr]); long selectorSource = identifierPositionStack[identifierPtr--]; identifierLengthPtr--; //type @@ -2915,7 +2915,7 @@ public MethodDeclaration parseSomeStatements(int start, int end, int fakeBlocksC goForBlockStatementsopt(); MethodDeclaration fakeMethod = new MethodDeclaration(unit.compilationResult()); - fakeMethod.selector = FAKE_METHOD_NAME; + fakeMethod.setSelector(FAKE_METHOD_NAME); fakeMethod.bodyStart = start; fakeMethod.bodyEnd = end; fakeMethod.declarationSourceStart = start; diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/impl/Engine.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/impl/Engine.java index 445d7299..475e1876 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/impl/Engine.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/impl/Engine.java @@ -88,10 +88,13 @@ public abstract class Engine implements ITypeRequestor, ITypeRequestor2 { lookupEnvironment.completeTypeBindings(parsedUnit, true); } public void accept(ICompilationUnit unit, char[][] typeNames, AccessRestriction accessRestriction) { - CompilationUnitDeclaration parsedUnit = doParse(unit,accessRestriction); + CompilationUnitDeclaration parsedUnit = lookupEnvironment.getExistingCompilationUnitDeclaration(unit.getFileName()); + if(parsedUnit == null) { + parsedUnit = doParse(unit,accessRestriction); + } lookupEnvironment.buildTypeBindings(parsedUnit, typeNames, accessRestriction); - lookupEnvironment.completeTypeBindings(parsedUnit, typeNames, true); + lookupEnvironment.completeTypeBindings(parsedUnit, typeNames, lookupEnvironment.shouldBuildFieldsAndMethods); } /** diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnImportReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnImportReference.java index 81d23a06..08c559a1 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnImportReference.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnImportReference.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnLocalName.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnLocalName.java index 4065e3d5..76fdd834 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnLocalName.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnLocalName.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnMethodName.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnMethodName.java new file mode 100644 index 00000000..553f6262 --- /dev/null +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnMethodName.java @@ -0,0 +1,49 @@ +/******************************************************************************* + * Copyright (c) 2000, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.wst.jsdt.internal.codeassist.select; + +import org.eclipse.wst.jsdt.internal.compiler.CompilationResult; +import org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration; +import org.eclipse.wst.jsdt.internal.compiler.lookup.Scope; + +public class SelectionOnMethodName extends MethodDeclaration { + public int selectorEnd; + + public SelectionOnMethodName(CompilationResult compilationResult){ + super(compilationResult); + } + + public StringBuffer print(int indent, StringBuffer output) { + + printIndent(indent, output); + output.append(" 0) output.append(", "); //$NON-NLS-1$ + arguments[i].print(0, output); + } + } + output.append(')'); + return output.append('>'); + } + + + /* (non-Javadoc) + * @see org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration#resolve(org.eclipse.wst.jsdt.internal.compiler.lookup.Scope) + */ + public void resolve(Scope upperScope) { + super.resolve(upperScope); + throw new SelectionNodeFound(binding); + } +} diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnPackageReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnPackageReference.java index ded889c4..bd5407a1 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnPackageReference.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnPackageReference.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnSingleNameReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnSingleNameReference.java index de19843e..6efb875f 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnSingleNameReference.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionOnSingleNameReference.java @@ -78,6 +78,23 @@ public TypeBinding resolveType(BlockScope scope) { throw new SelectionNodeFound(binding); } +/** + *

Overrides parent so that {@link #resolveType(BlockScope)} will be called and the {@link SelectionNodeFound} exception + * will be thrown. But calls parent implementation first so that if part of an assignment any possible defining will take + * place before trying to get the binding.

+ * + * @see org.eclipse.wst.jsdt.internal.compiler.ast.SingleNameReference#resolveType(org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope, boolean, org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding) + */ +public TypeBinding resolveType(BlockScope scope, boolean define, TypeBinding useType) { + /* resolve the single name reference + * this is needed for the case where the selection is the LHS of an assignment + */ + super.resolveType(scope, define, useType); + + //run the selection resolve type so that the SelectionNodeFound exception will be thrown + return this.resolveType(scope); +} + public TypeBinding resolveForAllocation(BlockScope scope, ASTNode location) { TypeBinding typeBinding=null; this.binding= diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionParser.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionParser.java index 94ed1e94..679013a0 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionParser.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/codeassist/select/SelectionParser.java @@ -34,6 +34,7 @@ import org.eclipse.wst.jsdt.internal.compiler.ast.FieldReference; import org.eclipse.wst.jsdt.internal.compiler.ast.ImportReference; import org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration; import org.eclipse.wst.jsdt.internal.compiler.ast.MessageSend; +import org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration; import org.eclipse.wst.jsdt.internal.compiler.ast.NameReference; import org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedAllocationExpression; import org.eclipse.wst.jsdt.internal.compiler.ast.Statement; @@ -382,6 +383,81 @@ protected void consumeLocalVariableDeclarationStatement() { } } +protected void consumeMethodHeaderName(boolean isAnonymous) { + MethodDeclaration md = null; + if (this.indexOfAssistIdentifier() < 0) { + md = new MethodDeclaration(this.compilationUnit.compilationResult); + } + else { + md = new SelectionOnMethodName(this.compilationUnit.compilationResult); + } + + md.exprStackPtr=this.expressionPtr; + //name + long selectorSource =-1; + if (!isAnonymous) + { + md.setSelector(this.identifierStack[this.identifierPtr]); + selectorSource = this.identifierPositionStack[this.identifierPtr--]; + this.identifierLengthPtr--; + } + + + if (this.nestedType>0) + markEnclosingMemberWithLocalType(); + + //type + // md.returnType = getTypeReference(this.intStack[this.intPtr--]); + //modifiers + int functionPos = this.intStack[this.intPtr--]; + int modifierPos = this.intStack[this.intPtr--]; + md.declarationSourceStart = (functionPos>modifierPos)? modifierPos:functionPos; + md.modifiers = this.intStack[this.intPtr--]; + // consume annotations + // int length; + // if ((length = this.expressionLengthStack[this.expressionLengthPtr--]) != 0) { + // System.arraycopy( + // this.expressionStack, + // (this.expressionPtr -= length) + 1, + // md.annotations = new Annotation[length], + // 0, + // length); + // } + // javadoc + md.javadoc = this.javadoc; + this.javadoc = null; + + //highlight starts at selector start + if (selectorSource>=0) + md.sourceStart = (int) (selectorSource >>> 32); + else + md.sourceStart=md.declarationSourceStart; + pushOnAstStack(md); + md.sourceEnd = this.lParenPos; + md.bodyStart = this.lParenPos+1; + this.listLength = 0; // initialize this.listLength before reading parameters/throws + + + + + incrementNestedType(); + + // recovery + if (this.currentElement != null){ + if (this.currentElement instanceof RecoveredType + //|| md.modifiers != 0 + || true/* (this.scanner.getLineNumber(md.returnType.sourceStart) + == this.scanner.getLineNumber(md.sourceStart))*/){ + this.lastCheckPoint = md.bodyStart; + this.currentElement = this.currentElement.add(md, 0); + this.lastIgnoredToken = -1; + } else { + this.lastCheckPoint = md.sourceStart; + this.restartRecovery = true; + } + } +} + // Nothing here applicable to javascript //protected void consumeMethodInvocationPrimary() { // //optimize the push/pop diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/Compiler.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/Compiler.java index e0cf4dfd..6f8c584c 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/Compiler.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/Compiler.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2012 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -15,6 +15,7 @@ import java.io.PrintWriter; import java.io.StringWriter; import org.eclipse.wst.jsdt.core.compiler.CategorizedProblem; +import org.eclipse.wst.jsdt.core.compiler.CharOperation; import org.eclipse.wst.jsdt.core.compiler.IProblem; import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode; import org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration; @@ -26,6 +27,7 @@ import org.eclipse.wst.jsdt.internal.compiler.env.INameEnvironment; import org.eclipse.wst.jsdt.internal.compiler.env.ISourceType; import org.eclipse.wst.jsdt.internal.compiler.impl.CompilerOptions; import org.eclipse.wst.jsdt.internal.compiler.impl.ITypeRequestor; +import org.eclipse.wst.jsdt.internal.compiler.impl.ITypeRequestor2; import org.eclipse.wst.jsdt.internal.compiler.lookup.LookupEnvironment; import org.eclipse.wst.jsdt.internal.compiler.lookup.PackageBinding; import org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding; @@ -41,7 +43,7 @@ import org.eclipse.wst.jsdt.internal.compiler.util.SimpleSetOfCharArray; import org.eclipse.wst.jsdt.internal.core.builder.SourceFile; import org.eclipse.wst.jsdt.internal.oaametadata.LibraryAPIs; -public class Compiler implements ITypeRequestor, ProblemSeverities { +public class Compiler implements ITypeRequestor, ProblemSeverities, ITypeRequestor2 { public Parser parser; public ICompilerRequestor requestor; public CompilerOptions options; @@ -230,8 +232,17 @@ public class Compiler implements ITypeRequestor, ProblemSeverities { parsedUnit.bits |= ASTNode.IsImplicitUnit; parser.inferTypes(parsedUnit, this.options); parsedUnits.put(sourceUnit.getFileName(), parsedUnit); - if (sourceUnit instanceof SourceFile) - this.addCompilationUnit(sourceUnit, parsedUnit); + if (sourceUnit instanceof SourceFile) { + // try to prevent, or at least reduce, the times the same file is processed multiple times + boolean addUnit = true; + if(this.lookupEnvironment != null && this.lookupEnvironment.unitBeingCompleted != null && + CharOperation.equals(this.lookupEnvironment.unitBeingCompleted.getFileName(), parsedUnit.getFileName())) { + addUnit = false; + + } + if(addUnit) + this.addCompilationUnit(sourceUnit, parsedUnit); + } } // initial type binding creation lookupEnvironment.buildTypeBindings(parsedUnit, accessRestriction); @@ -343,18 +354,17 @@ public class Compiler implements ITypeRequestor, ProblemSeverities { // process all units (some more could be injected in the loop by the lookup environment) for (int i = 0; i < this.totalUnits; i++) { unit = unitsToProcess[i]; - try { - if (options.verbose) - this.out.println( - Messages.bind(Messages.compilation_process, - new String[] { - String.valueOf(i + 1), - String.valueOf(this.totalUnits), - new String(unitsToProcess[i].getFileName()) - })); - process(unit, i); - } finally { - } + + if (options.verbose) + this.out.println( + Messages.bind(Messages.compilation_process, + new String[] { + String.valueOf(i + 1), + String.valueOf(this.totalUnits), + new String(unitsToProcess[i].getFileName()) + })); + process(unit, i); + requestor.acceptResult(unit.compilationResult.tagAsAccepted()); if (options.verbose) this.out.println( @@ -368,9 +378,8 @@ public class Compiler implements ITypeRequestor, ProblemSeverities { //clean up all units for(int i = 0; i < this.totalUnits; i++) { - // cleanup compilation unit result unitsToProcess[i].cleanUp(); - unitsToProcess[i] = null; // release reference to processed unit declaration + unitsToProcess[i] = null; } } catch (AbortCompilation e) { this.handleInternalException(e, unit); @@ -565,7 +574,7 @@ public class Compiler implements ITypeRequestor, ProblemSeverities { SimpleSetOfCharArray defined = new SimpleSetOfCharArray(); for (int j = 0; j < parsedUnit.numberInferredTypes; j++) { - if (parsedUnit.inferredTypes[j].isDefinition && !parsedUnit.inferredTypes[j].isEmptyGlobal()) { + if (parsedUnit.inferredTypes[j].isDefinition()) { defined.add(parsedUnit.inferredTypes[j].getName()); allDefinedTypes.add(parsedUnit.inferredTypes[j].getName()); } @@ -599,10 +608,6 @@ public class Compiler implements ITypeRequestor, ProblemSeverities { if (unit.scope != null) unit.scope.faultInTypes(); - // verify inherited methods - if (unit.scope != null) - unit.scope.verifyMethods(lookupEnvironment.methodVerifier()); - // type checking unit.resolve(); @@ -658,11 +663,7 @@ public class Compiler implements ITypeRequestor, ProblemSeverities { if (unit.scope != null) { // fault in fields & methods unit.scope.faultInTypes(); - if (unit.scope != null && verifyMethods) { - // http://dev.eclipse.org/bugs/show_bug.cgi?id=23117 - // verify inherited methods - unit.scope.verifyMethods(lookupEnvironment.methodVerifier()); - } + // type checking unit.resolve(); @@ -713,4 +714,52 @@ public class Compiler implements ITypeRequestor, ProblemSeverities { analyzeCode, generateCode); } + + public void accept(ICompilationUnit sourceUnit, char[][] typeNames, AccessRestriction accessRestriction) { + // Switch the current policy and compilation result for this unit to the requested one. + CompilationResult unitResult = + new CompilationResult(sourceUnit, totalUnits, totalUnits, this.options.maxProblemsPerUnit); + unitResult.packageName=sourceUnit.getPackageName(); + try { + if (options.verbose) { + String count = String.valueOf(totalUnits + 1); + this.out.println( + Messages.bind(Messages.compilation_request, + new String[] { + count, + count, + new String(sourceUnit.getFileName()) + })); + } + if (parsedUnits == null) + parsedUnits = new HashtableOfObject(); + CompilationUnitDeclaration parsedUnit = (CompilationUnitDeclaration) parsedUnits.get(sourceUnit.getFileName()); + if (parsedUnit == null) { + // diet parsing for large collection of unit + if (totalUnits < parseThreshold) { + parsedUnit = parser.parse(sourceUnit, unitResult); + } + else { + parsedUnit = parser.dietParse(sourceUnit, unitResult); + } + parsedUnit.bits |= ASTNode.IsImplicitUnit; + parser.inferTypes(parsedUnit, this.options); + parsedUnits.put(sourceUnit.getFileName(), parsedUnit); + } + // initial type binding creation + lookupEnvironment.buildTypeBindings(parsedUnit, typeNames, accessRestriction); + + // binding resolution + lookupEnvironment.completeTypeBindings(parsedUnit, typeNames); + } catch (AbortCompilationUnit e) { + // at this point, currentCompilationUnitResult may not be sourceUnit, but some other + // one requested further along to resolve sourceUnit. + if (unitResult.compilationUnit == sourceUnit) { // only report once + requestor.acceptResult(unitResult.tagAsAccepted()); + } else { + throw e; // want to abort enclosing request to compile + } + } + + } } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ISourceElementRequestor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ISourceElementRequestor.java index d2bf417c..f959effa 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ISourceElementRequestor.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ISourceElementRequestor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -48,6 +48,22 @@ public interface ISourceElementRequestor { public char[][] categories; public boolean secondary; public boolean anonymousMember; + public char[][] synonyms; + + /** + *

+ * true if this type is a globally visible type, + * false otherwise. + *

+ * + *

+ * EX: The anonymous type for a global variable would be globally + * visible, the anonymous type for a local would not. + *

+ * + * @since 1.1 + */ + public boolean isIndexed; } public static class MethodInfo { @@ -60,6 +76,7 @@ public interface ISourceElementRequestor { public int nameSourceEnd; public char[][] parameterTypes; public char[][] parameterNames; + public char[] declaringType; public char[][] categories; } @@ -68,6 +85,7 @@ public interface ISourceElementRequestor { public int modifiers; public char[] type; public char[] name; + public char[] declaringType; public int nameSourceStart; public int nameSourceEnd; public char[][] categories; @@ -100,7 +118,7 @@ public interface ISourceElementRequestor { */ void acceptLineSeparatorPositions(int[] positions); - void acceptMethodReference(char[] methodName, int argCount, int sourcePosition); + void acceptMethodReference(char[] methodName, int sourcePosition); void acceptProblem(CategorizedProblem problem); diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/SourceElementParser.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/SourceElementParser.java index 09c738f7..9ea1a55d 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/SourceElementParser.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/SourceElementParser.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -16,7 +16,6 @@ import java.util.HashMap; import java.util.Iterator; import org.eclipse.wst.jsdt.core.ast.IExpression; -import org.eclipse.wst.jsdt.core.ast.IFunctionExpression; import org.eclipse.wst.jsdt.core.compiler.CategorizedProblem; import org.eclipse.wst.jsdt.core.compiler.CharOperation; import org.eclipse.wst.jsdt.core.infer.InferredAttribute; @@ -53,6 +52,7 @@ import org.eclipse.wst.jsdt.internal.compiler.ast.MessageSend; import org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration; import org.eclipse.wst.jsdt.internal.compiler.ast.NameReference; import org.eclipse.wst.jsdt.internal.compiler.ast.ObjectLiteral; +import org.eclipse.wst.jsdt.internal.compiler.ast.ObjectLiteralField; import org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedAllocationExpression; import org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedNameReference; import org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedTypeReference; @@ -76,6 +76,7 @@ import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeConstants; import org.eclipse.wst.jsdt.internal.compiler.parser.SourceTypeConverter; import org.eclipse.wst.jsdt.internal.compiler.problem.AbortCompilation; import org.eclipse.wst.jsdt.internal.compiler.problem.ProblemReporter; +import org.eclipse.wst.jsdt.internal.compiler.util.HashtableOfInt; import org.eclipse.wst.jsdt.internal.compiler.util.HashtableOfObject; import org.eclipse.wst.jsdt.internal.compiler.util.HashtableOfObjectToInt; import org.eclipse.wst.jsdt.internal.compiler.util.Util; @@ -159,50 +160,152 @@ public class LocalDeclarationVisitor extends ASTVisitor { * A context is defined by either the top level or a closure (function) */ protected ASTVisitor contextDeclarationNotifier = new ASTVisitor(){ + + /** + * Key: int - function depth + *
+ * Value: ArrayList<String> locals defined at key depth + */ + private HashtableOfInt locals = new HashtableOfInt(); public boolean visit(LocalDeclaration localDeclaration, BlockScope scope) { - if (NOTIFY_LOCALS || nestedMethodIndex==0) + if (NOTIFY_LOCALS || nestedMethodIndex==1) { notifySourceElementRequestor( localDeclaration, null ); + + //visit method declaration on RHS of declaration if at nest level 0 + AbstractMethodDeclaration methodDecl = AbstractMethodDeclaration.findMethodDeclaration(localDeclaration); + if(methodDecl != null) { + notifySourceElementRequestor(methodDecl); + } + } + + //store the local declaration at the current nest level + storeLocal(localDeclaration.name, nestedMethodIndex); + return true; } - - /* - * Stop visiting here because the method opens a new context - */ public boolean visit(MethodDeclaration methodDeclaration, Scope scope) { - //only functions with names are notified - nestedMethodIndex++; - if( methodDeclaration.selector != null && methodDeclaration.selector.length > 0 ) + /* only non anonymous functions are notified here + * other functions will be notified from assignment and local declaration visits + */ + char[] name = methodDeclaration.getName(); + if( !methodDeclaration.isConstructor() && !methodDeclaration.isAnonymous() && name != null && name.length > 0 && (nestedMethodIndex == 1 || NOTIFY_LOCALS)) { notifySourceElementRequestor( methodDeclaration ); - return false; + } + + nestedMethodIndex++; + return true; + } + + //visit closures and add them as a source method in the model + public boolean visit(MessageSend messageSend, BlockScope scope) { + if (messageSend.receiver instanceof FunctionExpression) { + MethodDeclaration methodDecl = ((FunctionExpression) messageSend.receiver).methodDeclaration; + if (methodDecl != null && nestedMethodIndex == 1) { + notifySourceElementRequestor(methodDecl); + } + } + return true; } /** - *

Visit assignments so that if the right hand side is a function it can be indexed - * with the right hand side used as the selector.

- * * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.Assignment, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope) */ public boolean visit(Assignment assignment, BlockScope scope) { boolean keepVisiting = true; - IExpression righHandSide = assignment.getExpression(); - if(righHandSide instanceof IFunctionExpression) { - IExpression leftHandSide = assignment.getLeftHandSide(); + + IExpression leftHandSide = assignment.getLeftHandSide(); + + if(leftHandSide instanceof SingleNameReference && !containsLocal(((SingleNameReference)leftHandSide).token, nestedMethodIndex)) { + notifySourceElementRequestor(assignment, null); - char[] selector = Util.getTypeName(leftHandSide); - MethodDeclaration methodDecl = ((IFunctionExpression) righHandSide).getMethodDeclaration(); - if (selector != null && methodDecl.isConstructor()) { - notifySourceElementRequestor(methodDecl, selector); + //visit method declaration as long as local scope does not contain the single name reference + AbstractMethodDeclaration methodDecl = AbstractMethodDeclaration.findMethodDeclaration(assignment); + if(methodDecl != null) { + notifySourceElementRequestor(methodDecl); } + } else { + /* this is to prevent visiting expressions like: + * MyType.prototype.myFunc = ... + * They will be visited when visiting the type + */ + keepVisiting = false; } + + return keepVisiting; + } + + public boolean visit(Argument argument, BlockScope scope) { + boolean keepVisiting = true; + storeLocal(argument.name, nestedMethodIndex); return keepVisiting; } + /** + * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.ObjectLiteral, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope) + */ + public boolean visit(ObjectLiteral literal, BlockScope scope) { + //it is considered a nest level when inside an object literal + nestedMethodIndex++; + return true; + } + + /** + * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#endVisit(org.eclipse.wst.jsdt.internal.compiler.ast.ObjectLiteral, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope) + */ + public void endVisit(ObjectLiteral literal, BlockScope scope) { + //it is considered a nest level when inside an object literal + nestedMethodIndex--; + } + + public boolean visit(ObjectLiteralField field, BlockScope scope) { + //store the local declaration at the current nest level + if(field.getFieldName() instanceof SingleNameReference) + storeLocal(((SingleNameReference)field.getFieldName()).token, nestedMethodIndex); + return true; + } + public void endVisit(MethodDeclaration methodDeclaration, Scope scope) { + clearLocals(nestedMethodIndex); nestedMethodIndex--; + } + + private void storeLocal(char[] localName, int methodDepth) { + ArrayList localList = (ArrayList) locals.get(methodDepth); + if(localList == null) { + localList = new ArrayList(); + locals.put(methodDepth, localList); + } + + //store as string so that contains works correctly + String local = new String(localName); + if(!localList.contains(local)) + localList.add(local); + } + + private boolean containsLocal(char[] localName, int methodDepth) { + while(methodDepth >= 1) { + ArrayList localList = (ArrayList) locals.get(methodDepth); + if(localList == null) { + methodDepth--; + continue; + } + //list contains strings so that #contains call works as expected + if(localList.contains(new String(localName))) + return true; + methodDepth--; + } + return false; + } + + private void clearLocals(int methodDepth) { + ArrayList localList = (ArrayList) locals.get(methodDepth); + if(localList != null) { + localList.clear(); + } } }; @@ -255,6 +358,9 @@ public SourceElementParser( if (useSourceJavadocParser) { this.javadocParser = new SourceJavadocParser(this); } + + // must start at 1 because HashtableOfInt can not contain 0 + this.nestedMethodIndex = 1; } public void setRequestor(ISourceElementRequestor requestor) { @@ -347,7 +453,7 @@ public void checkComment() { } else if (reference instanceof JavadocMessageSend) { JavadocMessageSend messageSend = (JavadocMessageSend) reference; int argCount = messageSend.arguments == null ? 0 : messageSend.arguments.length; - this.requestor.acceptMethodReference(messageSend.selector, argCount, messageSend.sourceStart); + this.requestor.acceptMethodReference(messageSend.selector, messageSend.sourceStart); this.requestor.acceptConstructorReference(messageSend.selector, argCount, messageSend.sourceStart); if (messageSend.receiver != null && !messageSend.receiver.isThis()) { acceptJavadocTypeReference(messageSend.receiver); @@ -458,7 +564,6 @@ protected void consumeCallExpressionWithArguments() { if (reportReferenceInfo) { requestor.acceptMethodReference( messageSend.selector, - args == null ? 0 : args.length, (int)(messageSend.nameSourcePosition >>> 32)); } } @@ -704,21 +809,21 @@ public void notifySourceElementRequestor(CompilationUnitDeclaration parsedUnit) } public void notifySourceElementRequestor( InferredType type ) { - - if ( !type.isDefinition || type.isEmptyGlobal()) - return; - - if (type.isAnonymous && !type.isNamed() && !type.isObjectLiteral) + //do not notify if type is not a definition or not global + if ( !type.isDefinition() || !type.isIndexed()) { return; - // prevent possible recurrsion - if (notifiedTypes.containsKey(type.getName())) + } + + // prevent possible recursion + if (notifiedTypes.containsKey(type.getName())) { return; - notifiedTypes.put(type.getName(), null); + } - + //notify the requester of the type + notifiedTypes.put(type.getName(), null); ISourceElementRequestor.TypeInfo typeInfo = new ISourceElementRequestor.TypeInfo(); typeInfo.declarationStart = type.sourceStart; - typeInfo.modifiers = 0; + typeInfo.modifiers = type.getModifiers(); typeInfo.name = type.getName(); @@ -732,10 +837,22 @@ public void notifySourceElementRequestor( InferredType type ) { typeInfo.secondary = false; typeInfo.anonymousMember = type.isAnonymous; - + typeInfo.isIndexed = type.isIndexed(); + + //add synonym info + InferredType[] synonyms = type.getSynonyms(); + if(synonyms != null) { + char[][] synonymsNames = new char[synonyms.length][]; + for(int i = 0; i < synonyms.length; ++i) { + synonymsNames[i] = synonyms[i].getName(); + } + typeInfo.synonyms = synonymsNames; + } + requestor.enterType(typeInfo); - - for (int attributeInx=0; attributeInx= assignment.sourceEnd; + + int fieldEndPosition = this.sourceEnds.get(assignment); + if (fieldEndPosition == -1) { + // use the declaration source end by default + fieldEndPosition = assignment.sourceEnd; + } + + if (isInRange) { + if(assignment.getLeftHandSide() instanceof SingleNameReference) { + SingleNameReference lhs = (SingleNameReference) assignment.getLeftHandSide(); + ISourceElementRequestor.FieldInfo fieldInfo = new ISourceElementRequestor.FieldInfo(); + fieldInfo.declarationStart = assignment.sourceStart; + fieldInfo.name = lhs.getToken(); + fieldInfo.type = assignment.inferredType != null ? assignment.inferredType + .getName() + : null; + fieldInfo.nameSourceStart = assignment.sourceStart; + fieldInfo.nameSourceEnd = assignment.sourceEnd; + fieldInfo.categories = (char[][]) this.nodesToCategories + .get(assignment); + requestor.enterField(fieldInfo); + //If this field is of an anonymous type, need to notify so that it shows as a child + if (assignment.inferredType != null + && assignment.inferredType.isAnonymous) { + notifySourceElementRequestor(assignment.inferredType); + } + } + } + if (isInRange){ + requestor.exitField( + // filter out initializations that are not a constant (simple check) + (assignment.getExpression() == null + || assignment.getExpression() instanceof ArrayInitializer + || assignment.getExpression() instanceof AllocationExpression + || assignment.getExpression() instanceof ArrayAllocationExpression + || assignment.getExpression() instanceof Assignment + || assignment.getExpression() instanceof ClassLiteralAccess + || assignment.getExpression() instanceof MessageSend + || assignment.getExpression() instanceof ArrayReference + || assignment.getExpression() instanceof ThisReference) ? + -1 : + assignment.sourceStart, + fieldEndPosition, + assignment.sourceEnd); + } +} public void notifySourceElementRequestor( ImportReference importReference, boolean isPackage) { @@ -1405,24 +1614,31 @@ private int sourceEnd(TypeDeclaration typeDeclaration) { return typeDeclaration.sourceEnd; } } -private void visitIfNeeded(AbstractMethodDeclaration method) { - if (this.localDeclarationVisitor != null - //&& (method.bits & ASTNode.HasLocalType) != 0) { - ){ + private void visitIfNeeded(AbstractMethodDeclaration method) { + this.nestedMethodIndex++; + + if (this.localDeclarationVisitor != null){ if (method instanceof ConstructorDeclaration) { ConstructorDeclaration constructorDeclaration = (ConstructorDeclaration) method; if (constructorDeclaration.constructorCall != null) { - constructorDeclaration.constructorCall.traverse(this.localDeclarationVisitor, method.scope); + constructorDeclaration.constructorCall.traverse(this.localDeclarationVisitor, method.getScope()); } } + if (method.arguments != null) { + int argumentLength = method.arguments.length; + for (int i = 0; i < argumentLength; i++) + method.arguments[i].traverse(contextDeclarationNotifier, method.getScope()); + } if (method.statements != null) { int statementsLength = method.statements.length; - for (int i = 0; i < statementsLength; i++) - //method.statements[i].traverse(this.localDeclarationVisitor, method.scope); - method.statements[i].traverse( contextDeclarationNotifier, method.scope ); + for (int i = 0; i < statementsLength; i++) { + method.statements[i].traverse( contextDeclarationNotifier, method.getScope() ); + } } + } + + this.nestedMethodIndex--; } -} private void visitIfNeeded(AbstractVariableDeclaration field, TypeDeclaration declaringType) { if (this.localDeclarationVisitor != null diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ASTNode.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ASTNode.java index da894d15..6bb514b8 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ASTNode.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ASTNode.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -199,9 +199,6 @@ public abstract class ASTNode implements TypeConstants, TypeIds, IASTNode { public static final int IsVarArgs = Bit15; public static final int IgnoreRawTypeCheck = Bit31; - // for array initializer - public static final int IsAnnotationDefaultValue = Bit1; - // for null reference analysis public static final int IsNonNull = Bit18; @@ -229,7 +226,6 @@ public abstract class ASTNode implements TypeConstants, TypeIds, IASTNode { // constants used when checking invocation arguments public static final int INVOCATION_ARGUMENT_OK = 0; public static final int INVOCATION_ARGUMENT_UNCHECKED = 1; - public static final int INVOCATION_ARGUMENT_WILDCARD = 2; public ASTNode() { diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/AbstractMethodDeclaration.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/AbstractMethodDeclaration.java index 0af6e515..30708988 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/AbstractMethodDeclaration.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/AbstractMethodDeclaration.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -16,6 +16,9 @@ import java.util.List; import org.eclipse.wst.jsdt.core.ast.IASTNode; import org.eclipse.wst.jsdt.core.ast.IAbstractFunctionDeclaration; import org.eclipse.wst.jsdt.core.ast.IArgument; +import org.eclipse.wst.jsdt.core.ast.IAssignment; +import org.eclipse.wst.jsdt.core.ast.IFunctionDeclaration; +import org.eclipse.wst.jsdt.core.ast.IFunctionExpression; import org.eclipse.wst.jsdt.core.ast.IJsDoc; import org.eclipse.wst.jsdt.core.ast.IProgramElement; import org.eclipse.wst.jsdt.core.compiler.CategorizedProblem; @@ -30,8 +33,11 @@ import org.eclipse.wst.jsdt.internal.compiler.impl.ReferenceContext; import org.eclipse.wst.jsdt.internal.compiler.lookup.Binding; import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope; import org.eclipse.wst.jsdt.internal.compiler.lookup.ExtraCompilerModifiers; +import org.eclipse.wst.jsdt.internal.compiler.lookup.LocalFunctionBinding; +import org.eclipse.wst.jsdt.internal.compiler.lookup.LocalVariableBinding; import org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding; import org.eclipse.wst.jsdt.internal.compiler.lookup.MethodScope; +import org.eclipse.wst.jsdt.internal.compiler.lookup.ProblemBinding; import org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding; import org.eclipse.wst.jsdt.internal.compiler.lookup.Scope; import org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding; @@ -46,22 +52,38 @@ import org.eclipse.wst.jsdt.internal.compiler.problem.ProblemSeverities; public abstract class AbstractMethodDeclaration extends Statement implements IAbstractFunctionDeclaration, ProblemSeverities, ReferenceContext { - public MethodScope scope; + /** + *

Current scope used by this declaration.

+ */ + private MethodScope fScope; + private MethodScope prevScope; - //it is not relevent for constructor but it helps to have the name of the constructor here - //which is always the name of the class.....parsing do extra work to fill it up while it do not have to.... - public char[] selector; - public char[] potentialName; + + /** + *

The function selector

+ */ + protected char[] selector; + + /** + *

true if this function is defined as an anonymous function, + * false otherwise.

+ * + *

NOTE: A function could be defend as anonymous but + * still have a selector if assigned to a variable.

+ */ + private boolean fIsAnonymous; + public int declarationSourceStart; public int declarationSourceEnd; public int modifiers; public Argument[] arguments; public Statement[] statements; public int explicitDeclarations; - public MethodBinding binding; + protected MethodBinding binding; public boolean ignoreFurtherInvestigation = false; public boolean needFreeReturn = false; public boolean resolveChildStatments = true; + public boolean hasResolvedChildStatements = false; public Javadoc javadoc; @@ -74,10 +96,37 @@ public abstract class AbstractMethodDeclaration extends Statement public boolean errorInSignature = false; public int exprStackPtr; + + /** + *

+ * true if {@link #buildLocals(BlockScope)} has been called, + * false otherwise. + *

+ */ + private boolean fhasBuiltLocals; + + /** + *

+ * true if {@link #resolve(Scope)} has been called, + * false otherwise. + *

+ */ + private boolean fHasResolved; + + /** + *

+ * {@link IFunctionDeclaration} that this declaration is contained in, + * or null if declaration not contained in an {@link IFunctionDeclaration} + */ + private IFunctionDeclaration fContainingFunction; AbstractMethodDeclaration(CompilationResult compilationResult){ this.compilationResult = compilationResult; this.prevScope = null; + + this.fhasBuiltLocals = false; + this.fHasResolved = false; + this.fContainingFunction = null; } public void setArguments( IArgument[] args) { @@ -117,13 +166,12 @@ public abstract class AbstractMethodDeclaration extends Statement */ public void bindArguments() { //only bind arguments if the current scope does not equal the scope last used to bind args - if (this.arguments != null && (this.prevScope == null || this.prevScope != this.scope)) { - this.prevScope = this.scope; + if (this.arguments != null && (this.prevScope == null || this.prevScope != this.fScope)) { + this.prevScope = this.fScope; - // by default arguments in abstract/native methods are considered to be used (no complaint is expected) if (this.binding == null) { for (int i = 0, length = this.arguments.length; i < length; i++) { - this.arguments[i].bind(this.scope, null, true); + this.arguments[i].resolve(this.fScope); } return; } @@ -138,7 +186,7 @@ public abstract class AbstractMethodDeclaration extends Statement boolean used = this.binding.isAbstract(); for (int i = 0, length = this.arguments.length; i < length && i < this.binding.parameters.length; i++) { IArgument argument = this.arguments[i]; - argument.bind(this.scope, this.binding.parameters[i], used); + argument.bind(this.fScope, this.binding.parameters[i], used); } } } @@ -257,48 +305,68 @@ public abstract class AbstractMethodDeclaration extends Statement } public StringBuffer printReturnType(int indent, StringBuffer output) { - return output; } public void resolve(Scope upperScope) { - if (this.scope==null ) - { - this.scope = new MethodScope(upperScope,this, false); - if (this.selector!=null) { - SourceTypeBinding compilationUnitBinding = upperScope - .enclosingCompilationUnit(); - MethodBinding methodBinding = scope.createMethod(this, - this.selector, compilationUnitBinding, false, true); - if (methodBinding != null) { - this.binding = methodBinding; - methodBinding = compilationUnitBinding - .resolveTypesFor(methodBinding,this); - if (methodBinding != null) { - MethodScope enclosingMethodScope = upperScope - .enclosingMethodScope(); - if (enclosingMethodScope != null) - enclosingMethodScope.addLocalMethod(methodBinding); - else { - compilationUnitBinding.addMethod(methodBinding); - upperScope.environment().defaultPackage.addBinding( - methodBinding, methodBinding.selector, - Binding.METHOD); - } + /* resolve if the scope is not yet set or + * the locals were built causing the scope to be set without resolving */ + if (this.getScope() == null || this.fhasBuiltLocals) { + this.fHasResolved = true; + + //set the scope if it has not yet been set + if(this.getScope() == null) { + this.setScope(new MethodScope(upperScope,this, false)); + } + + SourceTypeBinding compilationUnitBinding = upperScope.enclosingCompilationUnit(); + if (this.getName()!=null && !this.hasBinding()) { + //is local if the upper scope is not a compilation unit scope + boolean isLocal = upperScope.kind != Scope.COMPILATION_UNIT_SCOPE; + + /* if inferred method has declaring binding, use that + * else use compilation unit binding */ + SourceTypeBinding declaringBinding = null; + if(this.getInferredMethod() != null && + this.getInferredMethod().inType != null && + this.getInferredMethod().inType.binding != null) { + + declaringBinding = this.getInferredMethod().inType.binding; + } else { + declaringBinding = compilationUnitBinding; + } + + //create and set the method binding + MethodBinding methodBinding = fScope.createMethod(this, + this.getName(), declaringBinding, false, isLocal); + this.setBinding(methodBinding); + } + + if (this.binding != null) { + MethodBinding methodBinding = compilationUnitBinding + .resolveTypesFor(this.binding,this); + if (methodBinding != null && methodBinding.selector != null) { + MethodScope enclosingMethodScope = upperScope.enclosingMethodScope(); + if (enclosingMethodScope != null) { + enclosingMethodScope.addLocalMethod(methodBinding); + } else { + compilationUnitBinding.addMethod(methodBinding); + upperScope.environment().defaultPackage.addBinding( + methodBinding, methodBinding.selector, + Binding.METHOD); } } } - } if (this.binding == null) { - - this.ignoreFurtherInvestigation = true; } try { - if(resolveChildStatments) { + // only need to resolve args, jsdoc, and statments once per function + if(resolveChildStatments && !hasResolvedChildStatements) { + hasResolvedChildStatements = true; bindArguments(); resolveJavadoc(); resolveStatements(); @@ -312,11 +380,11 @@ public abstract class AbstractMethodDeclaration extends Statement if (this.binding == null) return; if (this.javadoc != null) { - this.javadoc.resolve(this.scope); + this.javadoc.resolve(this.fScope); return; } if (this.binding.declaringClass != null && !this.binding.declaringClass.isLocalType()) { - this.scope.problemReporter().javadocMissing(this.sourceStart, this.sourceEnd, this.binding.modifiers); + this.fScope.problemReporter().javadocMissing(this.sourceStart, this.sourceEnd, this.binding.modifiers); } } @@ -326,38 +394,83 @@ public abstract class AbstractMethodDeclaration extends Statement List nonFunctions = null; List functions = null; for (int i = 0, length = this.statements.length; i < length; i++) { - // if this is not a function then skip it, we resolve function declarations first - if(!(this.statements[i] instanceof AbstractMethodDeclaration)) { - if(nonFunctions == null) + Statement statement = this.statements[i]; + + //look for an AbstractMethodDeclaration as part of the statement + AbstractMethodDeclaration methodDecl = null; + BlockScope scope = this.fScope; + if (statement instanceof AbstractMethodDeclaration) { + methodDecl = (AbstractMethodDeclaration)statement; + + //fully process the method declaration later + if(functions == null) { + functions = new ArrayList(); + } + functions.add(methodDecl); + } + if(methodDecl != null) { + methodDecl.resolveChildStatments = false; + methodDecl.resolve(scope); + methodDecl.resolveChildStatments = true; + } + + //if the statement itself was not a method declaration save it to processes after processing all functions + if(!(statement instanceof AbstractMethodDeclaration)) { + if(nonFunctions == null) { nonFunctions = new ArrayList(); + } nonFunctions.add(statements[i]); - } else { - // if this is a function then resolve it, but store it as well - // we need to take a second pass later to resolve its child statements - // this step will put the declaration in scope - if(functions == null) - functions = new ArrayList(); - functions.add(statements[i]); - ((AbstractMethodDeclaration)this.statements[i]).resolveChildStatments = false; - this.statements[i].resolve(this.scope); - ((AbstractMethodDeclaration)this.statements[i]).resolveChildStatments = true; } } - // now go back and resolve the non-function statements - this makes sure all functions - // are in scope in case they are called before being defined in the script file + + /* resolve all none method declarations, this includes expressions that have a child method declaration, + * such as an assignment + */ if(nonFunctions != null) { for(int j = 0; j < nonFunctions.size(); j++) { - ((Statement)nonFunctions.get(j)).resolve(this.scope); + Statement statement = (Statement)nonFunctions.get(j); + AbstractMethodDeclaration methodDecl = null; + BlockScope scope = this.fScope; + if(statement instanceof AbstractVariableDeclaration) { + AbstractVariableDeclaration variableDecl = (AbstractVariableDeclaration)statement; + if(variableDecl.initialization instanceof IFunctionExpression) { + methodDecl = ((IFunctionExpression)variableDecl.initialization).getMethodDeclaration(); + } + } else if(statement instanceof IAssignment) { + IAssignment assignment = (IAssignment)statement; + if(assignment.getExpression() instanceof IFunctionExpression) { + methodDecl = ((IFunctionExpression)assignment.getExpression()).getMethodDeclaration(); + } + + //if the LHS is an undeclared single name resolve the function at the compilation unit level + if(assignment.getLeftHandSide() instanceof SingleNameReference) { + SingleNameReference nameRef = (SingleNameReference)assignment.getLeftHandSide(); + + /* if the binding is a problem binding or not a local function + * binding then built with unit scope because it is not a local function */ + Binding binding = nameRef.findBinding(this.fScope); + if(binding instanceof ProblemBinding || !(binding instanceof LocalFunctionBinding || binding instanceof LocalVariableBinding)) { + scope = this.fScope.compilationUnitScope(); + } + } + } + if(methodDecl != null) { + methodDecl.resolveChildStatments = false; + methodDecl.resolve(scope); + methodDecl.resolveChildStatments = true; + } + statement.resolve(this.fScope); } } - // now its time to reslove the children statements of the function + + // now its time to resolve the children statements of the method declarations if(functions != null) { for(int f = 0; f < functions.size(); f++) { - ((Statement)functions.get(f)).resolve(this.scope); + ((Statement)functions.get(f)).resolve(this.fScope); } } } else if ((this.bits & UndocumentedEmptyBlock) != 0) { - this.scope.problemReporter().undocumentedEmptyBlock(this.bodyStart-1, this.bodyEnd+1); + this.fScope.problemReporter().undocumentedEmptyBlock(this.bodyStart-1, this.bodyEnd+1); } } @@ -395,8 +508,22 @@ public abstract class AbstractMethodDeclaration extends Statement return this.statements; } + /** + *

Returns this functions selector or inferred selector in that priority + * order, or null if neither are defined.

+ * + * @see org.eclipse.wst.jsdt.core.ast.IAbstractFunctionDeclaration#getName() + */ public char[] getName() { - return this.selector != null ? this.selector : this.potentialName; + char[] name = null; + + if(this.selector != null) { + name = this.selector; + } else if(this.inferredMethod != null && this.inferredMethod.name != null) { + name = this.inferredMethod.name; + } + + return name; } public void setInferredType(InferredType type) { @@ -411,11 +538,218 @@ public abstract class AbstractMethodDeclaration extends Statement return this.inferredType; } - public char [] getSafeName() { - if(this.selector != null) - return this.selector; - if(this.inferredMethod != null && this.inferredMethod.name != null) - return this.inferredMethod.name; - return new char []{}; - } -} + /** + * @return {@link MethodBinding} associated with this function declaration + */ + public MethodBinding getBinding() { + return this.binding; + } + + /** + *

Sets the {@link MethodBinding} associated with this function declaration. + * If one is already set then it will be overwritten.

+ * + * @param binding {@link MethodBinding} to associate with this function declaration + */ + public void setBinding(MethodBinding binding) { + this.binding = binding; + } + + /** + * @return true if a {@link MethodBinding} has already been associated + * with this function declaration, false otherwise. + */ + public boolean hasBinding() { + return this.binding != null; + } + + /** + *

Sets the selector.

+ * + * @param selector for this function declaration + */ + public void setSelector(char[] selector) { + this.selector = selector; + } + + /** + *

Set whether this function declared as anonymous or not.

+ * + *

NOTE: A function could be defend as anonymous but + * still have a selector if assigned to a variable.

+ * + * @param isAnonymous true if this function is anonymous, + * false otherwise + */ + public void setIsAnonymous(boolean isAnonymous) { + this.fIsAnonymous = isAnonymous; + } + + /** + *

NOTE: A function could be defend as anonymous but + * still have a selector if assigned to a variable.

+ * + * @return true if this function is anonymous, + * false otherwise. + */ + public boolean isAnonymous() { + return this.fIsAnonymous || this.getName() == null; + } + + /** + * @param scope + * {@link MethodScope} to use for this declaration + */ + public void setScope(MethodScope scope) { + this.fScope = scope; + } + + /** + * @return {@link MethodScope} used by this declaration, or + * null if none is set + */ + public MethodScope getScope() { + return this.fScope; + } + + /** + * @param containingFunction {@link IFunctionDeclaration} that contains this declaration + */ + public void setContainingFunction(IFunctionDeclaration containingFunction) { + //declaration can never and should never contain itself + if(containingFunction != this) { + this.fContainingFunction = containingFunction; + } + } + + /** + * @return {@link IFunctionDeclaration} that contains this declaration, + * or null if this declaration is not contained in an {@link IFunctionDeclaration} + */ + public IFunctionDeclaration getContainingFunction() { + return this.fContainingFunction; + } + + /** + *

+ * Finds all of the variables and functions defined in this function + * declaration and adds them to this functions scope. + *

+ * + *

+ * This is much cheaper then {@link #resolve(Scope)} and should be used + * whenever possible. + *

+ * + *

+ * NOTE: This is a no-op if this function has already been invoked + * or {@link #resolve(Scope)} has already been invoked. + *

+ * + * @param givenUpperScope + * {@link BlockScope} to use as the upper scope for this + * functions scope + */ + public void buildLocals(Scope givenUpperScope) { + //this is not resolving, but there is no point in doing it if already resolved + if(!this.fhasBuiltLocals && !this.fHasResolved) { + this.fhasBuiltLocals = true; + + //build the locals all for all of the containing functions + Scope upperScope = givenUpperScope; + IFunctionDeclaration containingFunc = this.getContainingFunction(); + if(containingFunc instanceof AbstractMethodDeclaration) { + ((AbstractMethodDeclaration) containingFunc).buildLocals(givenUpperScope); + upperScope = ((AbstractMethodDeclaration) containingFunc).getScope(); + } + + //create scope if it has not yet been created + if (this.getScope() == null ) { + this.setScope(new MethodScope(upperScope, this, false)); + } + + //traverse this functions statements looking for variables and functions + this.traverse(new ASTVisitor() { + /** + * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.Argument, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope) + */ + public boolean visit(Argument argument, BlockScope scope) { + if(scope != null && scope instanceof MethodScope) { + ((MethodScope) scope).addUnresolvedLocalVar(argument.getName(), argument); + } + + return true; + } + + /** + * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope) + */ + public boolean visit(LocalDeclaration localDeclaration, BlockScope scope) { + if(scope != null && scope instanceof MethodScope) { + /* be sure to add all variable declarations + * + * var b, c, d = "foo" */ + AbstractVariableDeclaration currVarDecl = localDeclaration; + while(currVarDecl != null) { + ((MethodScope) scope).addUnresolvedLocalVar(currVarDecl.getName(), currVarDecl); + + currVarDecl = currVarDecl.nextLocal; + } + } + + return true; + } + + /** + * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration, org.eclipse.wst.jsdt.internal.compiler.lookup.Scope) + */ + public boolean visit(MethodDeclaration methodDeclaration, Scope scope) { + boolean isSelf = AbstractMethodDeclaration.this == methodDeclaration; + if(scope != null && scope instanceof MethodScope) { + if(!isSelf) { + ((MethodScope) scope).addUnresolvedLocalFunc(methodDeclaration.getName(), methodDeclaration); + } + } + + return isSelf; + } + }, this.getScope()); + } + } + + /** + *

Given an {@link IProgramElement} returns the {@link AbstractMethodDeclaration} + * if there is one in the given element. The element itself could be the method, or + * the method could be part of a declaration, assignment, and so on.

+ * + * @param element to search for an {@link AbstractMethodDeclaration} + * + * @return {@link AbstractMethodDeclaration} if the given {@link IProgramElement} contains + * one, null otherwise + */ + public static AbstractMethodDeclaration findMethodDeclaration(IProgramElement element) { + AbstractMethodDeclaration methodDecl = null; + + /* if the statement is a method declaration + * else if statement is a variable declaration that could have a function assigned to it + * else if the statement is an assignment that could be assigning a function to a variable + */ + if (element instanceof AbstractMethodDeclaration) { + methodDecl = (AbstractMethodDeclaration)element; + } else if(element instanceof AbstractVariableDeclaration) { + AbstractVariableDeclaration variableDecl = (AbstractVariableDeclaration)element; + if(variableDecl.initialization instanceof IFunctionExpression) { + methodDecl = ((IFunctionExpression)variableDecl.initialization).getMethodDeclaration(); + } + } else if(element instanceof IAssignment) { + IAssignment assignment = (IAssignment)element; + if(assignment.getExpression() instanceof IFunctionExpression) { + methodDecl = ((IFunctionExpression)assignment.getExpression()).getMethodDeclaration(); + } + } else if(element instanceof IFunctionExpression) { + methodDecl = ((IFunctionExpression)element).getMethodDeclaration(); + } + + return methodDecl; + } +} \ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/AbstractVariableDeclaration.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/AbstractVariableDeclaration.java index 90d657f2..a90f833b 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/AbstractVariableDeclaration.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/AbstractVariableDeclaration.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -39,12 +39,30 @@ public abstract class AbstractVariableDeclaration extends Statement implements public TypeReference type; public AbstractVariableDeclaration nextLocal; + + /** + *

+ * true if this variable declaration is actually a reference to a type, + * rather then the instance of a type. false if this variable is + * a reference to an instance of a type rather then the type itself. + *

+ */ + private boolean fIsType; + /** + *

+ * Default constructor. + *

+ */ + public AbstractVariableDeclaration() { + this.fIsType = false; + } + public InferredType getInferredType() { return this.inferredType; } - public void setInferredType(InferredType type) { + public void setInferredType(InferredType type) { this.inferredType = type; } @@ -159,4 +177,18 @@ public abstract class AbstractVariableDeclaration extends Statement implements { return this.initialization; } + + /** + * @see org.eclipse.wst.jsdt.core.ast.IAssignment#setIsType(boolean) + */ + public void setIsType(boolean isType) { + this.fIsType = isType; + } + + /** + * @see org.eclipse.wst.jsdt.core.ast.IAssignment#isType() + */ + public boolean isType() { + return this.fIsType; + } } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Argument.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Argument.java index 707b418c..5a1a7753 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Argument.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Argument.java @@ -39,37 +39,25 @@ public class Argument extends LocalDeclaration implements IArgument { } public void bind(MethodScope scope, TypeBinding typeBinding, boolean used) { - // record the resolved type into the type reference - Binding existingVariable = scope.getLocalBinding(name, Binding.VARIABLE, this, false /*do not resolve hidden field*/); - if (existingVariable != null && existingVariable.isValidBinding() && existingVariable instanceof LocalVariableBinding ){ + + if (existingVariable != this.binding && existingVariable != null && existingVariable.isValidBinding() && existingVariable instanceof LocalVariableBinding ){ LocalVariableBinding localVariableBinding=(LocalVariableBinding)existingVariable; -// if (existingVariable instanceof LocalVariableBinding && this.hiddenVariableDepth == 0) { -// scope.problemReporter().redefineArgument(this); -// } else { -// boolean isSpecialArgument = false; -// if (existingVariable instanceof FieldBinding) { -// if (scope.isInsideConstructor()) { -// isSpecialArgument = true; // constructor argument -// } else { -// AbstractMethodDeclaration methodDecl = scope.referenceMethod(); -// if (methodDecl != null && CharOperation.prefixEquals(SET, methodDecl.selector)) { -// isSpecialArgument = true; // setter argument -// } -// } -// } - if (localVariableBinding.declaringScope.compilationUnitScope()==scope.compilationUnitScope()) + if (localVariableBinding.declaringScope.compilationUnitScope()==scope.compilationUnitScope()) { scope.problemReporter().localVariableHiding(this, existingVariable, false); -// } + } } if (this.binding == null) { this.binding = new LocalVariableBinding(this, typeBinding, this.modifiers, true); } - scope.addLocalVariable( this.binding ); -// if (JavaScriptCore.IS_ECMASCRIPT4) -// resolveAnnotations(scope, this.annotations, this.binding); + + //only add as local binding if the existing local binding is not the binding for this arg + if(existingVariable != this.binding) { + scope.addLocalVariable( this.binding ); + } + //true stand for argument instead of just local this.binding.declaration = this; this.binding.useFlag = used ? LocalVariableBinding.USED : LocalVariableBinding.UNUSED; diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ArrayInitializer.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ArrayInitializer.java index 7b5f95fc..fe34a462 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ArrayInitializer.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ArrayInitializer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -86,10 +86,6 @@ public class ArrayInitializer extends Expression implements IArrayInitializer { this.constant = Constant.NotAConstant; if (expectedType instanceof ArrayBinding) { - // allow new List[5] - if ((this.bits & IsAnnotationDefaultValue) == 0) { // annotation default value need only to be commensurate JLS9.7 - // allow new List[5] - only check for generic array when no initializer, since also checked inside initializer resolution - } this.resolvedType = this.binding = (ArrayBinding) expectedType; if (this.expressions == null) return this.binding; diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ArrayQualifiedTypeReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ArrayQualifiedTypeReference.java index 82ec9083..32ef489a 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ArrayQualifiedTypeReference.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ArrayQualifiedTypeReference.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Assignment.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Assignment.java index 97942cf5..c9b222de 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Assignment.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Assignment.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -14,6 +14,7 @@ package org.eclipse.wst.jsdt.internal.compiler.ast; import org.eclipse.wst.jsdt.core.ast.IASTNode; import org.eclipse.wst.jsdt.core.ast.IAssignment; import org.eclipse.wst.jsdt.core.ast.IExpression; +import org.eclipse.wst.jsdt.core.ast.IFunctionDeclaration; import org.eclipse.wst.jsdt.core.ast.IJsDoc; import org.eclipse.wst.jsdt.core.infer.InferredType; import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor; @@ -35,224 +36,270 @@ public class Assignment extends Expression implements IAssignment { public Javadoc javadoc; public InferredType inferredType; -public Assignment(Expression lhs, Expression expression, int sourceEnd) { - //lhs is always a reference by construction , - //but is build as an expression ==> the checkcast cannot fail - this.lhs = lhs; - lhs.bits |= IsStrictlyAssigned; // tag lhs as assigned - this.expression = expression; - this.sourceStart = lhs.sourceStart; - this.sourceEnd = sourceEnd; -} - -public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) { - // record setting a variable: various scenarii are possible, setting an array reference, -// a field reference, a blank final field reference, a field of an enclosing instance or -// just a local variable. - LocalVariableBinding local = this.lhs.localVariableBinding(); -// if (local!=null && local.isSameCompilationUnit(currentScope)) -// local=null; - int nullStatus = this.expression.nullStatus(flowInfo); - if (local != null && (local.type.tagBits & TagBits.IsBaseType) == 0) { - if (nullStatus == FlowInfo.NULL) { - flowContext.recordUsingNullReference(currentScope, local, this.lhs, - FlowContext.CAN_ONLY_NULL| FlowContext.IN_ASSIGNMENT, flowInfo); - } + /** + *

+ * true if this assignment is actually a assigning a type, + * rather then the instance of a type. false if this assignment is + * a assigning an instance of a type rather then the type itself. + *

+ */ + private boolean fIsType; + + /** + *

+ * {@link IFunctionDeclaration} that this assignment is contained in, + * or null if assignment not contained in an {@link IFunctionDeclaration} + */ + private IFunctionDeclaration fContainingFunction; + + public Assignment(Expression lhs, Expression expression, int sourceEnd) { + // lhs is always a reference by construction , + // but is build as an expression ==> the checkcast cannot fail + this.lhs = lhs; + lhs.bits |= IsStrictlyAssigned; // tag lhs as assigned + this.expression = expression; + this.sourceStart = lhs.sourceStart; + this.sourceEnd = sourceEnd; + + this.fIsType = false; } - flowInfo = ((Reference) lhs) - .analyseAssignment(currentScope, flowContext, flowInfo, this, false) - .unconditionalInits(); - if (local != null && (local.type.tagBits & TagBits.IsBaseType) == 0) { - switch(nullStatus) { - case FlowInfo.NULL : - flowInfo.markAsDefinitelyNull(local); - break; - case FlowInfo.NON_NULL : - flowInfo.markAsDefinitelyNonNull(local); - break; - default: - flowInfo.markAsDefinitelyUnknown(local); + + public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) { + /* record setting a variable: various scenarii are possible, setting an array reference, + * a field reference, a blank final field reference, a field of an enclosing instance or + * just a local variable. */ + LocalVariableBinding local = this.lhs.localVariableBinding(); + int nullStatus = this.expression.nullStatus(flowInfo); + if (local != null && (local.type.tagBits & TagBits.IsBaseType) == 0) { + if (nullStatus == FlowInfo.NULL) { + flowContext.recordUsingNullReference(currentScope, local, this.lhs, FlowContext.CAN_ONLY_NULL | FlowContext.IN_ASSIGNMENT, flowInfo); + } } - if (flowContext.initsOnFinally != null) { - switch(nullStatus) { + flowInfo = ((Reference) lhs).analyseAssignment(currentScope, flowContext, flowInfo, this, false).unconditionalInits(); + if (local != null && (local.type.tagBits & TagBits.IsBaseType) == 0) { + switch (nullStatus) { case FlowInfo.NULL : - flowContext.initsOnFinally.markAsDefinitelyNull(local); + flowInfo.markAsDefinitelyNull(local); break; case FlowInfo.NON_NULL : - flowContext.initsOnFinally.markAsDefinitelyNonNull(local); + flowInfo.markAsDefinitelyNonNull(local); break; - default: - flowContext.initsOnFinally.markAsDefinitelyUnknown(local); + default : + flowInfo.markAsDefinitelyUnknown(local); + } + if (flowContext.initsOnFinally != null) { + switch (nullStatus) { + case FlowInfo.NULL : + flowContext.initsOnFinally.markAsDefinitelyNull(local); + break; + case FlowInfo.NON_NULL : + flowContext.initsOnFinally.markAsDefinitelyNonNull(local); + break; + default : + flowContext.initsOnFinally.markAsDefinitelyUnknown(local); + } } } + return flowInfo; } - return flowInfo; -} -void checkAssignment(BlockScope scope, TypeBinding lhsType, TypeBinding rhsType) { -// FieldBinding leftField = getLastField(this.lhs); -// if (leftField != null && !leftField.isStatic() && leftField.declaringClass != null /*length pseudo field*/&& leftField.declaringClass.isRawType()) { -// scope.problemReporter().unsafeRawFieldAssignment(leftField, rhsType, this.lhs); -// } else -} - -public static Binding getDirectBinding(Expression someExpression) { - if ((someExpression.bits & ASTNode.IgnoreNoEffectAssignCheck) != 0) { + public static Binding getDirectBinding(Expression someExpression) { + if ((someExpression.bits & ASTNode.IgnoreNoEffectAssignCheck) != 0) { + return null; + } + if (someExpression instanceof SingleNameReference) { + return ((SingleNameReference) someExpression).binding; + } + else if (someExpression instanceof FieldReference) { + FieldReference fieldRef = (FieldReference) someExpression; + if (fieldRef.receiver.isThis() && !(fieldRef.receiver instanceof QualifiedThisReference)) { + return fieldRef.binding; + } + } + else if (someExpression instanceof Assignment) { + Expression lhs = ((Assignment) someExpression).lhs; + if ((lhs.bits & ASTNode.IsStrictlyAssigned) != 0) { + // i = i = ...; // eq to int i = ...; + return getDirectBinding(((Assignment) someExpression).lhs); + } + else if (someExpression instanceof PrefixExpression) { + // i = i++; // eq to ++i; + return getDirectBinding(((Assignment) someExpression).lhs); + } + } + return null; } - if (someExpression instanceof SingleNameReference) { - return ((SingleNameReference)someExpression).binding; - } else if (someExpression instanceof FieldReference) { - FieldReference fieldRef = (FieldReference)someExpression; - if (fieldRef.receiver.isThis() && !(fieldRef.receiver instanceof QualifiedThisReference)) { - return fieldRef.binding; + + public int nullStatus(FlowInfo flowInfo) { + return this.expression.nullStatus(flowInfo); + } + + public StringBuffer print(int indent, StringBuffer output) { + // no () when used as a statement + printIndent(indent, output); + return printExpressionNoParenthesis(indent, output); + } + + public StringBuffer printExpression(int indent, StringBuffer output) { + // subclass redefine printExpressionNoParenthesis() + output.append('('); + return printExpressionNoParenthesis(0, output).append(')'); + } + + public StringBuffer printExpressionNoParenthesis(int indent, StringBuffer output) { + lhs.printExpression(indent, output).append(" = "); //$NON-NLS-1$ + return expression.printExpression(0, output); + } + + public StringBuffer printStatement(int indent, StringBuffer output) { + // no () when used as a statement + return print(indent, output).append(';'); + } + + public TypeBinding resolveType(BlockScope scope) { + // due to syntax lhs may be only a NameReference, a FieldReference or an ArrayReference + this.constant = Constant.NotAConstant; + if (!(this.lhs instanceof Reference) || this.lhs.isThis()) { + scope.problemReporter().expressionShouldBeAVariable(this.lhs); + return null; } - } else if (someExpression instanceof Assignment) { - Expression lhs = ((Assignment)someExpression).lhs; - if ((lhs.bits & ASTNode.IsStrictlyAssigned) != 0) { - // i = i = ...; // eq to int i = ...; - return getDirectBinding (((Assignment)someExpression).lhs); - } else if (someExpression instanceof PrefixExpression) { - // i = i++; // eq to ++i; - return getDirectBinding (((Assignment)someExpression).lhs); + + /* if the inferred type for this assignment already has a binding use + * that. + * + * This is to prevent an assignment from overwriting the type for a + * variable that has been assigned to multiple times and all of those + * types have been combined into one type */ + TypeBinding rhsType = this.expression.resolveType(scope); + if (this.getInferredType() != null && this.getInferredType().binding != null) { + rhsType = this.getInferredType().binding; } - } -// } else if (someExpression instanceof PostfixExpression) { // recurse for postfix: i++ --> i -// // note: "b = b++" is equivalent to doing nothing, not to "b++" -// return getDirectBinding(((PostfixExpression) someExpression).lhs); - return null; -} + TypeBinding lhsType = lhs.resolveType(scope, true, rhsType); -public int nullStatus(FlowInfo flowInfo) { - return this.expression.nullStatus(flowInfo); -} + if (lhsType != null) { + this.resolvedType = lhsType; + } + + if (lhsType == null || rhsType == null) { + return null; + } -public StringBuffer print(int indent, StringBuffer output) { - //no () when used as a statement - printIndent(indent, output); - return printExpressionNoParenthesis(indent, output); -} -public StringBuffer printExpression(int indent, StringBuffer output) { - //subclass redefine printExpressionNoParenthesis() - output.append('('); - return printExpressionNoParenthesis(0, output).append(')'); -} + // check if the lhs is prototype, in which case we are done + if (lhs instanceof FieldReference && ((FieldReference) lhs).isPrototype()) + return this.resolvedType; -public StringBuffer printExpressionNoParenthesis(int indent, StringBuffer output) { - lhs.printExpression(indent, output).append(" = "); //$NON-NLS-1$ - return expression.printExpression(0, output); -} + // check for assignment with no effect + Binding left = getDirectBinding(this.lhs); + if (left != null && left == getDirectBinding(this.expression)) { + scope.problemReporter().assignmentHasNoEffect(this, left.shortReadableName()); + } -public StringBuffer printStatement(int indent, StringBuffer output) { - //no () when used as a statement - return print(indent, output).append(';'); -} -public TypeBinding resolveType(BlockScope scope) { - // due to syntax lhs may be only a NameReference, a FieldReference or an ArrayReference - this.constant = Constant.NotAConstant; - if (!(this.lhs instanceof Reference) || this.lhs.isThis()) { - scope.problemReporter().expressionShouldBeAVariable(this.lhs); - return null; - } - TypeBinding rhsType = this.expression.resolveType(scope); - TypeBinding lhsType = lhs.resolveType(scope,true,rhsType); -// this.expression.setExpectedType(lhsType); // needed in case of generic method invocation - if (lhsType != null) - this.resolvedType = lhsType; - if (lhsType == null || rhsType == null) { - return null; + if ((this.expression.isConstantValueOfTypeAssignableToType(rhsType, lhsType) || + (lhsType.isBaseType() && BaseTypeBinding.isWidening(lhsType.id, rhsType.id))) || + rhsType.isCompatibleWith(lhsType)) { + + return this.resolvedType; + } + // narrowing then boxing ? + else if (scope.isBoxingCompatibleWith(rhsType, lhsType) || (rhsType.isBaseType() + && scope.compilerOptions().sourceLevel >= ClassFileConstants.JDK1_5 // autoboxing + && !lhsType.isBaseType() && this.expression.isConstantValueOfTypeAssignableToType(rhsType, scope.environment().computeBoxingType(lhsType)))) { + return this.resolvedType; + } + if (rhsType.isFunctionType() && this.lhs.isTypeReference()) { + return lhsType; + } + + return lhsType; } - //check if the lhs is prototype, in which case we are done - if( lhs instanceof FieldReference && ((FieldReference)lhs).isPrototype() ) - return this.resolvedType; + /** + * @see org.eclipse.wst.jsdt.internal.compiler.ast.Expression#resolveTypeExpecting(org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope, + * org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding) + */ + public TypeBinding resolveTypeExpecting(BlockScope scope, TypeBinding expectedType) { - // check for assignment with no effect - Binding left = getDirectBinding(this.lhs); - if (left != null && left == getDirectBinding(this.expression)) { - scope.problemReporter().assignmentHasNoEffect(this, left.shortReadableName()); + TypeBinding type = super.resolveTypeExpecting(scope, expectedType); + if (type == null) + return null; + TypeBinding lhsType = this.resolvedType; + + // signal possible accidental boolean assignment (instead of using '==' operator) + if (expectedType == TypeBinding.BOOLEAN && lhsType == TypeBinding.BOOLEAN && (this.lhs.bits & IsStrictlyAssigned) != 0) { + scope.problemReporter().possibleAccidentalBooleanAssignment(this); + } + + return type; } - // Compile-time conversion of base-types : implicit narrowing integer into byte/short/character - // may require to widen the rhs expression at runtime -// if (lhsType != rhsType) // must call before computeConversion() and typeMismatchError() -// scope.compilationUnitScope().recordTypeConversion(lhsType, rhsType); - - - if ((this.expression.isConstantValueOfTypeAssignableToType(rhsType, lhsType) - || (lhsType.isBaseType() && BaseTypeBinding.isWidening(lhsType.id, rhsType.id))) - || rhsType.isCompatibleWith(lhsType)) { -// this.expression.computeConversion(scope, lhsType, rhsType); - checkAssignment(scope, lhsType, rhsType); - return this.resolvedType; - } else if (scope.isBoxingCompatibleWith(rhsType, lhsType) - || (rhsType.isBaseType() // narrowing then boxing ? - && scope.compilerOptions().sourceLevel >= ClassFileConstants.JDK1_5 // autoboxing - && !lhsType.isBaseType() - && this.expression.isConstantValueOfTypeAssignableToType(rhsType, scope.environment().computeBoxingType(lhsType)))) { - return this.resolvedType; + public void traverse(ASTVisitor visitor, BlockScope scope) { + if (visitor.visit(this, scope)) { + lhs.traverse(visitor, scope); + expression.traverse(visitor, scope); + } + visitor.endVisit(this, scope); } - if (rhsType.isFunctionType() && this.lhs.isTypeReference()) - return lhsType; - //scope.problemReporter().typeMismatchError(rhsType, lhsType, this.expression); - return lhsType; -} -/** - * @see org.eclipse.wst.jsdt.internal.compiler.ast.Expression#resolveTypeExpecting(org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope, org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding) - */ -public TypeBinding resolveTypeExpecting(BlockScope scope, TypeBinding expectedType) { - - TypeBinding type = super.resolveTypeExpecting(scope, expectedType); - if (type == null) return null; - TypeBinding lhsType = this.resolvedType; - TypeBinding rhsType = this.expression.resolvedType; - // signal possible accidental boolean assignment (instead of using '==' operator) - if (expectedType == TypeBinding.BOOLEAN - && lhsType == TypeBinding.BOOLEAN - && (this.lhs.bits & IsStrictlyAssigned) != 0) { - scope.problemReporter().possibleAccidentalBooleanAssignment(this); + public LocalVariableBinding localVariableBinding() { + return lhs.localVariableBinding(); } - checkAssignment(scope, lhsType, rhsType); - return type; -} -public void traverse(ASTVisitor visitor, BlockScope scope) { - if (visitor.visit(this, scope)) { - lhs.traverse(visitor, scope); - expression.traverse(visitor, scope); + public int getASTType() { + return IASTNode.ASSIGNMENT; + } - visitor.endVisit(this, scope); -} -public LocalVariableBinding localVariableBinding() { - return lhs.localVariableBinding(); -} -public int getASTType() { - return IASTNode.ASSIGNMENT; -} + public IExpression getExpression() { + return this.expression; + } -public IExpression getExpression() { - return this.expression; -} + public IExpression getLeftHandSide() { + return this.lhs; + } -public IExpression getLeftHandSide() { - return this.lhs; -} + public IJsDoc getJsDoc() { + return javadoc; + } -public IJsDoc getJsDoc() { - return javadoc; -} + public void setInferredType(InferredType type) { + this.inferredType = type; -public void setInferredType(InferredType type) { - this.inferredType = type; - -} + } -public InferredType getInferredType() { - return this.inferredType; -} + public InferredType getInferredType() { + return this.inferredType; + } + + /** + * @param containingFunction {@link IFunctionDeclaration} that contains this assignment + */ + public void setContainingFunction(IFunctionDeclaration containingFunction) { + this.fContainingFunction = containingFunction; + } + + /** + * @return {@link IFunctionDeclaration} that contains this assignment, + * or null if this assignment is not contained in an {@link IFunctionDeclaration} + */ + public IFunctionDeclaration getContainingFunction() { + return this.fContainingFunction; + } + + /** + * @see org.eclipse.wst.jsdt.core.ast.IAssignment#setIsType(boolean) + */ + public void setIsType(boolean isType) { + this.fIsType = isType; + } + + /** + * @see org.eclipse.wst.jsdt.core.ast.IAssignment#isType() + */ + public boolean isType() { + return this.fIsType; + } } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Clinit.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Clinit.java index 3e4aa63c..d88d40f6 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Clinit.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Clinit.java @@ -50,7 +50,7 @@ public class Clinit extends AbstractMethodDeclaration { staticInitializerFlowContext.parent, this, Binding.NO_EXCEPTIONS, - scope, + this.getScope(), FlowInfo.DEAD_END); // check for missing returning path @@ -62,7 +62,7 @@ public class Clinit extends AbstractMethodDeclaration { // check static initializers thrown exceptions staticInitializerFlowContext.checkInitializerExceptions( - scope, + this.getScope(), clinitContext, flowInfo); } catch (AbortMethod e) { @@ -99,7 +99,7 @@ public class Clinit extends AbstractMethodDeclaration { public void resolve(ClassScope classScope) { - this.scope = new MethodScope(classScope, classScope.referenceContext, true); + this.setScope(new MethodScope(classScope, classScope.referenceContext, true)); } public void traverse( @@ -115,7 +115,7 @@ public class Clinit extends AbstractMethodDeclaration { // we need to add the field right now, because the field infos are generated before the methods if (needClassLiteralField) { SourceTypeBinding sourceType = - this.scope.outerMostClassScope().enclosingSourceType(); + this.getScope().outerMostClassScope().enclosingSourceType(); // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=22334 } } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/CompilationUnitDeclaration.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/CompilationUnitDeclaration.java index f3d6f011..b9806426 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/CompilationUnitDeclaration.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/CompilationUnitDeclaration.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -17,6 +17,7 @@ import java.util.Iterator; import java.util.List; import org.eclipse.wst.jsdt.core.ast.IASTNode; +import org.eclipse.wst.jsdt.core.ast.IFunctionExpression; import org.eclipse.wst.jsdt.core.ast.IProgramElement; import org.eclipse.wst.jsdt.core.ast.IScriptFileDeclaration; import org.eclipse.wst.jsdt.core.compiler.CategorizedProblem; @@ -35,7 +36,6 @@ import org.eclipse.wst.jsdt.internal.compiler.lookup.CompilationUnitBinding; import org.eclipse.wst.jsdt.internal.compiler.lookup.CompilationUnitScope; import org.eclipse.wst.jsdt.internal.compiler.lookup.LocalTypeBinding; import org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding; -import org.eclipse.wst.jsdt.internal.compiler.lookup.MethodScope; import org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding; import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeConstants; import org.eclipse.wst.jsdt.internal.compiler.parser.NLSTag; @@ -244,21 +244,89 @@ public class CompilationUnitDeclaration } + /** + *

Find the {@link AbstractMethodDeclaration} for a given {@link MethodBinding} by searching + * all of the statements of this {@link CompilationUnitDeclaration} including inside of {@link MethodDeclaration} + * contained in this {@link CompilationUnitDeclaration}.

+ * + * @param methodBinding + * @return + */ public AbstractMethodDeclaration declarationOf(MethodBinding methodBinding) { - if (methodBinding != null && this.statements != null) { - for (int i = 0, max = this.statements.length; i < max; i++) { - if (this.statements[i] instanceof AbstractMethodDeclaration) - { - AbstractMethodDeclaration methodDecl = (AbstractMethodDeclaration)this.statements[i]; - if (methodDecl.binding == methodBinding) - return methodDecl; + return declarationOf(methodBinding, this.statements); + } + + /** + *

+ * Internal helper method to find the {@link AbstractMethodDeclaration} + * for a given {@link MethodBinding} by searching a given set of + * statements. + *

+ * + * @param methodBinding + * {@link MethodBinding} to find the + * {@link AbstractMethodDeclaration} for + * @param originalStatements + * statements to search for the + * {@link AbstractMethodDeclaration} in + * + * @return {@link AbstractMethodDeclaration} for the given + * {@link MethodBinding} found in the given {@link ProgramElement}s, + * or null if it could not be found + */ + private static AbstractMethodDeclaration declarationOf(MethodBinding methodBinding, ProgramElement[] originalStatements) { + if (methodBinding != null && originalStatements != null) { + List statements = new ArrayList(originalStatements.length); + statements.addAll(Arrays.asList(originalStatements)); + + for (int i = 0; i < statements.size(); i++) { + IProgramElement statement = (IProgramElement)statements.get(i); + if (statement instanceof MessageSend) { + MessageSend msgSend = (MessageSend) statement; + + //search arguments of message send + if (msgSend.arguments != null) { + statements.addAll(Arrays.asList(msgSend.arguments)); + } + + /* add anonymous function message send + * + * function() { foo = "test" }(); */ + if(msgSend.receiver instanceof IFunctionExpression) { + statements.add(msgSend.receiver); + } + + continue; + } else if(statement instanceof ObjectLiteral) { + ObjectLiteral objLit = (ObjectLiteral) statement; + if(objLit.fields != null) { + statements.addAll(Arrays.asList(objLit.fields)); + } + continue; + } else if(statement instanceof ObjectLiteralField) { + ObjectLiteralField objLitField = (ObjectLiteralField) statement; + if(objLitField.initializer != null && (objLitField.initializer instanceof ObjectLiteral || objLitField.initializer instanceof FunctionExpression)) { + statements.add(objLitField.initializer); + continue; + } + } + + AbstractMethodDeclaration methodDecl = AbstractMethodDeclaration.findMethodDeclaration(statement); + + //check statements inside of method declarations as well + if(methodDecl != null && methodDecl.statements != null) { + statements.addAll(Arrays.asList(methodDecl.statements)); + } + + //check if the found method declaration is the one that is being searched for + if (methodDecl != null && (methodDecl.getBinding() == methodBinding || methodDecl.getBinding() == methodBinding.original())) { + return methodDecl; } } } return null; } - public char[] getFileName() { return compilationResult.getFileName(); @@ -553,31 +621,6 @@ public class CompilationUnitDeclaration return; try { if (visitor.visit(this, this.scope)) { - if (this.types != null && isPackageInfo()) { - // resolve synthetic type declaration - final TypeDeclaration syntheticTypeDeclaration = types[0]; - // resolve javadoc package if any - final MethodScope methodScope = syntheticTypeDeclaration.staticInitializerScope; - if (this.javadoc != null) { - this.javadoc.traverse(visitor, methodScope); - } - } - -// if (currentPackage != null) { -// currentPackage.traverse(visitor, this.scope); -// } -// if (imports != null) { -// int importLength = imports.length; -// for (int i = 0; i < importLength; i++) { -// imports[i].traverse(visitor, this.scope); -// } -// } -// if (types != null) { -// int typesLength = types.length; -// for (int i = 0; i < typesLength; i++) { -// types[i].traverse(visitor, this.scope); -// } -// } if (statements != null) { int statementsLength = statements.length; for (int i = 0; i < statementsLength; i++) { @@ -610,15 +653,8 @@ public class CompilationUnitDeclaration } } - public InferredType findInferredType(char [] name) - { + public InferredType findInferredType(char [] name) { return (InferredType)inferredTypesHash.get(name); -// for (int i=0;i an error has occurs at parsing time .... @@ -249,7 +249,7 @@ public void resolveStatements() { && this.constructorCall.accessMode != ExplicitConstructorCall.This) { this.constructorCall = null; } else { - this.constructorCall.resolve(this.scope); + this.constructorCall.resolve(this.getScope()); } } super.resolveStatements(); @@ -258,19 +258,19 @@ public void resolveStatements() { public void traverse(ASTVisitor visitor, ClassScope classScope) { if (visitor.visit(this, classScope)) { if (this.javadoc != null) { - this.javadoc.traverse(visitor, this.scope); + this.javadoc.traverse(visitor, this.getScope()); } if (this.arguments != null) { int argumentLength = this.arguments.length; for (int i = 0; i < argumentLength; i++) - this.arguments[i].traverse(visitor, this.scope); + this.arguments[i].traverse(visitor, this.getScope()); } if (this.constructorCall != null) - this.constructorCall.traverse(visitor, this.scope); + this.constructorCall.traverse(visitor, this.getScope()); if (this.statements != null) { int statementsLength = this.statements.length; for (int i = 0; i < statementsLength; i++) - this.statements[i].traverse(visitor, this.scope); + this.statements[i].traverse(visitor, this.getScope()); } } visitor.endVisit(this, classScope); diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ExplicitConstructorCall.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ExplicitConstructorCall.java index b0d63f13..fbaf7dd4 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ExplicitConstructorCall.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ExplicitConstructorCall.java @@ -207,7 +207,7 @@ public class ExplicitConstructorCall extends Statement implements InvocationSite methodScope.isConstructorCall = true; ReferenceBinding receiverType = scope.enclosingReceiverType(); if (accessMode != This) - receiverType = receiverType.superclass(); + receiverType = receiverType.getSuperBinding(); if (receiverType == null) { return; diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Expression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Expression.java index 09ababa5..1116f236 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Expression.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Expression.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -39,7 +39,6 @@ public abstract class Expression extends Statement implements IExpression { //of wrappers around expression in order to tune them as expression //Expression is a subclass of Statement. See the message isValidJavaStatement() - public int implicitConversion; public TypeBinding resolvedType = TypeBinding.UNKNOWN; public static final boolean isConstantValueRepresentable(Constant constant, int constantTypeID, int targetTypeID) { @@ -215,12 +214,6 @@ public final boolean checkCastTypesCompatibility(Scope scope, TypeBinding castTy boolean necessary = false; if (expressionType.isCompatibleWith(castType) || (necessary = BaseTypeBinding.isNarrowing(castType.id, expressionType.id))) { - if (expression != null) { - expression.implicitConversion = (castType.id << 4) + expressionType.id; - if (expression.constant != Constant.NotAConstant) { - this.constant = expression.constant.castTo(expression.implicitConversion); - } - } if (!necessary) tagAsUnnecessaryCast(scope, castType); return true; @@ -420,46 +413,7 @@ public void markAsNonNull() { return this.constant; return Constant.NotAConstant; } - - /** - * Returns the type of the expression after required implicit conversions. When expression type gets promoted - * or inserted a generic cast, the converted type will differ from the resolved type (surface side-effects from - * #computeConversion(...)). - * @return the type after implicit conversion - */ - public TypeBinding postConversionType(Scope scope) { - TypeBinding convertedType = this.resolvedType; - int runtimeType = (this.implicitConversion & TypeIds.IMPLICIT_CONVERSION_MASK) >> 4; - switch (runtimeType) { - case T_boolean : - convertedType = TypeBinding.BOOLEAN; - break; - case T_short : - convertedType = TypeBinding.SHORT; - break; - case T_char : - convertedType = TypeBinding.CHAR; - break; - case T_int : - convertedType = TypeBinding.INT; - break; - case T_float : - convertedType = TypeBinding.FLOAT; - break; - case T_long : - convertedType = TypeBinding.LONG; - break; - case T_double : - convertedType = TypeBinding.DOUBLE; - break; - default : - } - if ((this.implicitConversion & TypeIds.BOXING) != 0) { - convertedType = scope.environment().computeBoxingType(convertedType); - } - return convertedType; - } - + public StringBuffer print(int indent, StringBuffer output) { printIndent(indent, output); return printExpression(indent, output); diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/FieldDeclaration.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/FieldDeclaration.java index 57f886bc..d9cb8b4c 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/FieldDeclaration.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/FieldDeclaration.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -30,200 +30,237 @@ import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding; public class FieldDeclaration extends AbstractVariableDeclaration implements IFieldDeclaration { public FieldBinding binding; -// is in super public Javadoc javadoc; + // is in super public Javadoc javadoc; - //allows to retrieve both the "type" part of the declaration (part1) - //and also the part that decribe the name and the init and optionally - //some other dimension ! .... - //public int[] a, b[] = X, c ; - //for b that would give for + // allows to retrieve both the "type" part of the declaration (part1) + // and also the part that decribe the name and the init and optionally + // some other dimension ! .... + // public int[] a, b[] = X, c ; + // for b that would give for // - part1 : public int[] // - part2 : b[] = X, public int endPart1Position; public int endPart2Position; -public FieldDeclaration() { - // for subtypes or conversion -} - -public FieldDeclaration( char[] name, int sourceStart, int sourceEnd) { - this.name = name; - //due to some declaration like - // int x, y = 3, z , x ; - //the sourceStart and the sourceEnd is ONLY on the name - this.sourceStart = sourceStart; - this.sourceEnd = sourceEnd; -} - -public FlowInfo analyseCode(MethodScope initializationScope, FlowContext flowContext, FlowInfo flowInfo) { - if (this.binding != null && !this.binding.isUsed()) { - if (this.binding.isPrivate() || (this.binding.declaringClass != null && this.binding.declaringClass.isLocalType())) { - if (!initializationScope.referenceCompilationUnit().compilationResult.hasSyntaxError) { - initializationScope.problemReporter().unusedPrivateField(this); + public FieldDeclaration() { + // for subtypes or conversion + } + + public FieldDeclaration(char[] name, int sourceStart, int sourceEnd) { + this.name = name; + // due to some declaration like + // int x, y = 3, z , x ; + // the sourceStart and the sourceEnd is ONLY on the name + this.sourceStart = sourceStart; + this.sourceEnd = sourceEnd; + } + + public FlowInfo analyseCode(MethodScope initializationScope, FlowContext flowContext, FlowInfo flowInfo) { + if (this.binding != null && !this.binding.isUsed()) { + if (this.binding.isPrivate() || (this.binding.declaringClass != null && this.binding.declaringClass.isLocalType())) { + if (!initializationScope.referenceCompilationUnit().compilationResult.hasSyntaxError) { + initializationScope.problemReporter().unusedPrivateField(this); + } } } + + if (this.initialization != null) { + flowInfo = this.initialization.analyseCode(initializationScope, flowContext, flowInfo).unconditionalInits(); + flowInfo.markAsDefinitelyAssigned(this.binding); + } + return flowInfo; } - if (this.initialization != null) { - flowInfo = - this.initialization - .analyseCode(initializationScope, flowContext, flowInfo) - .unconditionalInits(); - flowInfo.markAsDefinitelyAssigned(this.binding); + /** + * @see org.eclipse.wst.jsdt.internal.compiler.ast.AbstractVariableDeclaration#getKind() + */ + public int getKind() { + return FIELD; } - return flowInfo; -} - -/** - * @see org.eclipse.wst.jsdt.internal.compiler.ast.AbstractVariableDeclaration#getKind() - */ -public int getKind() { -// return this.type == null ? ENUM_CONSTANT : FIELD; - return FIELD; -} - -public boolean isStatic() { - if (this.binding != null) - return this.binding.isStatic(); - return (this.modifiers & ClassFileConstants.AccStatic) != 0; -} - -public StringBuffer printStatement(int indent, StringBuffer output) { - if (this.javadoc != null) { - this.javadoc.print(indent, output); + + public boolean isStatic() { + if (this.binding != null) { + return this.binding.isStatic(); + } + return (this.modifiers & ClassFileConstants.AccStatic) != 0; } - return super.printStatement(indent, output); -} - -public void resolve(MethodScope initializationScope) { - // the two could be regrouped into - // a single line but it is clearer to have two lines while the reason of their - // existence is not at all the same. See comment for the second one. - - //-------------------------------------------------------- - if ((this.bits & ASTNode.HasBeenResolved) != 0) return; - if (this.binding == null || !this.binding.isValidBinding()) return; - - this.bits |= ASTNode.HasBeenResolved; - - // check if field is hiding some variable - issue is that field binding already got inserted in scope - // thus must lookup separately in super type and outer context - ClassScope classScope = initializationScope.enclosingClassScope(); - - if (classScope != null) { - checkHiding: { - SourceTypeBinding declaringType = classScope.enclosingSourceType(); - checkHidingSuperField: { - if (declaringType.superclass == null) break checkHidingSuperField; - Binding existingVariable = classScope.findField(declaringType.superclass, this.name, this, false /*do not resolve hidden field*/); - if (existingVariable == null) break checkHidingSuperField; // keep checking outer scenario - if (!existingVariable.isValidBinding()) break checkHidingSuperField; // keep checking outer scenario + + public StringBuffer printStatement(int indent, StringBuffer output) { + if (this.javadoc != null) { + this.javadoc.print(indent, output); + } + return super.printStatement(indent, output); + } + + public void resolve(MethodScope initializationScope) { + // the two could be regrouped into + // a single line but it is clearer to have two lines while the reason + // of their existence is not at all the same. See comment for the second one. + + // -------------------------------------------------------- + if ((this.bits & ASTNode.HasBeenResolved) != 0) { + return; + } + + if (this.binding == null || !this.binding.isValidBinding()) { + return; + } + + this.bits |= ASTNode.HasBeenResolved; + + // check if field is hiding some variable - issue is that field + // binding already got inserted in scope + // thus must lookup separately in super type and outer context + ClassScope classScope = initializationScope.enclosingClassScope(); + + if (classScope != null) { + checkHiding : { + SourceTypeBinding declaringType = classScope.enclosingSourceType(); + checkHidingSuperField : { + if (declaringType.getSuperBinding0() == null) { + break checkHidingSuperField; + } + Binding existingVariable = classScope.findField(declaringType.getSuperBinding0(), this.name, this, false); + if (existingVariable == null) { + // keep checking outer scenario + break checkHidingSuperField; + } + + if (!existingVariable.isValidBinding()) { + // keep checking outer scenario + break checkHidingSuperField; + } + + if (existingVariable instanceof FieldBinding) { + FieldBinding existingField = (FieldBinding) existingVariable; + if (existingField.original() == this.binding) { + // keep checking outer scenario + break checkHidingSuperField; + } + } + // collision with supertype field + initializationScope.problemReporter().fieldHiding(this, existingVariable); + break checkHiding; // already found a matching field + } + // only corner case is: lookup of outer field through static + // declaringType, which isn't detected by #getBinding as lookup starts + // from outer scope. Subsequent static contexts are detected for free. + Scope outerScope = classScope.parent; + if (outerScope.kind == Scope.COMPILATION_UNIT_SCOPE) { + break checkHiding; + } + Binding existingVariable = outerScope.getBinding(this.name, Binding.VARIABLE, this, false); + if (existingVariable == null) { + break checkHiding; + } + + if (!existingVariable.isValidBinding()) { + break checkHiding; + } + + if (existingVariable == this.binding) { + break checkHiding; + } + if (existingVariable instanceof FieldBinding) { FieldBinding existingField = (FieldBinding) existingVariable; - if (existingField.original() == this.binding) break checkHidingSuperField; // keep checking outer scenario + if (existingField.original() == this.binding) { + break checkHiding; + } + + if (!existingField.isStatic() && declaringType.isStatic()) { + break checkHiding; + } } - // collision with supertype field + // collision with outer field or local variable initializationScope.problemReporter().fieldHiding(this, existingVariable); - break checkHiding; // already found a matching field - } - // only corner case is: lookup of outer field through static declaringType, which isn't detected by #getBinding as lookup starts - // from outer scope. Subsequent static contexts are detected for free. - Scope outerScope = classScope.parent; - if (outerScope.kind == Scope.COMPILATION_UNIT_SCOPE) break checkHiding; - Binding existingVariable = outerScope.getBinding(this.name, Binding.VARIABLE, this, false /*do not resolve hidden field*/); - if (existingVariable == null) break checkHiding; - if (!existingVariable.isValidBinding()) break checkHiding; - if (existingVariable == this.binding) break checkHiding; - if (existingVariable instanceof FieldBinding) { - FieldBinding existingField = (FieldBinding) existingVariable; - if (existingField.original() == this.binding) break checkHiding; - if (!existingField.isStatic() && declaringType.isStatic()) break checkHiding; } - // collision with outer field or local variable - initializationScope.problemReporter().fieldHiding(this, existingVariable); } - } - - if (this.type != null ) { // enum constants have no declared type - this.type.resolvedType = this.binding.type; // update binding for type reference - } - FieldBinding previousField = initializationScope.initializedField; - int previousFieldID = initializationScope.lastVisibleFieldID; - try { - initializationScope.initializedField = this.binding; - initializationScope.lastVisibleFieldID = this.binding.id; + // enum constants have no declared type + if (this.type != null) { + // update binding for type reference + this.type.resolvedType = this.binding.type; + } -// resolveAnnotations(initializationScope, this.annotations, this.binding); - // the resolution of the initialization hasn't been done - if (this.initialization != null) { + FieldBinding previousField = initializationScope.initializedField; + int previousFieldID = initializationScope.lastVisibleFieldID; + try { + initializationScope.initializedField = this.binding; + initializationScope.lastVisibleFieldID = this.binding.id; - TypeBinding fieldType = this.binding.type; - TypeBinding initializationType; - this.initialization.setExpectedType(fieldType); // needed in case of generic method invocation - if (this.initialization instanceof ArrayInitializer) { + // the resolution of the initialization hasn't been done + if (this.initialization != null) { - if ((initializationType = this.initialization.resolveTypeExpecting(initializationScope, fieldType)) != null) { - ((ArrayInitializer) this.initialization).binding = (ArrayBinding) initializationType; + TypeBinding fieldType = this.binding.type; + TypeBinding initializationType; + // needed in case of generic method invocation + this.initialization.setExpectedType(fieldType); + if (this.initialization instanceof ArrayInitializer) { + if ((initializationType = this.initialization.resolveTypeExpecting(initializationScope, fieldType)) != null) { + ((ArrayInitializer) this.initialization).binding = (ArrayBinding) initializationType; + } } - } else if ((initializationType = this.initialization.resolveType(initializationScope)) != null) { - - if (fieldType != initializationType) // must call before computeConversion() and typeMismatchError() - initializationScope.compilationUnitScope().recordTypeConversion(fieldType, initializationType); - if (this.initialization.isConstantValueOfTypeAssignableToType(initializationType, fieldType) - || (fieldType.isBaseType() && BaseTypeBinding.isWidening(fieldType.id, initializationType.id)) - || initializationType.isCompatibleWith(fieldType)) { - } else if (initializationScope.isBoxingCompatibleWith(initializationType, fieldType) - || (initializationType.isBaseType() // narrowing then boxing ? - && initializationScope.compilerOptions().sourceLevel >= ClassFileConstants.JDK1_5 // autoboxing - && !fieldType.isBaseType() - && initialization.isConstantValueOfTypeAssignableToType(initializationType, initializationScope.environment().computeBoxingType(fieldType)))) { - } else { - initializationScope.problemReporter().typeMismatchError(initializationType, fieldType, this); + else if ((initializationType = this.initialization.resolveType(initializationScope)) != null) { + // must call before computeConversion() and typeMismatchError() + if (fieldType != initializationType) { + initializationScope.compilationUnitScope().recordTypeConversion(fieldType, initializationType); + } + if (this.initialization.isConstantValueOfTypeAssignableToType(initializationType, fieldType) || + (fieldType.isBaseType() && BaseTypeBinding.isWidening(fieldType.id, initializationType.id)) || + initializationType.isCompatibleWith(fieldType)) { + + } + else if (initializationScope.isBoxingCompatibleWith(initializationType, fieldType) || (initializationType.isBaseType() + && initializationScope.compilerOptions().sourceLevel >= ClassFileConstants.JDK1_5 // autoboxing + && !fieldType.isBaseType() + && initialization.isConstantValueOfTypeAssignableToType(initializationType, initializationScope.environment().computeBoxingType(fieldType)))) { + } + else { + initializationScope.problemReporter().typeMismatchError(initializationType, fieldType, this); + } + } + // check for assignment with no effect + if (this.binding == Assignment.getDirectBinding(this.initialization)) { + initializationScope.problemReporter().assignmentHasNoEffect(this, this.name); } } - // check for assignment with no effect - if (this.binding == Assignment.getDirectBinding(this.initialization)) { - initializationScope.problemReporter().assignmentHasNoEffect(this, this.name); + // Resolve Javadoc comment if one is present + if (this.javadoc != null) { + this.javadoc.resolve(initializationScope); } - } - // Resolve Javadoc comment if one is present - if (this.javadoc != null) { - /* - if (classScope != null) { - this.javadoc.resolve(classScope); + else if (this.binding.declaringClass != null && !this.binding.declaringClass.isLocalType()) { + initializationScope.problemReporter().javadocMissing(this.sourceStart, this.sourceEnd, this.binding.modifiers); } - */ - this.javadoc.resolve(initializationScope); - } else if (this.binding.declaringClass != null && !this.binding.declaringClass.isLocalType()) { - initializationScope.problemReporter().javadocMissing(this.sourceStart, this.sourceEnd, this.binding.modifiers); } - } finally { - initializationScope.initializedField = previousField; - initializationScope.lastVisibleFieldID = previousFieldID; + finally { + initializationScope.initializedField = previousField; + initializationScope.lastVisibleFieldID = previousFieldID; + } } -} -public void traverse(ASTVisitor visitor, MethodScope scope) { - if (visitor.visit(this, scope)) { - if (this.javadoc != null) { - this.javadoc.traverse(visitor, scope); - } - if (this.type != null) { - this.type.traverse(visitor, scope); + public void traverse(ASTVisitor visitor, MethodScope scope) { + if (visitor.visit(this, scope)) { + if (this.javadoc != null) { + this.javadoc.traverse(visitor, scope); + } + if (this.type != null) { + this.type.traverse(visitor, scope); + } + if (this.initialization != null) { + this.initialization.traverse(visitor, scope); + } } - if (this.initialization != null) - this.initialization.traverse(visitor, scope); + visitor.endVisit(this, scope); + } + + public int getASTType() { + return IASTNode.FIELD_DECLARATION; + + } + + public IExpression getInitialization() { + return this.initialization; } - visitor.endVisit(this, scope); -} -public int getASTType() { - return IASTNode.FIELD_DECLARATION; - -} -public IExpression getInitialization() -{ - return this.initialization; -} -} +} \ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/FieldReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/FieldReference.java index 0b00db60..6948dae6 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/FieldReference.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/FieldReference.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2011 IBM Corporation and others. + * Copyright (c) 2007, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -17,22 +17,25 @@ import org.eclipse.wst.jsdt.core.ast.IASTNode; import org.eclipse.wst.jsdt.core.ast.IExpression; import org.eclipse.wst.jsdt.core.ast.IFieldReference; import org.eclipse.wst.jsdt.core.compiler.CharOperation; +import org.eclipse.wst.jsdt.core.infer.InferredMethod; +import org.eclipse.wst.jsdt.core.infer.InferredType; import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor; -import org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants; import org.eclipse.wst.jsdt.internal.compiler.flow.FlowContext; import org.eclipse.wst.jsdt.internal.compiler.flow.FlowInfo; import org.eclipse.wst.jsdt.internal.compiler.impl.Constant; import org.eclipse.wst.jsdt.internal.compiler.lookup.Binding; import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope; import org.eclipse.wst.jsdt.internal.compiler.lookup.FieldBinding; +import org.eclipse.wst.jsdt.internal.compiler.lookup.FunctionTypeBinding; import org.eclipse.wst.jsdt.internal.compiler.lookup.InvocationSite; +import org.eclipse.wst.jsdt.internal.compiler.lookup.LocalFunctionBinding; import org.eclipse.wst.jsdt.internal.compiler.lookup.LocalVariableBinding; import org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding; import org.eclipse.wst.jsdt.internal.compiler.lookup.ProblemFieldBinding; import org.eclipse.wst.jsdt.internal.compiler.lookup.ProblemReasons; import org.eclipse.wst.jsdt.internal.compiler.lookup.ProblemReferenceBinding; import org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding; -import org.eclipse.wst.jsdt.internal.compiler.lookup.Scope; +import org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding; import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding; import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeConstants; import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeIds; @@ -40,539 +43,392 @@ import org.eclipse.wst.jsdt.internal.compiler.util.Util; public class FieldReference extends Reference implements InvocationSite, IFieldReference { - public static final int READ = 0; - public static final int WRITE = 1; public Expression receiver; public char[] token; - public FieldBinding binding; // exact binding resulting from lookup - public TypeBinding typeBinding; // exact binding resulting from lookup -// protected FieldBinding codegenBinding; // actual binding used for code generation (if no synthetic accessor) -// public FunctionBinding[] syntheticAccessors; // [0]=read accessor [1]=write accessor + + /** + *

+ * exact binding resulting from lookup + *

+ */ + public FieldBinding binding; + + /** + *

+ * exact binding resulting from lookup + *

+ */ + public TypeBinding typeBinding; - public long nameSourcePosition; //(start<<32)+end + /** + * (start<<32)+end + */ + public long nameSourcePosition; public TypeBinding receiverType; -// public TypeBinding genericCast; - -public FieldReference(char[] source, long pos) { - token = source; - nameSourcePosition = pos; - //by default the position are the one of the field (not true for super access) - sourceStart = (int) (pos >>> 32); - sourceEnd = (int) (pos & 0x00000000FFFFFFFFL); - bits |= Binding.FIELD; - -} - -public FlowInfo analyseAssignment(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo, Assignment assignment, boolean isCompound) { - // compound assignment extra work -// if (isCompound) { // check the variable part is initialized if blank final -// if (binding.isBlankFinal() -// && receiver.isThis() -// && currentScope.allowBlankFinalFieldAssignment(binding) -// && (!flowInfo.isDefinitelyAssigned(binding))) { -// currentScope.problemReporter().uninitializedBlankFinalField(binding, this); -// // we could improve error msg here telling "cannot use compound assignment on final blank field" -// } -// manageSyntheticAccessIfNecessary(currentScope, flowInfo, true /*read-access*/); -// } - if (receiver instanceof SingleNameReference && ((SingleNameReference)receiver).binding instanceof LocalVariableBinding) - { - flowInfo.markAsDefinitelyNonNull((LocalVariableBinding)((SingleNameReference)receiver).binding); - flowInfo.markAsDefinitelyAssigned((LocalVariableBinding)((SingleNameReference)receiver).binding); + + public FieldReference(char[] source, long pos) { + token = source; + nameSourcePosition = pos; + // by default the position are the one of the field (not true for super access) + sourceStart = (int) (pos >>> 32); + sourceEnd = (int) (pos & 0x00000000FFFFFFFFL); + bits |= Binding.FIELD; } - flowInfo = - receiver - .analyseCode(currentScope, flowContext, flowInfo, binding==null || !binding.isStatic()) - .unconditionalInits(); - if (assignment.expression != null) { - flowInfo = - assignment - .expression - .analyseCode(currentScope, flowContext, flowInfo) - .unconditionalInits(); + + public FlowInfo analyseAssignment(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo, Assignment assignment, boolean isCompound) { + if (receiver instanceof SingleNameReference && ((SingleNameReference) receiver).binding instanceof LocalVariableBinding) { + flowInfo.markAsDefinitelyNonNull((LocalVariableBinding) ((SingleNameReference) receiver).binding); + flowInfo.markAsDefinitelyAssigned((LocalVariableBinding) ((SingleNameReference) receiver).binding); + } + flowInfo = receiver.analyseCode(currentScope, flowContext, flowInfo, binding == null || !binding.isStatic()).unconditionalInits(); + if (assignment.expression != null) { + flowInfo = assignment.expression.analyseCode(currentScope, flowContext, flowInfo).unconditionalInits(); + } + + return flowInfo; } - manageSyntheticAccessIfNecessary(currentScope, flowInfo, false /*write-access*/); - return flowInfo; -} + public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) { + return analyseCode(currentScope, flowContext, flowInfo, true); + } -public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) { - return analyseCode(currentScope, flowContext, flowInfo, true); -} + public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo, boolean valueRequired) { + boolean nonStatic = binding == null || !binding.isStatic(); + receiver.analyseCode(currentScope, flowContext, flowInfo, nonStatic); + if (nonStatic) { + receiver.checkNPE(currentScope, flowContext, flowInfo); + } -public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo, boolean valueRequired) { - boolean nonStatic = binding==null || !binding.isStatic(); - receiver.analyseCode(currentScope, flowContext, flowInfo, nonStatic); - if (nonStatic) { - receiver.checkNPE(currentScope, flowContext, flowInfo); + return flowInfo; } - if (valueRequired || currentScope.compilerOptions().complianceLevel >= ClassFileConstants.JDK1_4) { - manageSyntheticAccessIfNecessary(currentScope, flowInfo, true /*read-access*/); + public FieldBinding fieldBinding() { + return binding; } - return flowInfo; -} - -/** - * @see org.eclipse.wst.jsdt.internal.compiler.ast.Expression#computeConversion(org.eclipse.wst.jsdt.internal.compiler.lookup.Scope, org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding, org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding) - */ -public void computeConversion(Scope scope, TypeBinding runtimeTimeType, TypeBinding compileTimeType) { - if (runtimeTimeType == null || compileTimeType == null) - return; - // set the generic cast after the fact, once the type expectation is fully known (no need for strict cast) - if (this.binding != null && this.binding.isValidBinding()) { - FieldBinding originalBinding = this.binding.original(); + + /** + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.InvocationSite#genericTypeArguments() + */ + public TypeBinding[] genericTypeArguments() { + return null; } -} - -public FieldBinding fieldBinding() { - return binding; -} - -/** - * @see org.eclipse.wst.jsdt.internal.compiler.lookup.InvocationSite#genericTypeArguments() - */ -public TypeBinding[] genericTypeArguments() { - return null; -} -public boolean isSuperAccess() { - return receiver.isSuper(); -} - -public boolean isTypeAccess() { - return receiver != null && receiver.isTypeReference(); -} - -/* - * No need to emulate access to protected fields since not implicitly accessed - */ -public void manageSyntheticAccessIfNecessary(BlockScope currentScope, FlowInfo flowInfo, boolean isReadAccess) { - if ((flowInfo.tagBits & FlowInfo.UNREACHABLE) != 0) return; - - // if field from parameterized type got found, use the original field at codegen time -// this.codegenBinding = this.binding.original(); -// -// if (binding.isPrivate()) { -// if ((currentScope.enclosingSourceType() != this.codegenBinding.declaringClass) -// && binding.constant() == Constant.NotAConstant) { -// if (syntheticAccessors == null) -// syntheticAccessors = new FunctionBinding[2]; -// syntheticAccessors[isReadAccess ? READ : WRITE] = -// ((SourceTypeBinding) this.codegenBinding.declaringClass).addSyntheticMethod(this.codegenBinding, isReadAccess); -// currentScope.problemReporter().needToEmulateFieldAccess(this.codegenBinding, this, isReadAccess); -// return; -// } -// -// } else if (receiver instanceof QualifiedSuperReference) { // qualified super -// -// // qualified super need emulation always -// SourceTypeBinding destinationType = -// (SourceTypeBinding) (((QualifiedSuperReference) receiver) -// .currentCompatibleType); -// if (syntheticAccessors == null) -// syntheticAccessors = new FunctionBinding[2]; -// syntheticAccessors[isReadAccess ? READ : WRITE] = destinationType.addSyntheticMethod(this.codegenBinding, isReadAccess); -// currentScope.problemReporter().needToEmulateFieldAccess(this.codegenBinding, this, isReadAccess); -// return; -// -// } else if (binding.isProtected()) { -// -// SourceTypeBinding enclosingSourceType; -// if (((bits & DepthMASK) != 0) -// && binding.declaringClass.getPackage() -// != (enclosingSourceType = currentScope.enclosingSourceType()).getPackage()) { -// -// SourceTypeBinding currentCompatibleType = -// (SourceTypeBinding) enclosingSourceType.enclosingTypeAt( -// (bits & DepthMASK) >> DepthSHIFT); -// if (syntheticAccessors == null) -// syntheticAccessors = new FunctionBinding[2]; -// syntheticAccessors[isReadAccess ? READ : WRITE] = currentCompatibleType.addSyntheticMethod(this.codegenBinding, isReadAccess); -// currentScope.problemReporter().needToEmulateFieldAccess(this.codegenBinding, this, isReadAccess); -// return; -// } -// } - // if the binding declaring class is not visible, need special action - // for runtime compatibility on 1.2 VMs : change the declaring class of the binding - // NOTE: from target 1.2 on, field's declaring class is touched if any different from receiver type - // and not from Object or implicit static field access. -// if (this.binding.declaringClass != this.receiverType -// && !this.receiverType.isArrayType() -// && this.binding.declaringClass != null // array.length -// && this.binding.constant() == Constant.NotAConstant) { -// CompilerOptions options = currentScope.compilerOptions(); -// if ((options.targetJDK >= ClassFileConstants.JDK1_2 -// && (options.complianceLevel >= ClassFileConstants.JDK1_4 || !(receiver.isImplicitThis() && this.codegenBinding.isStatic())) -// && this.binding.declaringClass.id != T_JavaLangObject) // no change for Object fields -// || !this.binding.declaringClass.canBeSeenBy(currentScope)) { -// -// this.codegenBinding = -// currentScope.enclosingSourceType().getUpdatedFieldBinding( -// this.codegenBinding, -// (ReferenceBinding) this.receiverType.erasure()); -// } -// } -} - -public int nullStatus(FlowInfo flowInfo) { - return FlowInfo.UNKNOWN; -} - -public Constant optimizedBooleanConstant() { - switch (this.resolvedType.id) { - case T_boolean : - case T_JavaLangBoolean : - return Constant.NotAConstant; - default : - return Constant.NotAConstant; + + public boolean isSuperAccess() { + return receiver.isSuper(); } -} - -/** - * @see org.eclipse.wst.jsdt.internal.compiler.ast.Expression#postConversionType(Scope) - */ -public TypeBinding postConversionType(Scope scope) { - TypeBinding convertedType = this.resolvedType; -// if (this.genericCast != null) -// convertedType = this.genericCast; - int runtimeType = (this.implicitConversion & IMPLICIT_CONVERSION_MASK) >> 4; - switch (runtimeType) { - case T_boolean : - convertedType = TypeBinding.BOOLEAN; - break; - case T_short : - convertedType = TypeBinding.SHORT; - break; - case T_char : - convertedType = TypeBinding.CHAR; - break; - case T_int : - convertedType = TypeBinding.INT; - break; - case T_float : - convertedType = TypeBinding.FLOAT; - break; - case T_long : - convertedType = TypeBinding.LONG; - break; - case T_double : - convertedType = TypeBinding.DOUBLE; - break; - default : + + public boolean isTypeAccess() { + return receiver != null && receiver.isTypeReference(); } - if ((this.implicitConversion & BOXING) != 0) { - convertedType = scope.environment().computeBoxingType(convertedType); + + public int nullStatus(FlowInfo flowInfo) { + return FlowInfo.UNKNOWN; } - return convertedType; -} -public StringBuffer printExpression(int indent, StringBuffer output) { - return receiver.printExpression(0, output).append('.').append(token); -} + public Constant optimizedBooleanConstant() { + return Constant.NotAConstant; + } + public StringBuffer printExpression(int indent, StringBuffer output) { + return receiver.printExpression(0, output).append('.').append(token); + } -public TypeBinding resolveType(BlockScope scope) { - return resolveType(scope, false, null); -} -public TypeBinding resolveType(BlockScope scope, boolean define, TypeBinding useType) { - // Answer the signature type of the field. - // constants are propaged when the field is final - // and initialized with a (compile time) constant + public TypeBinding resolveType(BlockScope scope) { + return resolveType(scope, false, null); + } - //always ignore receiver cast, since may affect constant pool reference -// boolean receiverCast = false; -// if (this.receiver instanceof CastExpression) { -// this.receiver.bits |= DisableUnnecessaryCastCheck; // will check later on -// receiverCast = true; -// } + public TypeBinding resolveType(BlockScope scope, boolean define, TypeBinding useType) { + /* + * Handle if this is a reference to the prototype of a type + * + * By default, the prototype is of type Object, but if there is an + * InferredType for the receiver, it should yeild the receiver type. + */ + if (this.isPrototype()) { + // check if receiver type is defined + if ((this.receiverType = receiver.resolveType(scope)) == null) { + constant = Constant.NotAConstant; + return null; + } + // construct the name of the type based on the receiver + char[] possibleTypeName = Util.getTypeName(receiver); + TypeBinding typeBinding = scope.getJavaLangObject(); + if (possibleTypeName != null) { + Binding possibleTypeBinding = scope.getBinding(possibleTypeName, Binding.TYPE & RestrictiveFlagMASK, this, true /* resolve */); - /* - * Handle if this is a reference to the prototype of a type - * - * By default, the prototype is of type Object, but if there is an InferredType - * for the receiver, it should yeild the receiver type. - */ -if( this.isPrototype() ){ - // check if receiver type is defined - if ((this.receiverType = receiver.resolveType(scope)) == null) { - constant = Constant.NotAConstant; - return null; - } - - - //construc the name of the type based on the receiver - char [] possibleTypeName = Util.getTypeName( receiver ); - TypeBinding typeBinding = scope.getJavaLangObject(); - if( possibleTypeName != null ){ - Binding possibleTypeBinding = scope.getBinding( possibleTypeName, Binding.TYPE & RestrictiveFlagMASK, this, true /*resolve*/); - - if( possibleTypeBinding.isValidBinding() ){ - //get the super class -// TypeBinding superTypeBinding = ((ReferenceBinding)possibleTypeBinding).superclass(); -// if( superTypeBinding != null ) -// typeBinding = superTypeBinding; - typeBinding = (TypeBinding)possibleTypeBinding; + if (possibleTypeBinding.isValidBinding()) { + typeBinding = (TypeBinding) possibleTypeBinding; + } + char[] fieldname = new char[]{'p', 'r', 'o', 't', 'o', 't', 'y', 'p', 'e'}; + this.binding = scope.getJavaLangObject().getField(fieldname, true); + constant = Constant.NotAConstant; + return this.resolvedType = typeBinding; } - char[] fieldname=new char[]{'p','r','o','t','o','t','y','p','e'}; - this.binding=scope.getJavaLangObject().getField(fieldname, true); - constant = Constant.NotAConstant; - return this.resolvedType = typeBinding; + } - } + char[] possibleTypeName = Util.getTypeName(this); + Binding possibleTypeBinding = null; + if (possibleTypeName != null) { + possibleTypeBinding = scope.getBinding(possibleTypeName, Binding.TYPE & RestrictiveFlagMASK, this, true /* resolve */); + } - char [] possibleTypeName = Util.getTypeName( this ); - Binding possibleTypeBinding =null; - if (possibleTypeName!=null) - possibleTypeBinding = scope.getBinding( possibleTypeName, Binding.TYPE & RestrictiveFlagMASK, this, true /*resolve*/); - if(possibleTypeBinding != null && possibleTypeBinding.isValidBinding() && (TypeBinding)possibleTypeBinding != scope.getJavaLangObject()) { - this.typeBinding=(TypeBinding)possibleTypeBinding; - constant = Constant.NotAConstant; - this.bits|=Binding.TYPE; - return this.typeBinding; - } - boolean receiverDefined=true; - // if this could be a qualified type name, first check if receiver is defined, and if not look up as type name - if (possibleTypeName!=null && receiver instanceof SingleNameReference) - { - Binding receiverBinding = ((SingleNameReference)receiver).findBinding(scope); - if (receiverBinding==null || !receiverBinding.isValidBinding()) - receiverDefined=false; - this.receiverType=null; - } - if (receiverDefined) - this.receiverType = receiver.resolveType(scope); - if (this.receiverType == null || this.receiverType==scope.getJavaLangObject()) { - if (possibleTypeBinding!=null && possibleTypeBinding.isValidBinding()) - { - this.typeBinding=(TypeBinding)possibleTypeBinding; - this.bits|=Binding.TYPE; + if (possibleTypeBinding != null && possibleTypeBinding.isValidBinding() && (TypeBinding) possibleTypeBinding != scope.getJavaLangObject()) { + this.typeBinding = (TypeBinding) possibleTypeBinding; + constant = Constant.NotAConstant; + this.bits |= Binding.TYPE; return this.typeBinding; } - else - { - this.binding=new ProblemFieldBinding(null,this.token,ProblemReasons.NotFound); + + /* if this could be a qualified type name, first check if receiver is + * defined, and if not look up as type name */ + this.receiverType = this.receiver.resolveType(scope); + + if (this.receiverType == null || this.receiverType == scope.getJavaLangObject()) { + if (possibleTypeBinding != null && possibleTypeBinding.isValidBinding()) { + this.typeBinding = (TypeBinding) possibleTypeBinding; + this.bits |= Binding.TYPE; + return this.typeBinding; + } + else { + this.binding = new ProblemFieldBinding(null, this.token, ProblemReasons.NotFound); + constant = Constant.NotAConstant; + this.resolvedType = TypeBinding.ANY; + } + return null; + } + + /* Need to look in the fields and method for a match... In JS there is + * no distinction between member functions or field. We are trying to + * mimic that property below (Java does have a distinction) */ + if (this.receiverType.id == TypeIds.T_any) { constant = Constant.NotAConstant; - this.resolvedType=TypeBinding.ANY; + this.binding = new ProblemFieldBinding(null, token, ProblemReasons.NotFound); + return this.resolvedType = TypeBinding.ANY; } - return null; - } -// if (receiverCast) { -// // due to change of declaring class with receiver type, only identity cast should be notified -// if (((CastExpression)this.receiver).expression.resolvedType == this.receiverType) { -// scope.problemReporter().unnecessaryCast((CastExpression)this.receiver); -// } -// } - // the case receiverType.isArrayType and token = 'length' is handled by the scope API - - /* - * Need to look in the fields and method for a match... In JS there is no distinction between member functions - * or field. We are trying to mimic that property below (Java does have a distinction) - */ - if (this.receiverType.id==TypeIds.T_any) - { - constant = Constant.NotAConstant; - this.binding=new ProblemFieldBinding( null, token, ProblemReasons.NotFound) ; - return this.resolvedType=TypeBinding.ANY; - } - - Binding memberBinding = scope.getFieldOrMethod(this.receiverType, token, this); - boolean receiverIsType = (receiver instanceof NameReference || receiver instanceof FieldReference || receiver instanceof ThisReference) - && ( receiver.bits & Binding.TYPE) != 0; - if (!memberBinding.isValidBinding() && (this.receiverType!=null && this.receiverType.isFunctionType())) - { - Binding alternateBinding = receiver.alternateBinding(); - if (alternateBinding instanceof TypeBinding) - { - this.receiverType=(TypeBinding)alternateBinding; + + Binding memberBinding = scope.getFieldOrMethod(this.receiverType, token, this); + boolean receiverIsType = (receiver instanceof NameReference || receiver instanceof FieldReference || receiver instanceof ThisReference) && (receiver.bits & Binding.TYPE) != 0; + if (!memberBinding.isValidBinding() && (this.receiverType != null && this.receiverType.isFunctionType())) { + Binding alternateBinding = receiver.alternateBinding(); + if (alternateBinding instanceof TypeBinding) { + this.receiverType = (TypeBinding) alternateBinding; memberBinding = scope.getFieldOrMethod(this.receiverType, token, this); - receiverIsType=true; - } - } - - - //FieldBinding fieldBinding = this.codegenBinding = this.binding = scope.getField(this.receiverType, token, this); - - constant = Constant.NotAConstant; - if( memberBinding instanceof FieldBinding ){ - FieldBinding fieldBinding =/* this.codegenBinding =*/ this.binding = (FieldBinding)memberBinding; - if (!fieldBinding.isValidBinding()) { - this.binding=fieldBinding; - this.resolvedType=TypeBinding.ANY; - if (!define) - { - constant = Constant.NotAConstant; - scope.problemReporter().invalidField(this, this.receiverType); - return null; + receiverIsType = true; } - else // should add binding here - { + } + constant = Constant.NotAConstant; + if (memberBinding instanceof FieldBinding) { + FieldBinding fieldBinding = /* this.codegenBinding = */this.binding = (FieldBinding) memberBinding; + if (!fieldBinding.isValidBinding()) { + this.binding = fieldBinding; + this.resolvedType = TypeBinding.ANY; + if (!define) { + constant = Constant.NotAConstant; + scope.problemReporter().invalidField(this, this.receiverType); + return null; + } + else { + // should add binding here + } } - // return this.resolvedType=TypeBinding.UNKNOWN; - } - if (JavaScriptCore.IS_ECMASCRIPT4) - { - TypeBinding receiverErasure = this.receiverType; - if (receiverErasure instanceof ReferenceBinding) { - if (receiverErasure.findSuperTypeWithSameErasure(fieldBinding.declaringClass) == null) { - this.receiverType = fieldBinding.declaringClass; // handle indirect inheritance thru variable secondary bound + if (JavaScriptCore.IS_ECMASCRIPT4) { + TypeBinding receiverErasure = this.receiverType; + if (receiverErasure instanceof ReferenceBinding) { + if (receiverErasure.findSuperTypeWithSameErasure(fieldBinding.declaringClass) == null) { + // handle indirect inheritance thru variable secondary bound + this.receiverType = fieldBinding.declaringClass; + } } } - } - if (isFieldUseDeprecated(fieldBinding, scope, (this.bits & IsStrictlyAssigned) !=0)) { - scope.problemReporter().deprecatedField(fieldBinding, this); - } - boolean isImplicitThisRcv = receiver.isImplicitThis(); - constant = Constant.NotAConstant; - if (fieldBinding.isStatic()) { - // static field accessed through receiver? legal but unoptimal (optional warning) - if (!(isImplicitThisRcv - || receiverIsType - )) { - scope.problemReporter().nonStaticAccessToStaticField(this, fieldBinding); + if (isFieldUseDeprecated(fieldBinding, scope, (this.bits & IsStrictlyAssigned) != 0)) { + scope.problemReporter().deprecatedField(fieldBinding, this); } - if (!isImplicitThisRcv - && fieldBinding.declaringClass != receiverType - && fieldBinding.declaringClass.canBeSeenBy(scope)) { - scope.problemReporter().indirectAccessToStaticField(this, fieldBinding); + boolean isImplicitThisRcv = receiver.isImplicitThis(); + constant = Constant.NotAConstant; + if (fieldBinding.isStatic()) { + // static field accessed through receiver? legal but unoptimal (optional warning) + if (!(isImplicitThisRcv || receiverIsType)) { + scope.problemReporter().nonStaticAccessToStaticField(this, fieldBinding); + } + if (!isImplicitThisRcv && fieldBinding.declaringClass != receiverType && fieldBinding.declaringClass.canBeSeenBy(scope)) { + scope.problemReporter().indirectAccessToStaticField(this, fieldBinding); + } + } + else { + if (receiverIsType) { + scope.problemReporter().staticFieldAccessToNonStaticVariable(this, fieldBinding); + } + } + + //if there is a given useType and the field is not valid, create a valid binding + if(useType != null && !fieldBinding.isValidBinding()) { + fieldBinding = new FieldBinding(fieldBinding, fieldBinding.declaringClass); + if(fieldBinding.declaringClass instanceof SourceTypeBinding) { + ((SourceTypeBinding)fieldBinding.declaringClass).addField(fieldBinding); + } + this.binding = fieldBinding; + } + + //set use type + if(useType != null) { + fieldBinding.type = useType; + + //add as a function binding as well if there is not already a function binding by the same name + if(useType.isFunctionType() && fieldBinding.declaringClass instanceof SourceTypeBinding) { + SourceTypeBinding declaringBinding = (SourceTypeBinding)fieldBinding.declaringClass; + InferredMethod dupMeth = declaringBinding.getInferredType().findMethod(this.getToken(), null); + if(dupMeth == null) { + MethodBinding[] funcBindings = declaringBinding.getMethods(this.getToken()); + if(funcBindings == null || funcBindings.length == 0) { + MethodBinding methBinding = new MethodBinding( + ((FunctionTypeBinding)useType).functionBinding, fieldBinding.declaringClass); + methBinding.selector = fieldBinding.name; + + if(methBinding.declaringClass instanceof SourceTypeBinding) { + ((SourceTypeBinding)methBinding.declaringClass).addMethod(methBinding); + } + } + } + } } - } else { - if(receiverIsType) - scope.problemReporter().staticFieldAccessToNonStaticVariable(this, fieldBinding); + + // perform capture conversion if read access + return this.resolvedType = fieldBinding.type; } - // perform capture conversion if read access - return this.resolvedType = fieldBinding.type; - } - else if( memberBinding instanceof MethodBinding ){ - MethodBinding methodBinding=(MethodBinding) memberBinding; + else if (memberBinding instanceof MethodBinding) { + MethodBinding methodBinding = (MethodBinding) memberBinding; + + if (!methodBinding.isStatic() || memberBinding instanceof LocalFunctionBinding) { + if (receiverIsType && methodBinding.isValidBinding() && !methodBinding.isConstructor()) { + if (this.receiverType == null || !this.receiverType.isAnonymousType()) + scope.problemReporter().mustUseAStaticMethod(this, methodBinding); + } + } + else { + if (!receiverIsType && methodBinding.isValidBinding()) + scope.problemReporter().nonStaticAccessToStaticMethod(this, methodBinding); - if (!methodBinding.isStatic()) { - if (receiverIsType && methodBinding.isValidBinding() && !methodBinding.isConstructor()) { - if(this.receiverType == null || !this.receiverType.isAnonymousType()) - scope.problemReporter().mustUseAStaticMethod(this, methodBinding); } - } - else - { - if (!receiverIsType && methodBinding.isValidBinding()) - scope.problemReporter().nonStaticAccessToStaticMethod(this, - methodBinding); + this.resolvedType = methodBinding.functionTypeBinding; + this.binding = new FieldBinding(((MethodBinding) memberBinding).selector, this.receiverType, ((MethodBinding) memberBinding).modifiers, methodBinding.declaringClass); + if (memberBinding.isValidBinding()) { + return this.resolvedType; + } + return null; } - - this.resolvedType= scope.getJavaLangFunction(); - this.binding = new FieldBinding(((MethodBinding) memberBinding).selector, this.receiverType, ((MethodBinding) memberBinding).modifiers, methodBinding.declaringClass); - //this.binding=new ProblemFieldBinding(null,this.token,ProblemReasons.NotFound); - if( memberBinding.isValidBinding() ) - return this.resolvedType; + return null; } - return null; -} - -public void setActualReceiverType(ReferenceBinding receiverType) { - // ignored -} + public void setActualReceiverType(ReferenceBinding receiverType) { + // ignored + } -public void setDepth(int depth) { - bits &= ~DepthMASK; // flush previous depth if any - if (depth > 0) { - bits |= (depth & 0xFF) << DepthSHIFT; // encoded on 8 bits + public void setDepth(int depth) { + bits &= ~DepthMASK; // flush previous depth if any + if (depth > 0) { + bits |= (depth & 0xFF) << DepthSHIFT; // encoded on 8 bits + } } -} -public void setFieldIndex(int index) { - // ignored -} + public void setFieldIndex(int index) { + // ignored + } -public void traverse(ASTVisitor visitor, BlockScope scope) { - if (visitor.visit(this, scope)) { - receiver.traverse(visitor, scope); + public void traverse(ASTVisitor visitor, BlockScope scope) { + if (visitor.visit(this, scope)) { + receiver.traverse(visitor, scope); + } + visitor.endVisit(this, scope); } - visitor.endVisit(this, scope); -} -public boolean isPrototype() -{ - return (CharOperation.equals(TypeConstants.PROTOTYPE,this.token)); -} - - -public TypeBinding resolveForAllocation(BlockScope scope, ASTNode location) -{ - char [][]qualifiedName=asQualifiedName(); - TypeBinding typeBinding=null; - if (qualifiedName!=null) - { - typeBinding=scope.getType(CharOperation.concatWith(qualifiedName, '.')); + + public boolean isPrototype() { + return (CharOperation.equals(TypeConstants.PROTOTYPE, this.token)); } - if (typeBinding==null || !typeBinding.isValidBinding()) - { - this.receiverType = receiver.resolveType(scope); - if (this.receiverType == null) { - this.binding=new ProblemFieldBinding(null,this.token,ProblemReasons.NotFound); - constant = Constant.NotAConstant; - this.resolvedType=TypeBinding.ANY; - return null; + + + public TypeBinding resolveForAllocation(BlockScope scope, ASTNode location) { + char[][] qualifiedName = asQualifiedName(); + TypeBinding typeBinding = null; + if (qualifiedName != null) { + typeBinding = scope.getType(CharOperation.concatWith(qualifiedName, '.')); } - Binding memberBinding = scope.getFieldOrMethod(this.receiverType, token, this); - if( memberBinding instanceof MethodBinding && memberBinding.isValidBinding()){ - this.resolvedType= ((MethodBinding)memberBinding).allocationType; - this.binding=new ProblemFieldBinding(null,this.token,ProblemReasons.NotFound); - if( memberBinding.isValidBinding() ) - return this.resolvedType; + if (typeBinding == null || !typeBinding.isValidBinding()) { + this.receiverType = receiver.resolveType(scope); + if (this.receiverType == null) { + this.binding = new ProblemFieldBinding(null, this.token, ProblemReasons.NotFound); + constant = Constant.NotAConstant; + this.resolvedType = TypeBinding.ANY; + return null; + } + Binding memberBinding = scope.getFieldOrMethod(this.receiverType, token, this); + if (memberBinding instanceof MethodBinding && memberBinding.isValidBinding()) { + this.resolvedType = ((MethodBinding) memberBinding).allocationType; + this.binding = new ProblemFieldBinding(null, this.token, ProblemReasons.NotFound); + if (memberBinding.isValidBinding()) + return this.resolvedType; + } + + } + if (typeBinding == null) { + if (qualifiedName == null) + qualifiedName = new char[][]{token}; + typeBinding = new ProblemReferenceBinding(qualifiedName, null, ProblemReasons.NotFound); } - + return typeBinding; } - if (typeBinding==null) - { - if (qualifiedName==null) - qualifiedName=new char[][]{token}; - typeBinding=new ProblemReferenceBinding(qualifiedName,null,ProblemReasons.NotFound); + + public int getASTType() { + return IASTNode.FIELD_REFERENCE; + } - return typeBinding; -} -public int getASTType() { - return IASTNode.FIELD_REFERENCE; - -} - -public char [][] asQualifiedName() -{ - ArrayList list=new ArrayList(); - list.add(token); - FieldReference fieldReference=this; - while (fieldReference!=null) - { - if ( fieldReference.receiver instanceof SingleNameReference) - { - list.add(0,((SingleNameReference)fieldReference.receiver).token); - fieldReference=null; - } - else if (fieldReference.receiver instanceof FieldReference) - { - fieldReference=(FieldReference)fieldReference.receiver; - list.add(0,fieldReference.token); + + public char[][] asQualifiedName() { + ArrayList list = new ArrayList(); + list.add(token); + FieldReference fieldReference = this; + while (fieldReference != null) { + if (fieldReference.receiver instanceof SingleNameReference) { + list.add(0, ((SingleNameReference) fieldReference.receiver).token); + fieldReference = null; + } + else if (fieldReference.receiver instanceof FieldReference) { + fieldReference = (FieldReference) fieldReference.receiver; + list.add(0, fieldReference.token); + } + else if (fieldReference.receiver instanceof ThisReference) { + //use the inferred type name of "this" as the next segment + InferredType type = ((ThisReference)fieldReference.receiver).getInferredType(); + if(type != null) { + list.add(0, type.getName()); + } else { + //if do not have a type for "this" then can't build the fully qualified name + return null; + } + + fieldReference = null; } - else + else { return null; + } + } + return (char[][]) list.toArray(new char[list.size()][]); } - return (char [][])list.toArray(new char[list.size()][]); -} - -public IExpression getReceiver() { - return receiver; -} -public char[] getToken() { - return token; -} + public IExpression getReceiver() { + return receiver; + } -public boolean isTypeReference() { - return (this.bits & Binding.TYPE) ==Binding.TYPE; -} + public char[] getToken() { + return token; + } -} + public boolean isTypeReference() { + return (this.bits & Binding.TYPE) == Binding.TYPE; + } +} \ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/FunctionExpression.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/FunctionExpression.java index 66ddc9bc..3c2e6a81 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/FunctionExpression.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/FunctionExpression.java @@ -51,12 +51,20 @@ public class FunctionExpression extends Expression implements IFunctionExpressio public TypeBinding resolveType(BlockScope scope) { constant = Constant.NotAConstant; - this.methodDeclaration.scope=new MethodScope(scope,this.methodDeclaration,false); - this.methodDeclaration.binding=this.methodDeclaration.scope.createMethod(this.methodDeclaration, null, scope.enclosingCompilationUnit(), false, false); - methodDeclaration.bindArguments(); - this.methodDeclaration.binding.createFunctionTypeBinding(scope); + this.methodDeclaration.setScope(new MethodScope(scope,this.methodDeclaration,false)); + + if(!this.methodDeclaration.hasBinding()) { + this.methodDeclaration.setBinding(this.methodDeclaration.getScope().createMethod(this.methodDeclaration, this.methodDeclaration.selector, scope.enclosingCompilationUnit(), false, false)); + } + + //add binding to scope only if named + if(this.methodDeclaration.getName() != null) { + scope.addLocalMethod(this.methodDeclaration.getBinding()); + } + + this.methodDeclaration.getBinding().createFunctionTypeBinding(scope); this.methodDeclaration.resolve(scope); - return this.methodDeclaration.binding.functionTypeBinding; + return this.methodDeclaration.getBinding().functionTypeBinding; } public TypeBinding resolveForAllocation(BlockScope scope, ASTNode location) { diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ImportReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ImportReference.java index 5d8e0683..d62048c8 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ImportReference.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ImportReference.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Javadoc.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Javadoc.java index ba3422c4..35663d9e 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Javadoc.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/Javadoc.java @@ -295,7 +295,7 @@ public class Javadoc extends ASTNode implements IJsDoc { if (messageSend.binding != null && messageSend.binding.isValidBinding() && messageSend.actualReceiverType instanceof ReferenceBinding) { ReferenceBinding methodReceiverType = (ReferenceBinding) messageSend.actualReceiverType; if ((methodReceiverType.isSuperclassOf(methDecl.binding.declaringClass)) && - CharOperation.equals(messageSend.selector, methDecl.selector) && + CharOperation.equals(messageSend.selector, methDecl.getName()) && (methDecl.binding.returnType.isCompatibleWith(messageSend.binding.returnType))) { if (messageSend.arguments == null && methDecl.arguments == null) { superRef = true; diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/LocalDeclaration.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/LocalDeclaration.java index 1657e7dd..b3193b3f 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/LocalDeclaration.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/LocalDeclaration.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -32,11 +32,10 @@ import org.eclipse.wst.jsdt.internal.compiler.lookup.VariableBinding; public class LocalDeclaration extends AbstractVariableDeclaration implements ILocalDeclaration { public LocalVariableBinding binding; + + private boolean isLocal = true; - public LocalDeclaration( - char[] name, - int sourceStart, - int sourceEnd) { + public LocalDeclaration(char[] name, int sourceStart, int sourceEnd) { this.name = name; this.sourceStart = sourceStart; @@ -47,67 +46,68 @@ public class LocalDeclaration extends AbstractVariableDeclaration implements ILo public IAssignment getAssignment() { if (this.initialization == null) return null; - if (initialization instanceof FunctionExpression && ((FunctionExpression) initialization).getMethodDeclaration().getName() == null) { + if (initialization instanceof FunctionExpression) { return new Assignment(new SingleNameReference(this.name, this.sourceStart, this.sourceEnd), this.initialization, this.initialization.sourceEnd); } return null; } - -public LocalVariableBinding getBinding() { - return this.binding; -} -public void setBinding(LocalVariableBinding binding) { - this.binding=binding; -} - -public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) { - // record variable initialization if any - if ((flowInfo.tagBits & FlowInfo.UNREACHABLE) == 0) { - bits |= ASTNode.IsLocalDeclarationReachable; // only set if actually reached + public LocalVariableBinding getBinding() { + return this.binding; } - if (this.initialization != null) { - int nullStatus = this.initialization.nullStatus(flowInfo); - flowInfo = - this.initialization - .analyseCode(currentScope, flowContext, flowInfo) - .unconditionalInits(); - if (!flowInfo.isDefinitelyAssigned(this.binding)){// for local variable debug attributes - this.bits |= FirstAssignmentToLocal; - } else { - this.bits &= ~FirstAssignmentToLocal; // int i = (i = 0); + + public void setBinding(LocalVariableBinding binding) { + this.binding = binding; + } + + public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) { + // record variable initialization if any + if ((flowInfo.tagBits & FlowInfo.UNREACHABLE) == 0) { + // only set if actually reached + bits |= ASTNode.IsLocalDeclarationReachable; } - flowInfo.markAsDefinitelyAssigned(binding); - if ( true){//(this.binding.type.tagBits & TagBits.IsBaseType) == 0) { - switch(nullStatus) { + if (this.initialization != null) { + int nullStatus = this.initialization.nullStatus(flowInfo); + flowInfo = this.initialization.analyseCode(currentScope, flowContext, flowInfo).unconditionalInits(); + // for local variable debug attributes + if (!flowInfo.isDefinitelyAssigned(this.binding)) { + this.bits |= FirstAssignmentToLocal; + } + else { + this.bits &= ~FirstAssignmentToLocal; // int i = (i = 0); + } + flowInfo.markAsDefinitelyAssigned(binding); + + switch (nullStatus) { case FlowInfo.NULL : flowInfo.markAsDefinitelyNull(this.binding); break; case FlowInfo.NON_NULL : flowInfo.markAsDefinitelyNonNull(this.binding); break; - default: + default : flowInfo.markAsDefinitelyUnknown(this.binding); } // no need to inform enclosing try block since its locals won't get // known by the finally block } + if (this.nextLocal != null) { + flowInfo = this.nextLocal.analyseCode(currentScope, flowContext, flowInfo); + } + + return flowInfo; } - if (this.nextLocal!=null) - flowInfo=this.nextLocal.analyseCode(currentScope, flowContext, flowInfo); - - return flowInfo; -} public void checkModifiers() { - //only potential valid modifier is <> - if (((modifiers & ExtraCompilerModifiers.AccJustFlag) & ~ClassFileConstants.AccFinal) != 0) - //AccModifierProblem -> other (non-visibility problem) - //AccAlternateModifierProblem -> duplicate modifier - //AccModifierProblem | AccAlternateModifierProblem -> visibility problem" + // only potential valid modifier is <> + if (((modifiers & ExtraCompilerModifiers.AccJustFlag) & ~ClassFileConstants.AccFinal) != 0) { + // AccModifierProblem -> other (non-visibility problem) + // AccAlternateModifierProblem -> duplicate modifier + // AccModifierProblem | AccAlternateModifierProblem -> visibility problem" modifiers = (modifiers & ~ExtraCompilerModifiers.AccAlternateModifierProblem) | ExtraCompilerModifiers.AccModifierProblem; + } } /** @@ -117,98 +117,99 @@ public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, Fl return LOCAL_VARIABLE; } - public TypeBinding resolveVarType(BlockScope scope) - { + public TypeBinding resolveVarType(BlockScope scope) { TypeBinding variableType = null; - if (type!=null) - variableType=type.resolveType(scope, true /* check bounds*/); + if (type != null) + variableType = type.resolveType(scope, true /* check bounds */); else { - if (inferredType!=null) - variableType=inferredType.resolveType(scope,this); + if (inferredType != null) + variableType = inferredType.resolveType(scope, this); else - variableType=TypeBinding.UNKNOWN; + variableType = TypeBinding.UNKNOWN; } - checkModifiers(); return variableType; - } public void resolve(BlockScope scope) { resolve0(scope); - if (this.nextLocal!=null) + if (this.nextLocal != null) { this.nextLocal.resolve(scope); + } } - - - private void resolve0(BlockScope scope) { + + private void resolve0(BlockScope scope) { // create a binding and add it to the scope TypeBinding variableType = resolveVarType(scope); - - if (type!=null) - variableType=type.resolveType(scope, true /* check bounds*/); - else { - if (inferredType!=null) - { - variableType=inferredType.resolveType(scope,this); + if (type != null) { + variableType = type.resolveType(scope, true /* check bounds */); + } else { + if (inferredType != null) { + variableType = inferredType.resolveType(scope, this); + } + else { + variableType = TypeBinding.UNKNOWN; } - else - variableType=TypeBinding.UNKNOWN; } checkModifiers(); - Binding varBinding = null; - if (scope.enclosingMethodScope()==null) - varBinding=scope.getBinding(name, Binding.VARIABLE, this, false /*do not resolve hidden field*/); - else - varBinding=scope.getLocalBinding(name, Binding.VARIABLE, this, false); - boolean alreadyDefined=false; - if (varBinding != null && varBinding.isValidBinding()){ - VariableBinding existingVariable=(VariableBinding)varBinding; - if (existingVariable.isFor(this)) - { - if (variableType!=null) - existingVariable.type=variableType; - alreadyDefined=true; + Binding varBinding = null; + if (scope.enclosingMethodScope() == null) { + // do not resolve hidden field + varBinding = scope.getBinding(name, Binding.VARIABLE, this, false); + } else { + varBinding = scope.getLocalBinding(name, Binding.VARIABLE, this, false); + } + + boolean alreadyDefined = false; + if (varBinding != null && varBinding.isValidBinding()) { + VariableBinding existingVariable = (VariableBinding) varBinding; + if (existingVariable.isFor(this)) { + if (variableType != null) + existingVariable.type = variableType; + alreadyDefined = true; } - else - { - - if (existingVariable instanceof LocalVariableBinding && this.hiddenVariableDepth == 0) { - LocalVariableBinding localVariableBinding=(LocalVariableBinding)existingVariable; - if (localVariableBinding.declaringScope instanceof CompilationUnitScope && scope.enclosingMethodScope()!=null) + else { + if (existingVariable instanceof LocalVariableBinding && this.hiddenVariableDepth == 0) { + LocalVariableBinding localVariableBinding = (LocalVariableBinding) existingVariable; + if (localVariableBinding.declaringScope instanceof CompilationUnitScope && scope.enclosingMethodScope() != null) { + scope.problemReporter().localVariableHiding(this, existingVariable, false); + } else { + scope.problemReporter().redefineLocal(this); + } + } + else { scope.problemReporter().localVariableHiding(this, existingVariable, false); - else - scope.problemReporter().redefineLocal(this); - } else { - scope.problemReporter().localVariableHiding(this, existingVariable, false); - } + } } } - if ((modifiers & ClassFileConstants.AccFinal)!= 0 && this.initialization == null) { + if ((modifiers & ClassFileConstants.AccFinal) != 0 && this.initialization == null) { modifiers |= ExtraCompilerModifiers.AccBlankFinal; } - if (!(this.binding!=null && alreadyDefined)) - { + if (!(this.binding != null && alreadyDefined)) { this.binding = new LocalVariableBinding(this, variableType, modifiers, false); MethodScope methodScope = scope.enclosingMethodScope(); - if (methodScope!=null) + if (methodScope != null) { methodScope.addLocalVariable(binding); - else + } else { scope.compilationUnitScope().addLocalVariable(binding); + } } // allow to recursivelly target the binding.... // the correct constant is harmed if correctly computed at the end of this method if (variableType == null) { - if (initialization != null) - initialization.resolveType(scope); // want to report all possible errors + if (initialization != null) { + // want to report all possible errors + initialization.resolveType(scope); + } + return; } @@ -219,80 +220,36 @@ public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, Fl if (initializationType != null) { ((ArrayInitializer) initialization).binding = (ArrayBinding) initializationType; } - } else { - this.initialization.setExpectedType(variableType); + } + else { + this.initialization.setExpectedType(variableType); TypeBinding initializationType = this.initialization.resolveType(scope); if (initializationType != null) { -// if (variableType != initializationType) // must call before computeConversion() and typeMismatchError() -// scope.compilationUnitScope().recordTypeConversion(variableType, initializationType); - if (initializationType.isFunctionType()) - { - MethodBinding existingMethod = scope.findMethod(this.name, null,false); - if (existingMethod!=null) - { - MethodBinding functionBinding = ((FunctionTypeBinding)initializationType).functionBinding; + if (initializationType.isFunctionType()) { + MethodBinding existingMethod = scope.findMethod(this.name, null, false); + if (existingMethod != null) { + MethodBinding functionBinding = ((FunctionTypeBinding) initializationType).functionBinding; existingMethod.updateFrom(functionBinding); } } - if (variableType==TypeBinding.UNKNOWN && initializationType!=TypeBinding.NULL) - this.binding.type=initializationType; + if (variableType == TypeBinding.UNKNOWN && initializationType != TypeBinding.NULL) + this.binding.type = initializationType; else { TypeBinding reconcileAnonymous = initializationType.reconcileAnonymous(this.binding.type); - if (reconcileAnonymous!=null) - this.binding.type=variableType=reconcileAnonymous; - - if (initialization.isConstantValueOfTypeAssignableToType(initializationType, variableType) - || variableType.isBaseType() /* && BaseTypeBinding.isWidening(variableType.id, initializationType.id)) */ - || initializationType.isCompatibleWith(variableType)) { - - -// this.initialization.computeConversion(scope, variableType, initializationType); -// if (initializationType.needsUncheckedConversion(variableType)) { -// scope.problemReporter().unsafeTypeConversion(this.initialization, initializationType, variableType); -// } -// if (this.initialization instanceof CastExpression -// && (this.initialization.bits & ASTNode.UnnecessaryCast) == 0) { -// CastExpression.checkNeedForAssignedCast(scope, variableType, (CastExpression) this.initialization); -// } -// } else if (scope.isBoxingCompatibleWith(initializationType, variableType) -// || (initializationType.isBaseType() // narrowing then boxing ? -// && scope.compilerOptions().sourceLevel >= ClassFileConstants.JDK1_5 // autoboxing -// && !variableType.isBaseType() -// && initialization.isConstantValueOfTypeAssignableToType(initializationType, scope.environment().computeBoxingType(variableType)))) { -// this.initialization.computeConversion(scope, variableType, initializationType); -// if (this.initialization instanceof CastExpression -// && (this.initialization.bits & ASTNode.UnnecessaryCast) == 0) { -// CastExpression.checkNeedForAssignedCast(scope, variableType, (CastExpression) this.initialization); -// } - } else { - //scope.problemReporter().typeMismatchError(initializationType, variableType, this.initialization); + if (reconcileAnonymous != null) { + this.binding.type = variableType = reconcileAnonymous; } } } } + // check for assignment with no effect - if (this.binding == Assignment.getDirectBinding(this.initialization)) { scope.problemReporter().assignmentHasNoEffect(this, this.name); } } - // Resolve Javadoc comment if one is present - if (this.javadoc != null) { - /* - if (classScope != null) { - this.javadoc.resolve(classScope); - } - */ - if (scope.enclosingMethodScope()!=null) - this.javadoc.resolve(scope.enclosingMethodScope()); - else - this.javadoc.resolve(scope.compilationUnitScope()); - } - - // only resolve annotation at the end, for constant to be positionned before (96991) -// if (JavaScriptCore.IS_ECMASCRIPT4) -// resolveAnnotations(scope, this.annotations, this.binding); } + public StringBuffer printStatement(int indent, StringBuffer output) { if (this.javadoc != null) { this.javadoc.print(indent, output); @@ -303,30 +260,71 @@ public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, Fl public void traverse(ASTVisitor visitor, BlockScope scope) { if (visitor.visit(this, scope)) { - if (type!=null) + if (type != null) { type.traverse(visitor, scope); + } + IAssignment assignment = getAssignment(); if (assignment != null) { ((Assignment) assignment).traverse(visitor, scope); } - else if (initialization != null) + else if (initialization != null) { initialization.traverse(visitor, scope); + } } visitor.endVisit(this, scope); - if (this.nextLocal!=null) + if (this.nextLocal != null) { this.nextLocal.traverse(visitor, scope); + } } - public String getTypeName() - { - if (type!=null) + public String getTypeName() { + if (type != null) { return type.toString(); - if (inferredType!=null) + } + + if (inferredType != null) { return new String(inferredType.getName()); + } + return null; } + public int getASTType() { return IASTNode.LOCAL_DECLARATION; + } + + /** + *

+ * Set if declaration is a type on the declaration and the assignment. + *

+ * + * @see org.eclipse.wst.jsdt.internal.compiler.ast.AbstractVariableDeclaration#setIsType(boolean) + */ + public void setIsType(boolean isType) { + super.setIsType(isType); + + if(this.getAssignment() != null) { + this.getAssignment().setIsType(isType); + } + } + + /** + *

+ * Is type if declaration set as type or assignment is set as type. + *

+ * + * @see org.eclipse.wst.jsdt.internal.compiler.ast.AbstractVariableDeclaration#isType() + */ + public boolean isType() { + return super.isType() || (this.getAssignment() != null && this.getAssignment().isType()); + } + + public void setIsLocal(boolean isLocal) { + this.isLocal = isLocal; + } + public boolean isLocal() { + return this.isLocal; } -} +} \ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/MessageSend.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/MessageSend.java index 6b0c4fac..fb8c5c72 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/MessageSend.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/MessageSend.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -31,7 +31,6 @@ import org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding; import org.eclipse.wst.jsdt.internal.compiler.lookup.ProblemMethodBinding; import org.eclipse.wst.jsdt.internal.compiler.lookup.ProblemReasons; import org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding; -import org.eclipse.wst.jsdt.internal.compiler.lookup.Scope; import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding; import org.eclipse.wst.jsdt.internal.compiler.problem.ProblemSeverities; @@ -40,433 +39,303 @@ public class MessageSend extends Expression implements InvocationSite, IFunction public Expression receiver; public char[] selector; public Expression[] arguments; - public MethodBinding binding; // exact binding resulting from lookup - public TypeBinding expectedType; // for generic method invocation (return type inference) + + /** + * exact binding resulting from lookup + */ + public MethodBinding binding; + + /** + * for generic method invocation (return type inference) + */ + public TypeBinding expectedType; - public long nameSourcePosition ; //(start<<32)+end + /** + * (start<<32)+end + */ + public long nameSourcePosition; public TypeBinding actualReceiverType; - + public char[] getSelector() { return this.selector; } - + public IExpression[] getArguments() { return this.arguments; } - - -public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) { - - boolean nonStatic = binding==null || !binding.isStatic(); - if (receiver!=null) - { - flowInfo = receiver.analyseCode(currentScope, flowContext, flowInfo, nonStatic).unconditionalInits(); - if (nonStatic) { - receiver.checkNPE(currentScope, flowContext, flowInfo); + + + public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) { + + boolean nonStatic = binding == null || !binding.isStatic(); + if (receiver != null) { + flowInfo = receiver.analyseCode(currentScope, flowContext, flowInfo, nonStatic).unconditionalInits(); + if (nonStatic) { + receiver.checkNPE(currentScope, flowContext, flowInfo); + } } - } - if(selector != null) { - Binding existingVariable = currentScope.getLocalBinding(selector, Binding.VARIABLE, this, false /*do not resolve hidden field*/); - if(existingVariable != null && existingVariable instanceof LocalVariableBinding) { - LocalVariableBinding localBinding = (LocalVariableBinding) existingVariable; - - if ((flowInfo.tagBits & FlowInfo.UNREACHABLE) == 0) { - localBinding.useFlag = LocalVariableBinding.USED; - } else if (localBinding.useFlag == LocalVariableBinding.UNUSED) { - localBinding.useFlag = LocalVariableBinding.FAKE_USED; - } + if (selector != null) { + Binding existingVariable = currentScope.getLocalBinding(selector, Binding.VARIABLE, this, false); + if (existingVariable != null && existingVariable instanceof LocalVariableBinding) { + LocalVariableBinding localBinding = (LocalVariableBinding) existingVariable; + + if ((flowInfo.tagBits & FlowInfo.UNREACHABLE) == 0) { + localBinding.useFlag = LocalVariableBinding.USED; + } + else if (localBinding.useFlag == LocalVariableBinding.UNUSED) { + localBinding.useFlag = LocalVariableBinding.FAKE_USED; + } + } } - } - if (arguments != null) { - int length = arguments.length; - for (int i = 0; i < length; i++) { - flowInfo = arguments[i].analyseCode(currentScope, flowContext, flowInfo).unconditionalInits(); + if (arguments != null) { + int length = arguments.length; + for (int i = 0; i < length; i++) { + flowInfo = arguments[i].analyseCode(currentScope, flowContext, flowInfo).unconditionalInits(); + } } + return flowInfo; } - return flowInfo; -} -/** - * @see org.eclipse.wst.jsdt.internal.compiler.ast.Expression#computeConversion(org.eclipse.wst.jsdt.internal.compiler.lookup.Scope, org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding, org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding) - */ -public void computeConversion(Scope scope, TypeBinding runtimeTimeType, TypeBinding compileTimeType) { -// if (runtimeTimeType == null || compileTimeType == null) -// return; -// // set the generic cast after the fact, once the type expectation is fully known (no need for strict cast) -// if (this.binding != null && this.binding.isValidBinding()) { -// FunctionBinding originalBinding = this.binding.original(); -// TypeBinding originalType = originalBinding.returnType; -// // extra cast needed if method return type is type variable -// if (originalBinding != this.binding -// && originalType != this.binding.returnType -// && runtimeTimeType.id != T_JavaLangObject -// && (originalType.tagBits & TagBits.HasTypeVariable) != 0) { -// TypeBinding targetType = (!compileTimeType.isBaseType() && runtimeTimeType.isBaseType()) -// ? compileTimeType // unboxing: checkcast before conversion -// : runtimeTimeType; -// this.valueCast = originalType.genericCast(targetType); -// } else if (this.actualReceiverType!=null && this.actualReceiverType.isArrayType() -// && runtimeTimeType.id != T_JavaLangObject -// && this.binding.parameters == Binding.NO_PARAMETERS -// && scope.compilerOptions().complianceLevel >= ClassFileConstants.JDK1_5 -// && CharOperation.equals(this.binding.selector, CLONE)) { -// // from 1.5 compliant mode on, array#clone() resolves to array type, but codegen to #clone()Object - thus require extra inserted cast -// this.valueCast = runtimeTimeType; -// } -// } -// super.computeConversion(scope, runtimeTimeType, compileTimeType); -} -public boolean isSuperAccess() { - return receiver!=null && receiver.isSuper(); -} -public boolean isTypeAccess() { - return receiver != null && receiver.isTypeReference(); -} -public void manageSyntheticAccessIfNecessary(BlockScope currentScope, FlowInfo flowInfo){ - - if ((flowInfo.tagBits & FlowInfo.UNREACHABLE) != 0) return; - - // if method from parameterized type got found, use the original method at codegen time -// this.codegenBinding = this.binding.original(); - if (this.binding.isPrivate()){ - -// // depth is set for both implicit and explicit access (see FunctionBinding#canBeSeenBy) -// if (currentScope.enclosingSourceType() != this.codegenBinding.declaringClass){ -// -// syntheticAccessor = ((SourceTypeBinding)this.codegenBinding.declaringClass).addSyntheticMethod(this.codegenBinding, isSuperAccess()); -// currentScope.problemReporter().needToEmulateMethodAccess(this.codegenBinding, this); -// return; -// } - - } else if (binding.isProtected()){ - -// SourceTypeBinding enclosingSourceType; -// if (((bits & DepthMASK) != 0) -// && this.codegenBinding.declaringClass.getPackage() -// != (enclosingSourceType = currentScope.enclosingSourceType()).getPackage()){ -// -// SourceTypeBinding currentCompatibleType = (SourceTypeBinding)enclosingSourceType.enclosingTypeAt((bits & DepthMASK) >> DepthSHIFT); -// syntheticAccessor = currentCompatibleType.addSyntheticMethod(this.codegenBinding, isSuperAccess()); -// currentScope.problemReporter().needToEmulateMethodAccess(this.codegenBinding, this); -// return; -// } + public boolean isSuperAccess() { + return receiver != null && receiver.isSuper(); } - // if the binding declaring class is not visible, need special action - // for runtime compatibility on 1.2 VMs : change the declaring class of the binding - // NOTE: from target 1.2 on, method's declaring class is touched if any different from receiver type - // and not from Object or implicit static method call. -// if (this.binding.declaringClass != this.actualReceiverType -// && this.receiverGenericCast == null -// && !this.actualReceiverType.isArrayType()) { -// CompilerOptions options = currentScope.compilerOptions(); -// if ((options.targetJDK >= ClassFileConstants.JDK1_2 -// && (options.complianceLevel >= ClassFileConstants.JDK1_4 || !(receiver.isImplicitThis() && this.codegenBinding.isStatic())) -// && this.binding.declaringClass.id != T_JavaLangObject) // no change for Object methods -// || !this.binding.declaringClass.canBeSeenBy(currentScope)) { -// -// this.codegenBinding = currentScope.enclosingSourceType().getUpdatedMethodBinding( -// this.codegenBinding, (ReferenceBinding) this.actualReceiverType.erasure()); -// } -// // Post 1.4.0 target, array clone() invocations are qualified with array type -// // This is handled in array type #clone method binding resolution (see Scope and UpdatedMethodBinding) -// } -} -public int nullStatus(FlowInfo flowInfo) { - return FlowInfo.UNKNOWN; -} - -/** - * @see org.eclipse.wst.jsdt.internal.compiler.ast.Expression#postConversionType(Scope) - */ -public TypeBinding postConversionType(Scope scope) { - TypeBinding convertedType = this.resolvedType; -// if (this.valueCast != null) -// convertedType = this.valueCast; - int runtimeType = (this.implicitConversion & IMPLICIT_CONVERSION_MASK) >> 4; - switch (runtimeType) { - case T_boolean : - convertedType = TypeBinding.BOOLEAN; - break; - case T_short : - convertedType = TypeBinding.SHORT; - break; - case T_char : - convertedType = TypeBinding.CHAR; - break; - case T_int : - convertedType = TypeBinding.INT; - break; - case T_float : - convertedType = TypeBinding.FLOAT; - break; - case T_long : - convertedType = TypeBinding.LONG; - break; - case T_double : - convertedType = TypeBinding.DOUBLE; - break; - default : + public boolean isTypeAccess() { + return receiver != null && receiver.isTypeReference(); } - if ((this.implicitConversion & BOXING) != 0) { - convertedType = scope.environment().computeBoxingType(convertedType); - } - return convertedType; -} -public StringBuffer printExpression(int indent, StringBuffer output){ - - if (receiver!=null && !receiver.isImplicitThis()) - { - receiver.printExpression(0, output); - if (selector!=null) - output.append('.'); + public int nullStatus(FlowInfo flowInfo) { + return FlowInfo.UNKNOWN; } - if (selector!=null) - output.append(selector); - output.append('(') ; - if (arguments != null) { - for (int i = 0; i < arguments.length ; i ++) { - if (i > 0) output.append(", "); //$NON-NLS-1$ - arguments[i].printExpression(0, output); + + public StringBuffer printExpression(int indent, StringBuffer output) { + if (receiver != null && !receiver.isImplicitThis()) { + receiver.printExpression(0, output); + if (selector != null) { + output.append('.'); + } + } + if (selector != null) { + output.append(selector); + } + + output.append('('); + if (arguments != null) { + for (int i = 0; i < arguments.length; i++) { + if (i > 0) { + output.append(", "); //$NON-NLS-1$ + } + arguments[i].printExpression(0, output); + } } + return output.append(')'); } - return output.append(')'); -} -public TypeBinding resolveType(BlockScope scope) { - // Answer the signature return type - // Base type promotion + public TypeBinding resolveType(BlockScope scope) { + // Answer the signature return type Base type promotion + constant = Constant.NotAConstant; - constant = Constant.NotAConstant; + if (receiver instanceof FunctionExpression) { + FunctionExpression expr = (FunctionExpression) receiver; + if (expr.methodDeclaration != null) { + if (arguments != null && expr.methodDeclaration.arguments != null) { + for (int i = 0; i < Math.min(arguments.length, expr.methodDeclaration.arguments.length); i++) { + Expression msgSndArgument = arguments[i]; + Argument funcExprArgument = expr.methodDeclaration.arguments[i]; - - if (receiver instanceof FunctionExpression) { - FunctionExpression expr = (FunctionExpression) receiver; - if (expr.methodDeclaration != null) { - if (arguments != null && expr.methodDeclaration.arguments != null) { - for (int i = 0; i < Math.min(arguments.length, expr.methodDeclaration.arguments.length); i++) { - Expression msgSndArgument = arguments[i]; - Argument funcExprArgument = expr.methodDeclaration.arguments[i]; - - if (msgSndArgument != null) { - msgSndArgument.resolve(scope); - if (msgSndArgument.resolvedType != null) { - funcExprArgument.type = new SingleTypeReference(msgSndArgument.resolvedType.readableName(), 0); - funcExprArgument.type.resolvedType = arguments[i].resolvedType; + if (msgSndArgument != null) { + msgSndArgument.resolve(scope); + if (msgSndArgument.resolvedType != null) { + funcExprArgument.type = new SingleTypeReference(msgSndArgument.resolvedType.readableName(), 0); + funcExprArgument.type.resolvedType = arguments[i].resolvedType; + } } } } } } - } - - this.actualReceiverType = (receiver!=null) ?receiver.resolveType(scope):null; - boolean receiverIsType = (receiver instanceof NameReference || receiver instanceof FieldReference || receiver instanceof ThisReference) - && ( receiver.bits & Binding.TYPE) != 0; - - // will check for null after args are resolved - TypeBinding[] argumentTypes = Binding.NO_PARAMETERS; - if (arguments != null) { - boolean argHasError = false; // typeChecks all arguments - int length = arguments.length; - argumentTypes = new TypeBinding[length]; - for (int i = 0; i < length; i++){ - Expression argument = arguments[i]; - if ((argumentTypes[i] = argument.resolveType(scope)) == null){ - argHasError = true; + + this.actualReceiverType = (receiver != null) ? receiver.resolveType(scope) : null; + boolean receiverIsType = (receiver instanceof NameReference || receiver instanceof FieldReference || receiver instanceof ThisReference) && (receiver.bits & Binding.TYPE) != 0; + + // will check for null after args are resolved + TypeBinding[] argumentTypes = Binding.NO_PARAMETERS; + if (arguments != null) { + int length = arguments.length; + argumentTypes = new TypeBinding[length]; + for (int i = 0; i < length; i++) { + Expression argument = arguments[i]; + if ((argumentTypes[i] = argument.resolveType(scope)) == null) { + argumentTypes[i] = TypeBinding.UNKNOWN; + } } } - if (argHasError) { - if (actualReceiverType instanceof ReferenceBinding) { - // record a best guess, for clients who need hint about possible method match - TypeBinding[] pseudoArgs = new TypeBinding[length]; - for (int i = length; --i >= 0;) - pseudoArgs[i] = argumentTypes[i] == null ? TypeBinding.NULL : argumentTypes[i]; // replace args with errors with receiver - if (selector==null) - this.binding=new IndirectMethodBinding(0,this.actualReceiverType,argumentTypes,scope.compilationUnitScope().referenceContext.compilationUnitBinding); - else - this.binding = - receiver.isImplicitThis() - ? scope.getImplicitMethod(selector, pseudoArgs, this) - : scope.findMethod((ReferenceBinding) actualReceiverType, selector, pseudoArgs, this); - if (binding != null && !binding.isValidBinding()) { - MethodBinding closestMatch = ((ProblemMethodBinding)binding).closestMatch; - // record the closest match, for clients who may still need hint about possible method match - if (closestMatch != null) { - this.binding = closestMatch; - MethodBinding closestMatchOriginal = closestMatch.original(); - if ((closestMatchOriginal.isPrivate() || closestMatchOriginal.declaringClass.isLocalType()) && !scope.isDefinedInMethod(closestMatchOriginal)) { - // ignore cases where method is used from within inside itself (e.g. direct recursions) - closestMatchOriginal.original().modifiers |= ExtraCompilerModifiers.AccLocallyUsed; - } + + if (selector == null) { + this.binding = new IndirectMethodBinding(0, this.actualReceiverType, argumentTypes, scope.compilationUnitScope().referenceContext.compilationUnitBinding); + } else { + if (receiver == null) { + this.binding = scope.getImplicitMethod(selector, argumentTypes, this); + } else { + this.binding = scope.getMethod(this.actualReceiverType, selector, argumentTypes, this); + // if receiver type was function, try using binding from receiver + if (!binding.isValidBinding() && (this.actualReceiverType != null && this.actualReceiverType.isFunctionType())) { + Binding alternateBinding = receiver.alternateBinding(); + if (alternateBinding instanceof TypeBinding) { + this.actualReceiverType = (TypeBinding) alternateBinding; + this.binding = scope.getMethod(this.actualReceiverType, selector, argumentTypes, this); + receiverIsType = true; } } + else if (!binding.isValidBinding() && receiverIsType) { + /* we are a type, check the alternate binding which will + * be a Function object */ + Binding alternateBinding = scope.getJavaLangFunction(); + MethodBinding tempBinding = scope.getMethod((TypeBinding) alternateBinding, selector, argumentTypes, this); + if (tempBinding.isValidBinding()) { + this.actualReceiverType = (TypeBinding) alternateBinding; + this.binding = tempBinding; + receiverIsType = false; + } + } + } - return null; - } - } -// if (this.actualReceiverType == null) { -// return null; -// } - // base type cannot receive any message -// if (this.actualReceiverType!=null && this.actualReceiverType.isBaseType()) { -// scope.problemReporter().errorNoMethodFor(this, this.actualReceiverType, argumentTypes); -// return null; -// } - if (selector==null) - this.binding=new IndirectMethodBinding(0,this.actualReceiverType,argumentTypes,scope.compilationUnitScope().referenceContext.compilationUnitBinding); - else - { - if (receiver==null /*|| receiver.isImplicitThis()*/) - this.binding =scope.getImplicitMethod(selector, argumentTypes, this); - else - { - this.binding =scope.getMethod(this.actualReceiverType, selector, argumentTypes, this); - // if receiver type was function, try using binding from receiver - if (!binding.isValidBinding() && (this.actualReceiverType!=null && this.actualReceiverType.isFunctionType())) - { - Binding alternateBinding = receiver.alternateBinding(); - if (alternateBinding instanceof TypeBinding) - { - this.actualReceiverType=(TypeBinding)alternateBinding; - this.binding=scope.getMethod(this.actualReceiverType, selector, argumentTypes, this); - receiverIsType=true; - } - } else if(!binding.isValidBinding() && receiverIsType) { - // we are a type, check the alternate binding which will be a Function object - Binding alternateBinding = scope.getJavaLangFunction(); - MethodBinding tempBinding = scope.getMethod((TypeBinding)alternateBinding, selector, argumentTypes, this); - if(tempBinding.isValidBinding()) { - this.actualReceiverType=(TypeBinding)alternateBinding; - this.binding = tempBinding; - receiverIsType=false; - } - } - + if (argumentTypes.length != this.binding.parameters.length) + scope.problemReporter().wrongNumberOfArguments(this, this.binding); } - if (argumentTypes.length!=this.binding.parameters.length) - scope.problemReporter().wrongNumberOfArguments(this, this.binding); - } - if (!binding.isValidBinding() && !(this.actualReceiverType==TypeBinding.ANY || this.actualReceiverType==TypeBinding.UNKNOWN)) { - if (binding.declaringClass == null) { - if (this.actualReceiverType==null || this.actualReceiverType instanceof ReferenceBinding) { - binding.declaringClass = (ReferenceBinding) this.actualReceiverType; - } else { - return null; + if (!binding.isValidBinding() && !(this.actualReceiverType == TypeBinding.ANY || this.actualReceiverType == TypeBinding.UNKNOWN)) { + if (binding.declaringClass == null) { + if (this.actualReceiverType == null || this.actualReceiverType instanceof ReferenceBinding) { + binding.declaringClass = (ReferenceBinding) this.actualReceiverType; + } + else { + return null; + } + } + scope.problemReporter().invalidMethod(this, binding); + MethodBinding closestMatch = ((ProblemMethodBinding) binding).closestMatch; + switch (this.binding.problemId()) { + case ProblemReasons.Ambiguous : + break; // no resilience on ambiguous + case ProblemReasons.NotVisible : + case ProblemReasons.NonStaticReferenceInConstructorInvocation : + case ProblemReasons.NonStaticReferenceInStaticContext : + case ProblemReasons.ReceiverTypeNotVisible : + // only steal returnType in cases listed above + if (closestMatch != null) + this.resolvedType = closestMatch.returnType; + } + /* record the closest match, for clients who may still need hint + * about possible method match */ + if (closestMatch != null) { + this.binding = closestMatch; + MethodBinding closestMatchOriginal = closestMatch.original(); + if ((closestMatchOriginal.isPrivate() || closestMatchOriginal.declaringClass.isLocalType()) && !scope.isDefinedInMethod(closestMatchOriginal)) { + // ignore cases where method is used from within inside itself (e.g. direct recursions) + closestMatchOriginal.original().modifiers |= ExtraCompilerModifiers.AccLocallyUsed; + } } + + return this.resolvedType; } - scope.problemReporter().invalidMethod(this, binding); - MethodBinding closestMatch = ((ProblemMethodBinding)binding).closestMatch; - switch (this.binding.problemId()) { - case ProblemReasons.Ambiguous : - break; // no resilience on ambiguous - case ProblemReasons.NotVisible : - case ProblemReasons.NonStaticReferenceInConstructorInvocation : - case ProblemReasons.NonStaticReferenceInStaticContext : - case ProblemReasons.ReceiverTypeNotVisible : - // only steal returnType in cases listed above - if (closestMatch != null) this.resolvedType = closestMatch.returnType; + final CompilerOptions compilerOptions = scope.compilerOptions(); + if (!binding.isStatic()) { + /* the "receiver" must not be a type, in other words, a + * NameReference that the TC has bound to a Type */ + if (receiverIsType && binding.isValidBinding()) { + scope.problemReporter().mustUseAStaticMethod(this, binding); + } } - // record the closest match, for clients who may still need hint about possible method match - if (closestMatch != null) { - this.binding = closestMatch; - MethodBinding closestMatchOriginal = closestMatch.original(); - if ((closestMatchOriginal.isPrivate() || closestMatchOriginal.declaringClass.isLocalType()) && !scope.isDefinedInMethod(closestMatchOriginal)) { - // ignore cases where method is used from within inside itself (e.g. direct recursions) - closestMatchOriginal.original().modifiers |= ExtraCompilerModifiers.AccLocallyUsed; + else { + if (receiver != null) { + // static message invoked through receiver? legal but unoptimal (optional warning). + if (!(receiver.isImplicitThis() || receiver.isSuper() || receiverIsType)) { + scope.problemReporter().nonStaticAccessToStaticMethod(this, binding); + } + if (!receiver.isImplicitThis() && binding.declaringClass != actualReceiverType) { + // scope.problemReporter().indirectAccessToStaticMethod(this, binding); + } } } - return this.resolvedType; - } - final CompilerOptions compilerOptions = scope.compilerOptions(); - if (!binding.isStatic()) { - // the "receiver" must not be a type, in other words, a NameReference that the TC has bound to a Type - if (receiverIsType && binding.isValidBinding()) { - scope.problemReporter().mustUseAStaticMethod(this, binding); + + if (isMethodUseDeprecated(binding, scope, true)) { + scope.problemReporter().deprecatedMethod(binding, this); } - } else { - if (receiver!=null) { - // static message invoked through receiver? legal but unoptimal (optional warning). - if (!(receiver.isImplicitThis() || receiver.isSuper() || receiverIsType)) { - scope.problemReporter().nonStaticAccessToStaticMethod(this, - binding); - } - if (!receiver.isImplicitThis() - && binding.declaringClass != actualReceiverType) { - // scope.problemReporter().indirectAccessToStaticMethod(this, binding); + + + TypeBinding returnType = this.binding.returnType; + if (returnType == null) { + returnType = TypeBinding.UNKNOWN; + } + + this.resolvedType = returnType; + + if (receiver != null && receiver.isSuper() && compilerOptions.getSeverity(CompilerOptions.OverridingMethodWithoutSuperInvocation) != ProblemSeverities.Ignore) { + final ReferenceContext referenceContext = scope.methodScope().referenceContext; + if (referenceContext instanceof AbstractMethodDeclaration) { + final AbstractMethodDeclaration abstractMethodDeclaration = (AbstractMethodDeclaration) referenceContext; + MethodBinding enclosingMethodBinding = abstractMethodDeclaration.binding; + if (enclosingMethodBinding.isOverriding() && CharOperation.equals(this.binding.selector, enclosingMethodBinding.selector) && this.binding.areParametersEqual(enclosingMethodBinding)) { + abstractMethodDeclaration.bits |= ASTNode.OverridingMethodWithSupercall; + } } } + return this.resolvedType; } -// checkInvocationArguments(scope, this.receiver, actualReceiverType, binding, this.arguments, argumentTypes, argsContainCast, this); - if (isMethodUseDeprecated(binding, scope, true)) - scope.problemReporter().deprecatedMethod(binding, this); + public void setActualReceiverType(ReferenceBinding receiverType) { + // error scenario only + if (receiverType == null) { + return; + } + + this.actualReceiverType = receiverType; + } - - TypeBinding returnType = this.binding.returnType; - if (returnType == null) - returnType=TypeBinding.UNKNOWN; - this.resolvedType = returnType; - - if (receiver!=null && receiver.isSuper() && compilerOptions.getSeverity(CompilerOptions.OverridingMethodWithoutSuperInvocation) != ProblemSeverities.Ignore) { - final ReferenceContext referenceContext = scope.methodScope().referenceContext; - if (referenceContext instanceof AbstractMethodDeclaration) { - final AbstractMethodDeclaration abstractMethodDeclaration = (AbstractMethodDeclaration) referenceContext; - MethodBinding enclosingMethodBinding = abstractMethodDeclaration.binding; - if (enclosingMethodBinding.isOverriding() - && CharOperation.equals(this.binding.selector, enclosingMethodBinding.selector) - && this.binding.areParametersEqual(enclosingMethodBinding)) { - abstractMethodDeclaration.bits |= ASTNode.OverridingMethodWithSupercall; - } + public void setDepth(int depth) { + bits &= ~DepthMASK; // flush previous depth if any + if (depth > 0) { + bits |= (depth & 0xFF) << DepthSHIFT; // encoded on 8 bits } } - return this.resolvedType; -} -public void setActualReceiverType(ReferenceBinding receiverType) { - if (receiverType == null) return; // error scenario only - this.actualReceiverType = receiverType; -} -public void setDepth(int depth) { - bits &= ~DepthMASK; // flush previous depth if any - if (depth > 0) { - bits |= (depth & 0xFF) << DepthSHIFT; // encoded on 8 bits + /** + * @see org.eclipse.wst.jsdt.internal.compiler.ast.Expression#setExpectedType(org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding) + */ + public void setExpectedType(TypeBinding expectedType) { + this.expectedType = expectedType; } -} -/** - * @see org.eclipse.wst.jsdt.internal.compiler.ast.Expression#setExpectedType(org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding) - */ -public void setExpectedType(TypeBinding expectedType) { - this.expectedType = expectedType; -} -public void setFieldIndex(int depth) { - // ignore for here -} + public void setFieldIndex(int depth) { + // ignore for here + } -public void traverse(ASTVisitor visitor, BlockScope blockScope) { - if (visitor.visit(this, blockScope)) { - if (receiver!=null) - receiver.traverse(visitor, blockScope); - if (arguments != null) { - int argumentsLength = arguments.length; - for (int i = 0; i < argumentsLength; i++) - arguments[i].traverse(visitor, blockScope); + public void traverse(ASTVisitor visitor, BlockScope blockScope) { + if (visitor.visit(this, blockScope)) { + if (receiver != null) { + receiver.traverse(visitor, blockScope); + } + + if (arguments != null) { + int argumentsLength = arguments.length; + for (int i = 0; i < argumentsLength; i++) { + arguments[i].traverse(visitor, blockScope); + } + } } + visitor.endVisit(this, blockScope); } - visitor.endVisit(this, blockScope); -} -public int getASTType() { - return IASTNode.FUNCTION_CALL; -} + public int getASTType() { + return IASTNode.FUNCTION_CALL; -public IExpression getReceiver() { - return this.receiver; -} + } + + public IExpression getReceiver() { + return this.receiver; + } } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/MethodDeclaration.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/MethodDeclaration.java index 7d34022f..54ab35d9 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/MethodDeclaration.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/MethodDeclaration.java @@ -53,14 +53,10 @@ public class MethodDeclaration extends AbstractMethodDeclaration implements IFun (this.binding.isPrivate() || (((this.binding.modifiers & (ExtraCompilerModifiers.AccOverriding|ExtraCompilerModifiers.AccImplementing)) == 0) && this.binding.declaringClass.isLocalType()))) { if (!classScope.referenceCompilationUnit().compilationResult.hasSyntaxError) { - scope.problemReporter().unusedPrivateMethod(this); + getScope().problemReporter().unusedPrivateMethod(this); } } -// // skip enum implicit methods -// if (binding.declaringClass.isEnum() && (this.selector == TypeConstants.VALUES || this.selector == TypeConstants.VALUEOF)) -// return flowInfo; - // may be in a non necessary for innerclass with static final constant fields if (binding.isAbstract()) return flowInfo; @@ -70,7 +66,7 @@ public class MethodDeclaration extends AbstractMethodDeclaration implements IFun initializationContext, this, null, - scope, + this.getScope(), FlowInfo.DEAD_END); // tag parameters as being set @@ -84,11 +80,11 @@ public class MethodDeclaration extends AbstractMethodDeclaration implements IFun boolean didAlreadyComplain = false; for (int i = 0, count = statements.length; i < count; i++) { Statement stat = statements[i]; - if (!stat.complainIfUnreachable(flowInfo, scope, didAlreadyComplain)) { + if (!stat.complainIfUnreachable(flowInfo, this.getScope(), didAlreadyComplain)) { if (stat instanceof AbstractMethodDeclaration) { - ((AbstractMethodDeclaration)stat).analyseCode(this.scope, null, flowInfo.copy()); + ((AbstractMethodDeclaration)stat).analyseCode(this.getScope(), null, flowInfo.copy()); } else - flowInfo = stat.analyseCode(scope, methodContext, flowInfo); + flowInfo = stat.analyseCode(this.getScope(), methodContext, flowInfo); } else { didAlreadyComplain = true; } @@ -104,10 +100,10 @@ public class MethodDeclaration extends AbstractMethodDeclaration implements IFun if (flowInfo != FlowInfo.DEAD_END) { if ((this.inferredMethod==null || !this.inferredMethod.isConstructor) && !isJsDocInferredReturn) - scope.problemReporter().shouldReturn(returnTypeBinding, this); + this.getScope().problemReporter().shouldReturn(returnTypeBinding, this); } } - this.scope.reportUnusedDeclarations(); + this.getScope().reportUnusedDeclarations(); // check unreachable catch blocks if (JavaScriptCore.IS_ECMASCRIPT4) methodContext.complainIfUnusedExceptionHandlers(this); @@ -118,12 +114,10 @@ public class MethodDeclaration extends AbstractMethodDeclaration implements IFun } public boolean isMethod() { - return true; } public void parseStatements(Parser parser, CompilationUnitDeclaration unit) { - //fill up the method body with statement if (ignoreFurtherInvestigation) return; @@ -131,9 +125,7 @@ public class MethodDeclaration extends AbstractMethodDeclaration implements IFun } public void resolveStatements() { - // ========= abort on fatal error ============= - super.resolveStatements(); } @@ -143,42 +135,39 @@ public class MethodDeclaration extends AbstractMethodDeclaration implements IFun if (visitor.visit(this, classScope)) { if (this.javadoc != null) { - this.javadoc.traverse(visitor, scope); + this.javadoc.traverse(visitor, this.getScope()); } if (arguments != null) { int argumentLength = arguments.length; for (int i = 0; i < argumentLength; i++) - arguments[i].traverse(visitor, scope); + arguments[i].traverse(visitor, this.getScope()); } if (statements != null) { int statementsLength = statements.length; for (int i = 0; i < statementsLength; i++) - statements[i].traverse(visitor, scope); + statements[i].traverse(visitor, this.getScope()); } } visitor.endVisit(this, classScope); } - public void traverse( - ASTVisitor visitor, - BlockScope blockScope) { - - if (visitor.visit(this, blockScope)) { - if (arguments != null) { - int argumentLength = arguments.length; - for (int i = 0; i < argumentLength; i++) - arguments[i].traverse(visitor, scope); - } - if (statements != null) { - int statementsLength = statements.length; - for (int i = 0; i < statementsLength; i++) - statements[i].traverse(visitor, scope); - } + + public void traverse(ASTVisitor visitor, BlockScope blockScope) { + if (visitor.visit(this, blockScope)) { + if (arguments != null) { + int argumentLength = arguments.length; + for (int i = 0; i < argumentLength; i++) + arguments[i].traverse(visitor, this.getScope()); + } + if (statements != null) { + int statementsLength = statements.length; + for (int i = 0; i < statementsLength; i++) + statements[i].traverse(visitor, this.getScope()); } - visitor.endVisit(this, blockScope); } + visitor.endVisit(this, blockScope); + } public int getASTType() { return IASTNode.FUNCTION_DECLARATION; - } } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ObjectLiteral.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ObjectLiteral.java index 8619ab0e..fbe326eb 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ObjectLiteral.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ObjectLiteral.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2008 IBM Corporation and others. + * Copyright (c) 2005, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -75,12 +75,23 @@ public class ObjectLiteral extends Expression implements IObjectLiteral { public TypeBinding resolveType(BlockScope scope) { this.constant=Constant.NotAConstant; - if (this.fields!=null) + if (this.fields!=null) { for (int i = 0; i < this.fields.length; i++) { this.fields[i].resolveType(scope); } - if(inferredType != null && inferredType.binding != null) - return inferredType.binding; + } + + if(inferredType != null) { + //build the type if it is not yet built + if(inferredType.binding == null) { + inferredType.resolveType(scope, this); + } + + if(inferredType.binding != null) { + return inferredType.binding; + } + } + return TypeBinding.ANY; } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/QualifiedNameReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/QualifiedNameReference.java index 37c5a256..ba1c34e0 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/QualifiedNameReference.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/QualifiedNameReference.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -392,45 +392,6 @@ public Constant optimizedBooleanConstant() { return Constant.NotAConstant; } -/** - * @see org.eclipse.wst.jsdt.internal.compiler.ast.Expression#postConversionType(Scope) - */ -public TypeBinding postConversionType(Scope scope) { - TypeBinding convertedType = this.resolvedType; - TypeBinding requiredGenericCast = getGenericCast(this.otherCodegenBindings == null ? 0 : this.otherCodegenBindings.length); - if (requiredGenericCast != null) - convertedType = requiredGenericCast; - int runtimeType = (this.implicitConversion & TypeIds.IMPLICIT_CONVERSION_MASK) >> 4; - switch (runtimeType) { - case T_boolean : - convertedType = TypeBinding.BOOLEAN; - break; - case T_short : - convertedType = TypeBinding.SHORT; - break; - case T_char : - convertedType = TypeBinding.CHAR; - break; - case T_int : - convertedType = TypeBinding.INT; - break; - case T_float : - convertedType = TypeBinding.FLOAT; - break; - case T_long : - convertedType = TypeBinding.LONG; - break; - case T_double : - convertedType = TypeBinding.DOUBLE; - break; - default : - } - if ((this.implicitConversion & TypeIds.BOXING) != 0) { - convertedType = scope.environment().computeBoxingType(convertedType); - } - return convertedType; -} - public StringBuffer printExpression(int indent, StringBuffer output) { for (int i = 0; i < this.tokens.length; i++) { if (i > 0) output.append('.'); diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ReturnStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ReturnStatement.java index 515cbb1b..b0fff98e 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ReturnStatement.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ReturnStatement.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -13,6 +13,7 @@ package org.eclipse.wst.jsdt.internal.compiler.ast; import org.eclipse.wst.jsdt.core.ast.IASTNode; import org.eclipse.wst.jsdt.core.ast.IExpression; import org.eclipse.wst.jsdt.core.ast.IReturnStatement; +import org.eclipse.wst.jsdt.core.infer.InferredType; import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor; import org.eclipse.wst.jsdt.internal.compiler.flow.FlowContext; import org.eclipse.wst.jsdt.internal.compiler.flow.FlowInfo; @@ -31,146 +32,194 @@ public class ReturnStatement extends Statement implements IReturnStatement { public SubRoutineStatement[] subroutines; public LocalVariableBinding saveValueVariable; public int initStateIndex = -1; - -public ReturnStatement(Expression expression, int sourceStart, int sourceEnd) { - this.sourceStart = sourceStart; - this.sourceEnd = sourceEnd; - this.expression = expression ; -} - -public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) { - if (this.expression != null) { - flowInfo = this.expression.analyseCode(currentScope, flowContext, flowInfo); + + /** + *

+ * {@link InferredType} returned by this return statement. + *

+ */ + private InferredType fInferredType; + + /** + *

+ * true if this return statement is actually returning a + * type, rather then the instance of a type. false if this + * return statement is returning an instance of a type rather then the + * type itself. + *

+ */ + private boolean fIsType; + + public ReturnStatement(Expression expression, int sourceStart, int sourceEnd) { + this.sourceStart = sourceStart; + this.sourceEnd = sourceEnd; + this.expression = expression ; + this.fInferredType = null; + this.fIsType = false; } - - // compute the return sequence (running the finally blocks) - FlowContext traversedContext = flowContext; - int subCount = 0; - boolean saveValueNeeded = false; - boolean hasValueToSave = this.expression != null - && this.expression.constant == Constant.NotAConstant - && !(this.expression instanceof NullLiteral); - do { - SubRoutineStatement sub; - if ((sub = traversedContext.subroutine()) != null) { - if (this.subroutines == null){ - this.subroutines = new SubRoutineStatement[5]; - } - if (subCount == this.subroutines.length) { - System.arraycopy(this.subroutines, 0, (this.subroutines = new SubRoutineStatement[subCount*2]), 0, subCount); // grow - } - this.subroutines[subCount++] = sub; - if (sub.isSubRoutineEscaping()) { - saveValueNeeded = false; - this.bits |= ASTNode.IsAnySubRoutineEscaping; - break; - } + + public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) { + if (this.expression != null) { + flowInfo = this.expression.analyseCode(currentScope, flowContext, flowInfo); } - traversedContext.recordReturnFrom(flowInfo.unconditionalInits()); - - if (traversedContext instanceof InsideSubRoutineFlowContext) { - ASTNode node = traversedContext.associatedNode; - if (node instanceof TryStatement) { - TryStatement tryStatement = (TryStatement) node; - flowInfo.addInitializationsFrom(tryStatement.subRoutineInits); // collect inits - if (hasValueToSave) { - if (this.saveValueVariable == null){ // closest subroutine secret variable is used - prepareSaveValueLocation(tryStatement); + + // compute the return sequence (running the finally blocks) + FlowContext traversedContext = flowContext; + int subCount = 0; + boolean saveValueNeeded = false; + boolean hasValueToSave = this.expression != null + && this.expression.constant == Constant.NotAConstant + && !(this.expression instanceof NullLiteral); + do { + SubRoutineStatement sub; + if ((sub = traversedContext.subroutine()) != null) { + if (this.subroutines == null){ + this.subroutines = new SubRoutineStatement[5]; + } + if (subCount == this.subroutines.length) { + System.arraycopy(this.subroutines, 0, (this.subroutines = new SubRoutineStatement[subCount*2]), 0, subCount); // grow + } + this.subroutines[subCount++] = sub; + if (sub.isSubRoutineEscaping()) { + saveValueNeeded = false; + this.bits |= ASTNode.IsAnySubRoutineEscaping; + break; + } + } + traversedContext.recordReturnFrom(flowInfo.unconditionalInits()); + + if (traversedContext instanceof InsideSubRoutineFlowContext) { + ASTNode node = traversedContext.associatedNode; + if (node instanceof TryStatement) { + TryStatement tryStatement = (TryStatement) node; + flowInfo.addInitializationsFrom(tryStatement.subRoutineInits); // collect inits + if (hasValueToSave) { + if (this.saveValueVariable == null){ // closest subroutine secret variable is used + prepareSaveValueLocation(tryStatement); + } + saveValueNeeded = true; } - saveValueNeeded = true; } + } else if (traversedContext instanceof InitializationFlowContext) { + currentScope.problemReporter().cannotReturnOutsideFunction(this); + return FlowInfo.DEAD_END; } - } else if (traversedContext instanceof InitializationFlowContext) { - currentScope.problemReporter().cannotReturnOutsideFunction(this); - return FlowInfo.DEAD_END; + } while ((traversedContext = traversedContext.parent) != null); + + // resize subroutines + if ((this.subroutines != null) && (subCount != this.subroutines.length)) { + System.arraycopy(this.subroutines, 0, (this.subroutines = new SubRoutineStatement[subCount]), 0, subCount); } - } while ((traversedContext = traversedContext.parent) != null); - - // resize subroutines - if ((this.subroutines != null) && (subCount != this.subroutines.length)) { - System.arraycopy(this.subroutines, 0, (this.subroutines = new SubRoutineStatement[subCount]), 0, subCount); + + // secret local variable for return value (note that this can only occur in a real method) + if (saveValueNeeded) { + if (this.saveValueVariable != null) { + this.saveValueVariable.useFlag = LocalVariableBinding.USED; + } + } else { + this.saveValueVariable = null; + if ( this.expression != null && this.expression.resolvedType == TypeBinding.BOOLEAN) { + this.expression.bits |= ASTNode.IsReturnedValue; + } + } + return FlowInfo.DEAD_END; } - - // secret local variable for return value (note that this can only occur in a real method) - if (saveValueNeeded) { - if (this.saveValueVariable != null) { - this.saveValueVariable.useFlag = LocalVariableBinding.USED; + + public boolean needValue() { + return this.saveValueVariable != null + || ((this.bits & ASTNode.IsAnySubRoutineEscaping) == 0); + } + + public void prepareSaveValueLocation(TryStatement targetTryStatement){ + this.saveValueVariable = targetTryStatement.secretReturnValue; + } + + public StringBuffer printStatement(int tab, StringBuffer output){ + printIndent(tab, output).append("return "); //$NON-NLS-1$ + if (this.expression != null ) + this.expression.printExpression(0, output) ; + return output.append(';'); + } + + public void resolve(BlockScope scope) { + MethodScope methodScope = scope.methodScope(); + + if(methodScope==null) { + /* return statement outside of a method */ + scope.problemReporter().cannotReturnOutsideFunction(this); + return; + } + + MethodBinding methodBinding = null; + TypeBinding methodType = + (methodScope.referenceContext instanceof AbstractMethodDeclaration) + ? ((methodBinding = ((AbstractMethodDeclaration) methodScope.referenceContext).binding) == null + ? null + : methodBinding.returnType) + : TypeBinding.ANY; + TypeBinding expressionType; + if (this.expression == null) { + if (methodType != null && !methodType.isAnyType()) scope.problemReporter().shouldReturn(methodType, this); + return; } - } else { - this.saveValueVariable = null; - if ( this.expression != null && this.expression.resolvedType == TypeBinding.BOOLEAN) { - this.expression.bits |= ASTNode.IsReturnedValue; + this.expression.setExpectedType(methodType); // needed in case of generic method invocation + if ((expressionType = this.expression.resolveType(scope)) == null) return; + if (methodType == null) + return; + + if (methodType != expressionType) // must call before computeConversion() and typeMismatchError() + scope.compilationUnitScope().recordTypeConversion(methodType, expressionType); + if (this.expression.isConstantValueOfTypeAssignableToType(expressionType, methodType) + || expressionType.isCompatibleWith(methodType)) { + + return; } + if(methodBinding != null && !methodBinding.isConstructor()) + scope.problemReporter().typeMismatchError(expressionType, methodType, this.expression); } - return FlowInfo.DEAD_END; -} - -public boolean needValue() { - return this.saveValueVariable != null - || ((this.bits & ASTNode.IsAnySubRoutineEscaping) == 0); -} - -public void prepareSaveValueLocation(TryStatement targetTryStatement){ - this.saveValueVariable = targetTryStatement.secretReturnValue; -} - -public StringBuffer printStatement(int tab, StringBuffer output){ - printIndent(tab, output).append("return "); //$NON-NLS-1$ - if (this.expression != null ) - this.expression.printExpression(0, output) ; - return output.append(';'); -} - -public void resolve(BlockScope scope) { - MethodScope methodScope = scope.methodScope(); - - if(methodScope==null) { - /* return statement outside of a method */ - scope.problemReporter().cannotReturnOutsideFunction(this); - return; + + public void traverse(ASTVisitor visitor, BlockScope scope) { + if (visitor.visit(this, scope)) { + if (this.expression != null) + this.expression.traverse(visitor, scope); + } + visitor.endVisit(this, scope); } - - MethodBinding methodBinding = null; - TypeBinding methodType = - (methodScope.referenceContext instanceof AbstractMethodDeclaration) - ? ((methodBinding = ((AbstractMethodDeclaration) methodScope.referenceContext).binding) == null - ? null - : methodBinding.returnType) - : TypeBinding.ANY; - TypeBinding expressionType; - if (this.expression == null) { - if (methodType != null && !methodType.isAnyType()) scope.problemReporter().shouldReturn(methodType, this); - return; + + public int getASTType() { + return IASTNode.RETURN_STATEMENT; + + } + + public IExpression getExpression() { + return this.expression; } - this.expression.setExpectedType(methodType); // needed in case of generic method invocation - if ((expressionType = this.expression.resolveType(scope)) == null) return; - if (methodType == null) - return; - - if (methodType != expressionType) // must call before computeConversion() and typeMismatchError() - scope.compilationUnitScope().recordTypeConversion(methodType, expressionType); - if (this.expression.isConstantValueOfTypeAssignableToType(expressionType, methodType) - || expressionType.isCompatibleWith(methodType)) { - return; + /** + * @see org.eclipse.wst.jsdt.core.ast.IReturnStatement#setInferredType(org.eclipse.wst.jsdt.core.infer.InferredType) + */ + public void setInferredType(InferredType type) { + this.fInferredType = type; } - if(methodBinding != null && !methodBinding.isConstructor()) - scope.problemReporter().typeMismatchError(expressionType, methodType, this.expression); -} -public void traverse(ASTVisitor visitor, BlockScope scope) { - if (visitor.visit(this, scope)) { - if (this.expression != null) - this.expression.traverse(visitor, scope); + /** + * @see org.eclipse.wst.jsdt.core.ast.IReturnStatement#getInferredType() + */ + public InferredType getInferredType() { + return this.fInferredType; } - visitor.endVisit(this, scope); -} -public int getASTType() { - return IASTNode.RETURN_STATEMENT; -} + /** + * @see org.eclipse.wst.jsdt.core.ast.IReturnStatement#setIsType(boolean) + */ + public void setIsType(boolean isType) { + this.fIsType = isType; + } -public IExpression getExpression() { - return this.expression; -} -} + /** + * @see org.eclipse.wst.jsdt.core.ast.IReturnStatement#isType() + */ + public boolean isType() { + return this.fIsType; + } +} \ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/SingleNameReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/SingleNameReference.java index daf541a8..7d2a6b70 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/SingleNameReference.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/SingleNameReference.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -13,6 +13,7 @@ package org.eclipse.wst.jsdt.internal.compiler.ast; import org.eclipse.wst.jsdt.core.ast.IASTNode; import org.eclipse.wst.jsdt.core.ast.ISingleNameReference; import org.eclipse.wst.jsdt.core.compiler.CharOperation; +import org.eclipse.wst.jsdt.core.infer.InferEngine; import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor; import org.eclipse.wst.jsdt.internal.compiler.flow.FlowContext; import org.eclipse.wst.jsdt.internal.compiler.flow.FlowInfo; @@ -21,25 +22,18 @@ import org.eclipse.wst.jsdt.internal.compiler.lookup.Binding; import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope; import org.eclipse.wst.jsdt.internal.compiler.lookup.ClassScope; import org.eclipse.wst.jsdt.internal.compiler.lookup.FieldBinding; -import org.eclipse.wst.jsdt.internal.compiler.lookup.FunctionTypeBinding; import org.eclipse.wst.jsdt.internal.compiler.lookup.LocalVariableBinding; import org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding; import org.eclipse.wst.jsdt.internal.compiler.lookup.MethodScope; -import org.eclipse.wst.jsdt.internal.compiler.lookup.ProblemBinding; import org.eclipse.wst.jsdt.internal.compiler.lookup.ProblemFieldBinding; import org.eclipse.wst.jsdt.internal.compiler.lookup.ProblemReferenceBinding; -import org.eclipse.wst.jsdt.internal.compiler.lookup.Scope; import org.eclipse.wst.jsdt.internal.compiler.lookup.TagBits; import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding; import org.eclipse.wst.jsdt.internal.compiler.lookup.VariableBinding; public class SingleNameReference extends NameReference implements ISingleNameReference, OperatorIds { - public static final int READ = 0; - public static final int WRITE = 1; public char[] token; -// public FunctionBinding[] syntheticAccessors; // [0]=read accessor [1]=write accessor -// public TypeBinding genericCast; public SingleNameReference(char[] source, long pos) { this(source, (int) (pos >>> 32), (int) pos); @@ -62,21 +56,25 @@ public class SingleNameReference extends NameReference implements ISingleNameRef if (isCompound) { // check the variable part is initialized if blank final switch (bits & RestrictiveFlagMASK) { case Binding.FIELD : // reading a field - manageSyntheticAccessIfNecessary(currentScope, flowInfo, true /*read-access*/); break; case Binding.LOCAL : // reading a local variable // check if assigning a final blank field - LocalVariableBinding localBinding; - if (!flowInfo.isDefinitelyAssigned(localBinding = (LocalVariableBinding) binding)) { + LocalVariableBinding localBinding = null; + if (this.binding instanceof LocalVariableBinding && + !flowInfo.isDefinitelyAssigned(localBinding = (LocalVariableBinding) binding)) { + if (localBinding.declaringScope instanceof MethodScope) { currentScope.problemReporter().uninitializedLocalVariable(localBinding, this); } // we could improve error msg here telling "cannot use compound assignment on final local variable" } - if (isReachable) { - localBinding.useFlag = LocalVariableBinding.USED; - } else if (localBinding.useFlag == LocalVariableBinding.UNUSED) { - localBinding.useFlag = LocalVariableBinding.FAKE_USED; + + if(localBinding != null) { + if (isReachable) { + localBinding.useFlag = LocalVariableBinding.USED; + } else if (localBinding.useFlag == LocalVariableBinding.UNUSED) { + localBinding.useFlag = LocalVariableBinding.FAKE_USED; + } } } } @@ -85,20 +83,20 @@ public class SingleNameReference extends NameReference implements ISingleNameRef } switch (bits & RestrictiveFlagMASK) { case Binding.FIELD : // assigning to a field - manageSyntheticAccessIfNecessary(currentScope, flowInfo, false /*write-access*/); - break; case Binding.LOCAL : // assigning to a local variable - LocalVariableBinding localBinding = (LocalVariableBinding) binding; - if (!flowInfo.isDefinitelyAssigned(localBinding)){// for local variable debug attributes - bits |= FirstAssignmentToLocal; - } else { - bits &= ~FirstAssignmentToLocal; - } - if ((localBinding.tagBits & TagBits.IsArgument) != 0) { - currentScope.problemReporter().parameterAssignment(localBinding, this); + if(this.binding instanceof LocalVariableBinding) { + LocalVariableBinding localBinding = (LocalVariableBinding) binding; + if (!flowInfo.isDefinitelyAssigned(localBinding)){// for local variable debug attributes + bits |= FirstAssignmentToLocal; + } else { + bits &= ~FirstAssignmentToLocal; + } + if ((localBinding.tagBits & TagBits.IsArgument) != 0) { + currentScope.problemReporter().parameterAssignment(localBinding, this); + } + flowInfo.markAsDefinitelyAssigned(localBinding); } - flowInfo.markAsDefinitelyAssigned(localBinding); } manageEnclosingInstanceAccessIfNecessary(currentScope, flowInfo); return flowInfo; @@ -110,10 +108,6 @@ public class SingleNameReference extends NameReference implements ISingleNameRef switch (bits & RestrictiveFlagMASK) { case Binding.FIELD : // reading a field - if (valueRequired) { - manageSyntheticAccessIfNecessary(currentScope, flowInfo, true /*read-access*/); - } - break; case Binding.LOCAL : // reading a local variable case Binding.LOCAL | Binding.TYPE : @@ -170,43 +164,10 @@ public class SingleNameReference extends NameReference implements ISingleNameRef if (isFieldUseDeprecated(fieldBinding, scope, (this.bits & IsStrictlyAssigned) !=0)) scope.problemReporter().deprecatedField(fieldBinding, this); -// if ((this.bits & IsStrictlyAssigned) == 0 -// && methodScope.enclosingSourceType() == fieldBinding.original().declaringClass -// && methodScope.lastVisibleFieldID >= 0 -// && fieldBinding.id >= methodScope.lastVisibleFieldID -// && (!fieldBinding.isStatic() || methodScope.isStatic)) { -// scope.problemReporter().forwardReference(this, 0, methodScope.enclosingSourceType()); -// this.bits |= ASTNode.IgnoreNoEffectAssignCheck; -// } return fieldBinding.type; } - /** - * @see org.eclipse.wst.jsdt.internal.compiler.ast.Expression#computeConversion(org.eclipse.wst.jsdt.internal.compiler.lookup.Scope, org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding, org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding) - */ - public void computeConversion(Scope scope, TypeBinding runtimeTimeType, TypeBinding compileTimeType) { -// if (runtimeTimeType == null || compileTimeType == null) -// return; -// if ((bits & Binding.FIELD) != 0 && this.binding != null && this.binding.isValidBinding()) { -// // set the generic cast after the fact, once the type expectation is fully known (no need for strict cast) -// FieldBinding field = (FieldBinding) this.binding; -// FieldBinding originalBinding = field.original(); -// TypeBinding originalType = originalBinding.type; -// // extra cast needed if method return type is type variable -// if (originalBinding != field -// && originalType != field.type -// && runtimeTimeType.id != T_JavaLangObject -// && (originalType.tagBits & TagBits.HasTypeVariable) != 0) { -// TypeBinding targetType = (!compileTimeType.isBaseType() && runtimeTimeType.isBaseType()) -// ? compileTimeType // unboxing: checkcast before conversion -// : runtimeTimeType; -// this.genericCast = originalType.genericCast(scope.boxing(targetType)); -// } -// } -// super.computeConversion(scope, runtimeTimeType, compileTimeType); - } - /** * @see org.eclipse.wst.jsdt.internal.compiler.lookup.InvocationSite#genericTypeArguments() */ @@ -223,125 +184,47 @@ public class SingleNameReference extends NameReference implements ISingleNameRef case Binding.FIELD : // reading a field break; case Binding.LOCAL : // reading a local variable - return (LocalVariableBinding) this.binding; + if(this.binding instanceof LocalVariableBinding) { + return (LocalVariableBinding) this.binding; + } } return null; } public void manageEnclosingInstanceAccessIfNecessary(BlockScope currentScope, FlowInfo flowInfo) { - if ((flowInfo.tagBits & FlowInfo.UNREACHABLE) == 0) { - //If inlinable field, forget the access emulation, the code gen will directly target it - if (((bits & DepthMASK) == 0) || (constant != Constant.NotAConstant)) return; - - if ((bits & RestrictiveFlagMASK) == Binding.LOCAL) { - currentScope.emulateOuterAccess((LocalVariableBinding) binding); - } + //If inlinable field, forget the access emulation, the code gen will directly target it + if (((bits & DepthMASK) == 0) || (constant != Constant.NotAConstant)) { + return; + } + + if ((bits & RestrictiveFlagMASK) == Binding.LOCAL && this.binding instanceof LocalVariableBinding) { + currentScope.emulateOuterAccess((LocalVariableBinding) binding); + } } } - public void manageSyntheticAccessIfNecessary(BlockScope currentScope, FlowInfo flowInfo, boolean isReadAccess) { - -// if ((flowInfo.tagBits & FlowInfo.UNREACHABLE) != 0) return; -// -// //If inlinable field, forget the access emulation, the code gen will directly target it -// if (constant != Constant.NotAConstant) -// return; -// -// if ((bits & Binding.FIELD) != 0) { -// FieldBinding fieldBinding = (FieldBinding) binding; -// FieldBinding codegenField = fieldBinding.original(); -// this.codegenBinding = codegenField; -// if (((bits & DepthMASK) != 0) -// && (codegenField.isPrivate() // private access -// || (codegenField.isProtected() // implicit protected access -// && codegenField.declaringClass.getPackage() != currentScope.enclosingSourceType().getPackage()))) { -// if (syntheticAccessors == null) -// syntheticAccessors = new FunctionBinding[2]; -// syntheticAccessors[isReadAccess ? READ : WRITE] = -// ((SourceTypeBinding)currentScope.enclosingSourceType(). -// enclosingTypeAt((bits & DepthMASK) >> DepthSHIFT)).addSyntheticMethod(codegenField, isReadAccess); -// currentScope.problemReporter().needToEmulateFieldAccess(codegenField, this, isReadAccess); -// return; -// } -// // if the binding declaring class is not visible, need special action -// // for runtime compatibility on 1.2 VMs : change the declaring class of the binding -// // NOTE: from target 1.2 on, field's declaring class is touched if any different from receiver type -// // and not from Object or implicit static field access. -// if (fieldBinding.declaringClass != this.actualReceiverType -// && !this.actualReceiverType.isArrayType() -// && fieldBinding.declaringClass != null // array.length -// && fieldBinding.constant() == Constant.NotAConstant) { -// CompilerOptions options = currentScope.compilerOptions(); -// if ((options.targetJDK >= ClassFileConstants.JDK1_2 -// && (options.complianceLevel >= ClassFileConstants.JDK1_4 || !fieldBinding.isStatic()) -// && fieldBinding.declaringClass.id != T_JavaLangObject) // no change for Object fields -// || !fieldBinding.declaringClass.canBeSeenBy(currentScope)) { -// -// this.codegenBinding = -// currentScope.enclosingSourceType().getUpdatedFieldBinding( -// codegenField, -// (ReferenceBinding)this.actualReceiverType.erasure()); -// } -// } -// } - } -public int nullStatus(FlowInfo flowInfo) { - if (this.constant != null && this.constant != Constant.NotAConstant) { - return FlowInfo.NON_NULL; // constant expression cannot be null - } - switch (bits & RestrictiveFlagMASK) { - case Binding.FIELD : // reading a field - return FlowInfo.UNKNOWN; - case Binding.LOCAL : // reading a local variable - LocalVariableBinding local = (LocalVariableBinding) this.binding; - if (local != null) { - if (flowInfo.isDefinitelyNull(local)) - return FlowInfo.NULL; - if (flowInfo.isDefinitelyNonNull(local)) - return FlowInfo.NON_NULL; - return FlowInfo.UNKNOWN; - } - } - return FlowInfo.NON_NULL; // never get there -} - /** - * @see org.eclipse.wst.jsdt.internal.compiler.ast.Expression#postConversionType(Scope) - */ - public TypeBinding postConversionType(Scope scope) { - TypeBinding convertedType = this.resolvedType; -// if (this.genericCast != null) -// convertedType = this.genericCast; - int runtimeType = (this.implicitConversion & IMPLICIT_CONVERSION_MASK) >> 4; - switch (runtimeType) { - case T_boolean : - convertedType = TypeBinding.BOOLEAN; - break; - case T_short : - convertedType = TypeBinding.SHORT; - break; - case T_char : - convertedType = TypeBinding.CHAR; - break; - case T_int : - convertedType = TypeBinding.INT; - break; - case T_float : - convertedType = TypeBinding.FLOAT; - break; - case T_long : - convertedType = TypeBinding.LONG; - break; - case T_double : - convertedType = TypeBinding.DOUBLE; - break; - default : + public int nullStatus(FlowInfo flowInfo) { + if (this.constant != null && this.constant != Constant.NotAConstant) { + return FlowInfo.NON_NULL; // constant expression cannot be null } - if ((this.implicitConversion & BOXING) != 0) { - convertedType = scope.environment().computeBoxingType(convertedType); + switch (bits & RestrictiveFlagMASK) { + case Binding.FIELD : // reading a field + return FlowInfo.UNKNOWN; + case Binding.LOCAL : // reading a local variable + if(this.binding instanceof LocalVariableBinding) { + LocalVariableBinding local = (LocalVariableBinding) this.binding; + if (local != null) { + if (flowInfo.isDefinitelyNull(local)) + return FlowInfo.NULL; + if (flowInfo.isDefinitelyNonNull(local)) + return FlowInfo.NON_NULL; + return FlowInfo.UNKNOWN; + } + } } - return convertedType; + return FlowInfo.NON_NULL; // never get there } public StringBuffer printExpression(int indent, StringBuffer output){ @@ -367,19 +250,26 @@ public int nullStatus(FlowInfo flowInfo) { } public TypeBinding resolveType(BlockScope scope, boolean define, TypeBinding useType) { - // for code gen, harm the restrictiveFlag constant = Constant.NotAConstant; this.binding=findBinding(scope); - if (define && this.binding instanceof ProblemBinding) - { - LocalDeclaration localDeclaration = new LocalDeclaration(this.token,this.sourceEnd,this.sourceEnd); + + //if define and the found binding is not valid or is a method then declare a local variable + if (define && (!this.binding.isValidBinding() || this.binding.kind() == Binding.METHOD)) { + LocalDeclaration localDeclaration = new LocalDeclaration(this.token,this.sourceStart,this.sourceEnd); LocalVariableBinding localBinding=new LocalVariableBinding(localDeclaration,TypeBinding.UNKNOWN,0,false); scope.compilationUnitScope().addLocalVariable(localBinding); this.binding=localBinding; } -// this.codegenBinding = this.binding; + + /* if we could not find a binding try finding one for the anonymous global + * type that MAYBE associated with this single name reference */ + if(binding == null || !binding.isValidBinding()) { + char[] typeName = InferEngine.createAnonymousGlobalTypeName(this.token); + this.binding = scope.getBinding(typeName, (Binding.TYPE | bits) & RestrictiveFlagMASK, this, true); + } + if (this.binding.isValidBinding()) { switch (bits & RestrictiveFlagMASK) { case Binding.FIELD: @@ -392,32 +282,13 @@ public int nullStatus(FlowInfo flowInfo) { if (binding instanceof LocalVariableBinding) { bits &= ~RestrictiveFlagMASK; // clear bits bits |= Binding.LOCAL; -// if (!variable.isFinal() && (bits & DepthMASK) != 0) { -// scope.problemReporter().cannotReferToNonFinalOuterLocal((LocalVariableBinding)variable, this); -// } TypeBinding fieldType = variable.type; -// if (fieldType.isAnonymousType() && !fieldType.isObjectLiteralType()) { -// LocalDeclaration declaration = ((LocalVariableBinding)binding).declaration; -// if(declaration != null && !(declaration.getInitialization() instanceof AllocationExpression) && -// ! (declaration.getInitialization() instanceof Literal)) { -// bits |= Binding.TYPE; -// } -// } if (useType!=null && !(useType.id==T_null ||useType.id==T_any || useType.id==T_undefined)) { if (define) { fieldType=variable.type=useType; - if (useType.isFunctionType()) // add method binding if function - { - MethodBinding methodBinding = ((FunctionTypeBinding)useType).functionBinding.createNamedMethodBinding(this.token); - MethodScope methodScope = scope.enclosingMethodScope(); - if (methodScope!=null) - methodScope.addLocalMethod(methodBinding); - else - scope.compilationUnitScope().addLocalMethod(methodBinding); - } } else { @@ -454,11 +325,25 @@ public int nullStatus(FlowInfo flowInfo) { case Binding.TYPE : //========only type============== constant = Constant.NotAConstant; - //deprecated test - TypeBinding type = (TypeBinding)binding; - if (isTypeUseDeprecated(type, scope)) - scope.problemReporter().deprecatedType(type, this); - return this.resolvedType = type; + TypeBinding type = null; + switch (binding.kind()) { + case Binding.VARIABLE : + type = ((VariableBinding) binding).type; + break; + case Binding.METHOD : + type = ((MethodBinding) binding).returnType; + break; + case Binding.TYPE : + type = (TypeBinding) binding; + break; + } + + if(type != null) { + if (isTypeUseDeprecated(type, scope)) { + scope.problemReporter().deprecatedType(type, this); + } + return this.resolvedType = type; + } } } @@ -467,15 +352,7 @@ public int nullStatus(FlowInfo flowInfo) { } public Binding findBinding(BlockScope scope) { - if (this.actualReceiverType != null) { - Binding binding = scope.getField(this.actualReceiverType, token, this); - if(!(binding instanceof ProblemFieldBinding)) - return binding; - - } else { - this.actualReceiverType = scope.enclosingSourceType(); - } - return scope.getBinding(token, (Binding.TYPE|Binding.METHOD | bits) & RestrictiveFlagMASK, this, true /*resolve*/); + return scope.getBinding(token, (Binding.TYPE | Binding.METHOD | bits) & RestrictiveFlagMASK, this, true /*resolve*/); } public void traverse(ASTVisitor visitor, BlockScope scope) { diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/SuperReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/SuperReference.java index 2cfd9e33..a0981764 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/SuperReference.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/SuperReference.java @@ -60,7 +60,7 @@ public class SuperReference extends ThisReference implements ISuperReference { if (enclosingReceiverType.id == T_JavaLangObject) { return null; } - return this.resolvedType = enclosingReceiverType.superclass(); + return this.resolvedType = enclosingReceiverType.getSuperBinding(); } public void traverse(ASTVisitor visitor, BlockScope blockScope) { diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/SwitchStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/SwitchStatement.java index 08a79953..17eb9cb1 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/SwitchStatement.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/SwitchStatement.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2012 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -139,7 +139,6 @@ public class SwitchStatement extends Statement implements ISwitchStatement{ public void resolve(BlockScope upperScope) { try { -// boolean isEnumSwitch = false; TypeBinding expressionType = expression.resolveType(upperScope); if (statements != null) { scope = !JavaScriptCore.IS_ECMASCRIPT4 ? upperScope : new BlockScope(upperScope); @@ -204,6 +203,8 @@ public class SwitchStatement extends Statement implements ISwitchStatement{ BlockScope blockScope) { if (visitor.visit(this, blockScope)) { + if (this.scope == null) + this.scope = blockScope; expression.traverse(visitor, scope); if (statements != null) { int statementsLength = statements.length; diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ThisReference.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ThisReference.java index c15f5f99..024d1250 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ThisReference.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ThisReference.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -12,6 +12,7 @@ package org.eclipse.wst.jsdt.internal.compiler.ast; import org.eclipse.wst.jsdt.core.ast.IASTNode; import org.eclipse.wst.jsdt.core.ast.IThisReference; +import org.eclipse.wst.jsdt.core.infer.InferredType; import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor; import org.eclipse.wst.jsdt.internal.compiler.flow.FlowContext; import org.eclipse.wst.jsdt.internal.compiler.flow.FlowInfo; @@ -24,6 +25,13 @@ import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding; public class ThisReference extends Reference implements IThisReference { + /** + *

+ * {@link InferredType} referred to by "this" + *

+ */ + private InferredType fInferredType; + public static ThisReference implicitThis(){ ThisReference implicitThis = new ThisReference(0, 0); @@ -107,4 +115,19 @@ public class ThisReference extends Reference implements IThisReference { return IASTNode.THIS_REFERENCE; } + + /** + * @param type {@link InferredType} referred to by "this" + */ + public void setInferredType(InferredType type) { + this.fInferredType = type; + } + + /** + * @return {@link InferredType} referred to by "this", or + * null if none is set + */ + public InferredType getInferredType() { + return this.fInferredType; + } } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ThrowStatement.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ThrowStatement.java index 30f559ad..4b27882f 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ThrowStatement.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/ThrowStatement.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -12,6 +12,7 @@ package org.eclipse.wst.jsdt.internal.compiler.ast; import org.eclipse.wst.jsdt.core.ast.IASTNode; import org.eclipse.wst.jsdt.core.ast.IThrowStatement; +import org.eclipse.wst.jsdt.core.compiler.CharOperation; import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor; import org.eclipse.wst.jsdt.internal.compiler.flow.FlowContext; import org.eclipse.wst.jsdt.internal.compiler.flow.FlowInfo; @@ -46,7 +47,7 @@ public StringBuffer printStatement(int indent, StringBuffer output) { public void resolve(BlockScope scope) { this.exceptionType = this.exception.resolveType(scope); if (this.exceptionType == null || !this.exceptionType.isValidBinding()) { - this.exceptionType = new ProblemReferenceBinding(new char[0][0],null,0); + this.exceptionType = new ProblemReferenceBinding(CharOperation.NO_CHAR_CHAR,null,0); } } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/TypeDeclaration.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/TypeDeclaration.java index 94fd96b6..c4082918 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/TypeDeclaration.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/ast/TypeDeclaration.java @@ -140,7 +140,7 @@ public MethodDeclaration addMissingAbstractMethodFor(MethodBinding methodBinding int argumentsLength = argumentTypes.length; //the constructor MethodDeclaration methodDeclaration = new MethodDeclaration(this.compilationResult); - methodDeclaration.selector = methodBinding.selector; + methodDeclaration.setSelector(methodBinding.selector); methodDeclaration.sourceStart = this.sourceStart; methodDeclaration.sourceEnd = this.sourceEnd; methodDeclaration.modifiers = methodBinding.getAccessFlags() & ~ClassFileConstants.AccAbstract; @@ -169,30 +169,16 @@ public MethodDeclaration addMissingAbstractMethodFor(MethodBinding methodBinding } //============BINDING UPDATE========================== - methodDeclaration.binding = new MethodBinding( - methodDeclaration.modifiers, //methodDeclaration - methodBinding.selector, - methodBinding.returnType, - argumentsLength == 0 ? Binding.NO_PARAMETERS : argumentTypes, //arguments bindings - this.binding); //declaringClass - - methodDeclaration.scope = new MethodScope(this.scope, methodDeclaration, true); - methodDeclaration.bindArguments(); - -/* if (binding.methods == null) { - binding.methods = new FunctionBinding[] { methodDeclaration.binding }; - } else { - FunctionBinding[] newMethods; - System.arraycopy( - binding.methods, - 0, - newMethods = new FunctionBinding[binding.methods.length + 1], - 1, - binding.methods.length); - newMethods[0] = methodDeclaration.binding; - binding.methods = newMethods; - }*/ - //=================================================== + if(!methodDeclaration.hasBinding()) { + methodDeclaration.setBinding(new MethodBinding( + methodDeclaration.modifiers, //methodDeclaration + methodBinding.selector, + methodBinding.returnType, + argumentsLength == 0 ? Binding.NO_PARAMETERS : argumentTypes, //arguments bindings + this.binding)); //declaringClass + } + + methodDeclaration.setScope(new MethodScope(this.scope, methodDeclaration, true)); return methodDeclaration; } @@ -280,7 +266,7 @@ public boolean checkConstructors(Parser parser) { for (int i = this.methods.length; --i >= 0;) { AbstractMethodDeclaration am; if ((am = this.methods[i]).isConstructor()) { - if (!CharOperation.equals(am.selector, this.name)) { + if (!CharOperation.equals(am.getName(), this.name)) { // the constructor was in fact a method with no return type // unless an explicit constructor call was supplied ConstructorDeclaration c = (ConstructorDeclaration) am; @@ -310,7 +296,7 @@ public ConstructorDeclaration createDefaultConstructor( boolean needExplicitCons //the constructor ConstructorDeclaration constructor = new ConstructorDeclaration(this.compilationResult); constructor.bits |= ASTNode.IsDefaultConstructor; - constructor.selector = this.name; + constructor.setSelector(this.name); constructor.modifiers = this.modifiers & ExtraCompilerModifiers.AccVisibilityMASK; //if you change this setting, please update the @@ -354,7 +340,7 @@ public MethodBinding createDefaultConstructorWithBinding(MethodBinding inherited int argumentsLength = argumentTypes.length; //the constructor ConstructorDeclaration constructor = new ConstructorDeclaration(this.compilationResult); - constructor.selector = new char[] { 'x' }; //no maining + constructor.setSelector(new char[] { 'x' }); //no maining constructor.sourceStart = this.sourceStart; constructor.sourceEnd = this.sourceEnd; int newModifiers = this.modifiers & ExtraCompilerModifiers.AccVisibilityMASK; @@ -395,27 +381,28 @@ public MethodBinding createDefaultConstructorWithBinding(MethodBinding inherited //============BINDING UPDATE========================== SourceTypeBinding sourceType = this.binding; - constructor.binding = new MethodBinding( - constructor.modifiers, //methodDeclaration - argumentsLength == 0 ? Binding.NO_PARAMETERS : argumentTypes, //arguments bindings - sourceType); //declaringClass + if(!constructor.hasBinding()) { + constructor.setBinding(new MethodBinding( + constructor.modifiers, //methodDeclaration + argumentsLength == 0 ? Binding.NO_PARAMETERS : argumentTypes, //arguments bindings + sourceType)); //declaringClass + } - constructor.binding.modifiers |= ExtraCompilerModifiers.AccIsDefaultConstructor; + constructor.getBinding().modifiers |= ExtraCompilerModifiers.AccIsDefaultConstructor; - constructor.scope = new MethodScope(this.scope, constructor, true); - constructor.bindArguments(); - constructor.constructorCall.resolve(constructor.scope); + constructor.setScope(new MethodScope(this.scope, constructor, true)); + constructor.constructorCall.resolve(constructor.getScope()); MethodBinding[] methodBindings = sourceType.methods(); // trigger sorting int length; System.arraycopy(methodBindings, 0, methodBindings = new MethodBinding[(length = methodBindings.length) + 1], 1, length); - methodBindings[0] = constructor.binding; + methodBindings[0] = constructor.getBinding(); if (++length > 1) ReferenceBinding.sortMethods(methodBindings, 0, length); // need to resort, since could be valid methods ahead (140643) - DOM needs eager sorting sourceType.setMethods(methodBindings); //=================================================== - return constructor.binding; + return constructor.getBinding(); } /** @@ -454,7 +441,7 @@ public AbstractMethodDeclaration declarationOf(MethodBinding methodBinding) { for (int i = 0, max = this.methods.length; i < max; i++) { AbstractMethodDeclaration methodDecl; - if ((methodDecl = this.methods[i]).binding == methodBinding) + if ((methodDecl = this.methods[i]).getBinding() == methodBinding) return methodDecl; } } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/batch/ClasspathFile.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/batch/ClasspathFile.java index e1080b4f..807609aa 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/batch/ClasspathFile.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/batch/ClasspathFile.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -93,7 +93,7 @@ private void parseFile(ITypeRequestor requestor) { for (int i = 0; i < declaration.statements.length; i++) { if (declaration.statements[i] instanceof AbstractMethodDeclaration) { AbstractMethodDeclaration method = (AbstractMethodDeclaration) declaration.statements[i]; - definedItems[Binding.METHOD].put(method.selector, foundAnswer); + definedItems[Binding.METHOD].put(method.getName(), foundAnswer); } else if (declaration.statements[i] instanceof AbstractVariableDeclaration) { AbstractVariableDeclaration var = (AbstractVariableDeclaration) declaration.statements[i]; @@ -103,7 +103,7 @@ private void parseFile(ITypeRequestor requestor) { } for (int inx=0;inx>> 32) : return "super"; //$NON-NLS-1$ case (int) (UninitializedLocalVariable >>> 32) : - return "uninitializedLocalVariable"; + return "uninitializedLocalVariable"; //$NON-NLS-1$ case (int) (UninitializedGlobalVariable >>> 32) : - return "uninitializedGlobalVariable"; + return "uninitializedGlobalVariable"; //$NON-NLS-1$ } } return null; @@ -1246,7 +1246,6 @@ public class CompilerOptions { // keep in sync with warningTokenToIrritant and warningTokenFromIrritant public final static String[] warningTokens = { "all", //$NON-NLS-1$ - "boxing", //$NON-NLS-1$ "cast", //$NON-NLS-1$ "deprecation", //$NON-NLS-1$ "fallthrough", //$NON-NLS-1$ @@ -1261,6 +1260,8 @@ public class CompilerOptions { "unchecked", //$NON-NLS-1$ "unqualified-field-access", //$NON-NLS-1$ "unused", //$NON-NLS-1$ + "uninitializedLocalVariable", //$NON-NLS-1$ + "uninitializedGlobalVariable" //$NON-NLS-1$ }; public static long warningTokenToIrritant(String warningToken) { // keep in sync with warningTokens and warningTokenFromIrritant diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/IntConstant.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/IntConstant.java index 9ded4b45..c7bf90e6 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/IntConstant.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/impl/IntConstant.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ArrayBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ArrayBinding.java index da4eed25..21276837 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ArrayBinding.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ArrayBinding.java @@ -193,9 +193,9 @@ public char[] sourceName() { } return CharOperation.concat(leafComponentType.sourceName(), brackets); } -public ReferenceBinding superclass() { +public ReferenceBinding getSuperBinding() { if(referenceBinding != null) - return referenceBinding.superclass(); + return referenceBinding.getSuperBinding(); return null; } public void swapUnresolved(UnresolvedReferenceBinding unresolvedType, ReferenceBinding resolvedType, LookupEnvironment env) { diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/BinaryTypeBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/BinaryTypeBinding.java index 9b38f5ce..1b2eb938 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/BinaryTypeBinding.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/BinaryTypeBinding.java @@ -565,7 +565,7 @@ public MethodBinding getExactMethod(char[] selector, TypeBinding[] argumentTypes } } if (foundNothing) { - if (superclass() != null) { // ensure superclass is resolved before checking + if (getSuperBinding() != null) { // ensure superclass is resolved before checking if (refScope != null) refScope.recordTypeReference(superclass); return superclass.getExactMethod(selector, argumentTypes, refScope); @@ -704,7 +704,7 @@ MethodBinding resolveTypesFor(MethodBinding method) { * * NOTE: superclass of a binary type is resolved when needed */ -public ReferenceBinding superclass() { +public ReferenceBinding getSuperBinding() { if ((this.tagBits & TagBits.HasUnresolvedSuperclass) == 0) return this.superclass; diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/BlockScope.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/BlockScope.java index 9d41c6f4..cb3576e3 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/BlockScope.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/BlockScope.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -16,7 +16,6 @@ import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode; import org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.wst.jsdt.internal.compiler.ast.Argument; import org.eclipse.wst.jsdt.internal.compiler.ast.CaseStatement; -import org.eclipse.wst.jsdt.internal.compiler.ast.FunctionExpression; import org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration; import org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants; @@ -42,11 +41,6 @@ public class BlockScope extends Scope { // record the current case statement being processed (for entire switch case block). public CaseStatement enclosingCase; // from 1.4 on, local types should not be accessed across switch case blocks (52221) - public final static VariableBinding[] EmulationPathToImplicitThis = {}; - public final static VariableBinding[] NoEnclosingInstanceInConstructorCall = {}; - - public final static VariableBinding[] NoEnclosingInstanceInStaticContext = {}; - public BlockScope(BlockScope parent) { this(parent, true); } @@ -94,7 +88,6 @@ public final void addLocalType(TypeDeclaration localType) { * and checking there are not too many locals or arguments allocated. */ public void addLocalVariable(LocalVariableBinding binding) { - checkAndSetModifiersForVariable(binding); // insert local in scope if (this.localIndex == this.locals.length) System.arraycopy( @@ -108,32 +101,30 @@ public void addLocalVariable(LocalVariableBinding binding) { // update local variable binding binding.declaringScope = this; + // share the outermost method scope analysisIndex MethodScope outerMostMethodScope = this.outerMostMethodScope(); binding.id = (outerMostMethodScope!=null)? outerMostMethodScope.analysisIndex++ : this.compilationUnitScope().analysisIndex++; - // share the outermost method scope analysisIndex - - // added second checked for inferredType to fix - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=268991 - if ((binding.declaration!=null && binding.declaration.initialization instanceof FunctionExpression) || - (binding.declaration.inferredType != null && binding.declaration.inferredType.isFunction())) { - - MethodBinding methodBinding= - new MethodBinding(0, binding.name, TypeBinding.UNKNOWN, null,this.enclosingTypeBinding()); - methodBinding.createFunctionTypeBinding(this); - addLocalMethod(methodBinding); - - } } public void addLocalMethod(MethodBinding methodBinding) { - if (this.numberMethods == this.methods.length) - System.arraycopy( - this.methods, - 0, - (this.methods = new MethodBinding[this.numberMethods * 2]), - 0, - this.numberMethods); - this.methods[this.numberMethods++] = methodBinding; + /* prevent duplicate bindings + * NOTE: this has no noticeable affect on performance */ + boolean isDuplicate = false; + for(int i = 0; i < this.numberMethods && !isDuplicate; ++i) { + isDuplicate = methodBinding == this.methods[i]; + } + + if(!isDuplicate) { + if (this.numberMethods == this.methods.length) { + System.arraycopy( + this.methods, + 0, + (this.methods = new MethodBinding[this.numberMethods * 2]), + 0, + this.numberMethods); + } + this.methods[this.numberMethods++] = methodBinding; + } } @@ -176,13 +167,6 @@ String basicToString(int tab) { return s; } -private void checkAndSetModifiersForVariable(LocalVariableBinding varBinding) { - int modifiers = varBinding.modifiers; - int realModifiers = modifiers & ExtraCompilerModifiers.AccJustFlag; - - varBinding.modifiers = modifiers; -} - public void reportUnusedDeclarations() { if (this.locals!=null) @@ -269,8 +253,9 @@ public MethodBinding findMethod(char[] methodName,TypeBinding[]argumentTypes, bo for (int i = this.numberMethods-1; i >= 0; i--) { MethodBinding method; char[] name; - if ((name = (method = this.methods[i]).selector).length == methodLength && CharOperation.equals(name, methodName)) + if ((name = (method = this.methods[i]).selector) != null && name.length == methodLength && CharOperation.equals(name, methodName)) { return method; + } } if (checkVars) { @@ -654,87 +639,6 @@ public VariableBinding[] getEmulationPath(LocalVariableBinding outerLocalVariabl return null; } -/* - * This retrieves the argument that maps to an enclosing instance of the suitable type, - * if not found then answers nil -- do not create one - * - * #implicitThis : the implicit this will be ok - * #((arg) this$n) : available as a constructor arg - * #((arg) this$n access$m... access$p) : available as as a constructor arg + a sequence of synthetic accessors to synthetic fields - * #((fieldDescr) this$n access#m... access$p) : available as a first synthetic field + a sequence of synthetic accessors to synthetic fields - * null : not found - * jls 15.9.2 + http://www.ergnosis.com/java-spec-report/java-language/jls-8.8.5.1-d.html - */ -public Object[] getEmulationPath(ReferenceBinding targetEnclosingType, boolean onlyExactMatch, boolean denyEnclosingArgInConstructorCall) { - MethodScope currentMethodScope = this.methodScope(); - SourceTypeBinding sourceType = currentMethodScope.enclosingSourceType(); - - // use 'this' if possible - if (!currentMethodScope.isStatic && !currentMethodScope.isConstructorCall) { - if (sourceType == targetEnclosingType || (!onlyExactMatch && sourceType.findSuperTypeWithSameErasure(targetEnclosingType) != null)) { - return BlockScope.EmulationPathToImplicitThis; // implicit this is good enough - } - } - if (!sourceType.isNestedType() || sourceType.isStatic()) { // no emulation from within non-inner types - if (currentMethodScope.isConstructorCall) { - return BlockScope.NoEnclosingInstanceInConstructorCall; - } else if (currentMethodScope.isStatic){ - return BlockScope.NoEnclosingInstanceInStaticContext; - } - return null; - } - boolean insideConstructor = currentMethodScope.isInsideInitializerOrConstructor(); - - // use a direct synthetic field then - if (currentMethodScope.isStatic) { - return BlockScope.NoEnclosingInstanceInStaticContext; - } - if (sourceType.isAnonymousType()) { - ReferenceBinding enclosingType = sourceType.enclosingType(); - if (enclosingType.isNestedType()) { - NestedTypeBinding nestedEnclosingType = (NestedTypeBinding) enclosingType; - } - } - - // could be reached through a sequence of enclosing instance link (nested members) - Object[] path = new Object[2]; // probably at least 2 of them - ReferenceBinding currentType = sourceType.enclosingType(); - if (insideConstructor) { - } else { - if (currentMethodScope.isConstructorCall){ - return BlockScope.NoEnclosingInstanceInConstructorCall; - } - } - if (path[0] != null) { // keep accumulating - - int count = 1; - ReferenceBinding currentEnclosingType; - while ((currentEnclosingType = currentType.enclosingType()) != null) { - - //done? - if (currentType == targetEnclosingType - || (!onlyExactMatch && currentType.findSuperTypeWithSameErasure(targetEnclosingType) != null)) break; - - if (currentMethodScope != null) { - currentMethodScope = currentMethodScope.enclosingMethodScope(); - if (currentMethodScope != null && currentMethodScope.isConstructorCall){ - return BlockScope.NoEnclosingInstanceInConstructorCall; - } - if (currentMethodScope != null && currentMethodScope.isStatic){ - return BlockScope.NoEnclosingInstanceInStaticContext; - } - } - - break; - } - if (currentType == targetEnclosingType - || (!onlyExactMatch && currentType.findSuperTypeWithSameErasure(targetEnclosingType) != null)) { - return path; - } - } - return null; -} - /* Answer true if the variable name already exists within the receiver's scope. */ public final boolean isDuplicateLocalVariable(char[] name) { diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ClassScope.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ClassScope.java index abefc6d9..44ef5a75 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ClassScope.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ClassScope.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -10,11 +10,7 @@ *******************************************************************************/ package org.eclipse.wst.jsdt.internal.compiler.lookup; -import java.util.ArrayList; - import org.eclipse.wst.jsdt.core.compiler.CharOperation; -import org.eclipse.wst.jsdt.core.infer.InferredAttribute; -import org.eclipse.wst.jsdt.core.infer.InferredMethod; import org.eclipse.wst.jsdt.core.infer.InferredType; import org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.wst.jsdt.internal.compiler.ast.AbstractVariableDeclaration; @@ -47,12 +43,11 @@ public class ClassScope extends Scope { LocalTypeBinding anonymousType = buildLocalType(enclosingType, enclosingType.fPackage); SourceTypeBinding sourceType = getReferenceBinding(); - sourceType.superclass = supertype; + sourceType.setSuperBinding(supertype); connectMemberTypes(); buildFieldsAndMethods(); anonymousType.faultInTypesForFieldsAndMethods(); - sourceType.verifyMethods(environment().methodVerifier()); } private void buildFields() { @@ -198,8 +193,6 @@ public class ClassScope extends Scope { connectTypeHierarchy(); buildFieldsAndMethods(); localType.faultInTypesForFieldsAndMethods(); - - getReferenceBinding().verifyMethods(environment().methodVerifier()); } private void buildMemberTypes(AccessRestriction accessRestriction) { @@ -257,15 +250,12 @@ public class ClassScope extends Scope { MethodBinding[] methodBindings = new MethodBinding[(clinitIndex == -1 ? size : size - 1) + count]; // create special methods for enums SourceTypeBinding sourceType = getReferenceBinding(); -// if (isEnum) { -// methodBindings[0] = sourceType.addSyntheticEnumMethod(TypeConstants.VALUES); // add [] values() -// methodBindings[1] = sourceType.addSyntheticEnumMethod(TypeConstants.VALUEOF); // add valueOf() -// } + // create bindings for source methods for (int i = 0; i < size; i++) { if (i != clinitIndex) { MethodScope scope = new MethodScope(this, methods[i], false); - MethodBinding methodBinding = scope.createMethod(methods[i],methods[i].selector,sourceType,false,false); + MethodBinding methodBinding = scope.createMethod(methods[i],methods[i].getName(),sourceType,false,false); if (methodBinding != null) // is null if binding could not be created methodBindings[count++] = methodBinding; } @@ -289,7 +279,7 @@ public class ClassScope extends Scope { } else { char[][] className = CharOperation.deepCopy(enclosingType.compoundName); className[className.length - 1] = - CharOperation.concat(className[className.length - 1], referenceContext.name, '$'); + CharOperation.concat(className[className.length - 1], referenceContext.name, '.'); ReferenceBinding existingType = packageBinding.getType0(className[className.length - 1]); referenceContext.binding = new MemberTypeBinding(className, this, enclosingType); } @@ -336,7 +326,7 @@ public class ClassScope extends Scope { modifiers |= ExtraCompilerModifiers.AccDeprecatedImplicitly; } } else { - MethodBinding method = ((AbstractMethodDeclaration) methodScope.referenceContext).binding; + MethodBinding method = ((AbstractMethodDeclaration) methodScope.referenceContext).getBinding(); if (method != null) { if (method.isStrictfp()) modifiers |= ClassFileConstants.AccStrictfp; @@ -430,13 +420,13 @@ public class ClassScope extends Scope { if (currentType.hasMemberTypes()) // avoid resolving member types eagerly return; /* BC- Added cycle check BUG 200501 */ - } while (currentType.superclass()!=currentType && (currentType = currentType.superclass()) != null && (currentType.tagBits & TagBits.HasNoMemberTypes) == 0); + } while (currentType.getSuperBinding()!=currentType && (currentType = currentType.getSuperBinding()) != null && (currentType.tagBits & TagBits.HasNoMemberTypes) == 0); // tag the sourceType and all of its superclasses, unless they have already been tagged currentType = sourceType; do { currentType.tagBits |= TagBits.HasNoMemberTypes; - } while ((currentType = currentType.superclass()) != null && (currentType.tagBits & TagBits.HasNoMemberTypes) == 0); + } while ((currentType = currentType.getSuperBinding()) != null && (currentType.tagBits & TagBits.HasNoMemberTypes) == 0); } private void connectMemberTypes() { @@ -461,12 +451,12 @@ public class ClassScope extends Scope { private boolean connectSuperclass() { SourceTypeBinding sourceType = getReferenceBinding(); if (sourceType.id == T_JavaLangObject) { // handle the case of redefining java.lang.Object up front - sourceType.superclass = null; + sourceType.setSuperBinding(null); return true; // do not propagate Object's hierarchy problems down to every subtype } - if ( (referenceContext!=null && referenceContext.superclass == null) || (inferredType!=null && inferredType.superClass==null)) { - sourceType.superclass = getJavaLangObject(); - return !detectHierarchyCycle(sourceType, sourceType.superclass, null); + if ( (referenceContext!=null && referenceContext.superclass == null) || (inferredType!=null && inferredType.getSuperType()==null)) { + sourceType.setSuperBinding(getJavaLangObject()); + return !detectHierarchyCycle(sourceType, sourceType.getSuperBinding0(), null); } if (referenceContext!=null) { @@ -474,7 +464,7 @@ public class ClassScope extends Scope { ReferenceBinding superclass = findSupertype(superclassRef); if (superclass != null) { // is null if a cycle was detected cycle or a problem // only want to reach here when no errors are reported - sourceType.superclass = superclass; + sourceType.setSuperBinding(superclass); return true; } } @@ -483,16 +473,16 @@ public class ClassScope extends Scope { ReferenceBinding superclass = findInferredSupertype(inferredType); if (superclass != null) { // is null if a cycle was detected cycle or a problem // only want to reach here when no errors are reported - sourceType.superclass = superclass; + sourceType.setSuperBinding(superclass); if (superclass.isValidBinding()) return true; } } sourceType.tagBits |= TagBits.HierarchyHasProblems; - sourceType.superclass = getJavaLangObject(); - if ((sourceType.superclass.tagBits & TagBits.BeginHierarchyCheck) == 0) - detectHierarchyCycle(sourceType, sourceType.superclass, null); + sourceType.setSuperBinding(getJavaLangObject()); + if ((sourceType.getSuperBinding0().tagBits & TagBits.BeginHierarchyCheck) == 0) + detectHierarchyCycle(sourceType, sourceType.getSuperBinding0(), null); return false; // reported some error against the source type } @@ -515,7 +505,7 @@ public class ClassScope extends Scope { int length = this.inferredType.mixins.size(); nextExtends : for (int i = 0; i < length; i++) { char []mixinsName=(char [])this.inferredType.mixins.get(i); - ReferenceBinding mixinBinding = (ReferenceBinding)this.getType(mixinsName); + TypeBinding mixinBinding = this.getType(mixinsName); if (mixinBinding == null) { // detected cycle sourceType.tagBits |= TagBits.HierarchyHasProblems; noProblems = false; @@ -523,69 +513,24 @@ public class ClassScope extends Scope { } //loop through the nextTypes of the mixinBinding because each contains a partial inferred type - while(mixinBinding != null) { - // get the partial inferred type - InferredType mixinInferredType = mixinBinding.getInferredType(); - if(mixinInferredType !=null) { - InferredAttribute[] attributes = mixinInferredType.attributes; - ArrayList methods = mixinInferredType.methods; - if(methods == null) - methods = new ArrayList(1); - - // get the full list of methods and attributes from the mix class and its super class - InferredType mixSuperType = mixinInferredType.superClass; - while(mixSuperType != null && !CharOperation.equals(mixSuperType.getName(), "Object".toCharArray())) { //$NON-NLS-1$ - // attributes - InferredAttribute[] tempAttributes = new InferredAttribute[attributes.length + mixSuperType.attributes.length]; - System.arraycopy(attributes, 0, tempAttributes, 0, attributes.length); - System.arraycopy(mixSuperType.attributes, 0, tempAttributes, attributes.length - 1, mixSuperType.attributes.length); - attributes = tempAttributes; + if(mixinBinding instanceof SourceTypeBinding) { + ((SourceTypeBinding) mixinBinding).performActionOnLinkedBindings(new SourceTypeBinding.LinkedBindingAction() { + /** + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding.LinkedTypeAction#performAction(org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding) + */ + public boolean performAction(SourceTypeBinding linkedBinding) { + // get the partial inferred type + InferredType mixin = linkedBinding.getInferredType(); + ClassScope.this.inferredType.mixin(mixin); - // methods - if (mixSuperType.methods != null) - methods.addAll(mixSuperType.methods); - mixSuperType = mixSuperType.superClass; - } - - // add attributes to the type - for(int a = 0; a < attributes.length; a++) { - if(attributes[a] != null) { - InferredAttribute attr = this.inferredType.findAttribute( attributes[a].name ); - if(attr == null || attr.type == null) { - attr = this.inferredType.addAttribute( attributes[a].name, attributes[a].node , attributes[a].nameStart); - attr.type=attributes[a].type; - attr.isStatic = false; - attr.nameStart = attributes[a].nameStart; - } - } - } - - // add methods to the type - for(int m = 0; m < methods.size(); m++) { - if(!((InferredMethod)methods.get(m)).isConstructor) { - InferredMethod method = this.inferredType.findMethod(((InferredMethod)methods.get(m)).name, null); - - //ignore if the attribute exists and has a type - if(method == null) { - method = this.inferredType.addMethod(((InferredMethod)methods.get(m)).name, ((InferredMethod)methods.get(m)).getFunctionDeclaration(),((InferredMethod)methods.get(m)).nameStart); - method.isStatic=false; - } - } + // mixin all linked types + return true; } - } - - //get the next partial source type for this 'mixin' - if(mixinBinding instanceof SourceTypeBinding) { - mixinBinding = ((SourceTypeBinding)mixinBinding).nextType; - } else { - mixinBinding = null; - } + }); } } return noProblems; } - - void connectTypeHierarchy() { @@ -681,7 +626,7 @@ public class ClassScope extends Scope { // - a binary type... this case MUST be caught & reported here // - another source type... this case is reported against the other source type boolean hasCycle = false; - ReferenceBinding parentType = superType.superclass(); + ReferenceBinding parentType = superType.getSuperBinding(); if (parentType != null) { if (sourceType == parentType) { problemReporter().hierarchyCircularity(sourceType, superType, reference); @@ -721,7 +666,7 @@ public class ClassScope extends Scope { private ReferenceBinding findInferredSupertype(InferredType type) { try { // typeReference.aboutToResolve(this); // allows us to trap completion & selection nodes - compilationUnitScope().recordQualifiedReference(new char[][]{type.superClass.getName()}); + compilationUnitScope().recordQualifiedReference(new char[][]{type.getSuperType().getName()}); // this.superTypeReference = typeReference; ReferenceBinding superType = type.resolveSuperType(this); this.superTypeReference = null; @@ -791,7 +736,7 @@ public class ClassScope extends Scope { inferredType.binding = new SourceTypeBinding(className, packageBinding, this); //@GINO: Anonymous set bits - if( inferredType.isAnonymous ) + if( !inferredType.isNamed() ) inferredType.binding.tagBits |= TagBits.AnonymousTypeMask; if( inferredType.isObjectLiteral ) inferredType.binding.tagBits |= TagBits.IsObjectLiteralType; diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/CombinedSourceTypeBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/CombinedSourceTypeBinding.java index 93a7544d..fa9d0480 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/CombinedSourceTypeBinding.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/CombinedSourceTypeBinding.java @@ -139,7 +139,7 @@ public class CombinedSourceTypeBinding extends SourceTypeBinding { } - public boolean contains(ReferenceBinding binding) + public boolean isLinkedType(ReferenceBinding binding) { for (int i = 0; i < this.sourceTypes.length ; i++) if (this.sourceTypes[i]==binding) @@ -158,22 +158,22 @@ public class CombinedSourceTypeBinding extends SourceTypeBinding { private void setSuperclass(SourceTypeBinding from) { - if (this.superclass==null || (from.superclass!=null && from.superclass.id!=TypeIds.T_JavaLangObject)) - this.superclass=from.superclass; + if (this.getSuperBinding0()==null || (from.getSuperBinding0()!=null && from.getSuperBinding0().id!=TypeIds.T_JavaLangObject)) + this.setSuperBinding(from.getSuperBinding0()); } - public ReferenceBinding superclass() { + public ReferenceBinding getSuperBinding() { ReferenceBinding supercls = null; for (int i = 0; i < this.sourceTypes.length ; i++) { - supercls = this.sourceTypes[i].superclass; + supercls = this.sourceTypes[i].getSuperBinding0(); if (supercls!=null && supercls.id!=TypeIds.T_JavaLangObject) return supercls; } - if (supercls!=null && this.superclass==null) + if (supercls!=null && this.getSuperBinding0()==null) return supercls; - return this.superclass; + return this.getSuperBinding0(); } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/CompilationUnitBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/CompilationUnitBinding.java index 48fdbab7..9ec7984b 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/CompilationUnitBinding.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/CompilationUnitBinding.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2009 IBM Corporation and others. + * Copyright (c) 2005, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -51,7 +51,7 @@ public class CompilationUnitBinding extends SourceTypeBinding { setShortName(this.fileName); this.path=path; /* bc - allows super type of 'Window' (and other types) for a compilation unit */ - this.superclass = superType; + this.setSuperBinding(superType); } @@ -82,11 +82,11 @@ public class CompilationUnitBinding extends SourceTypeBinding { public AbstractMethodDeclaration sourceMethod(MethodBinding binding) { ProgramElement[] statements = compilationUnitScope.referenceContext.statements; for (int i = 0; i < statements.length; i++) { - if (statements[i] instanceof AbstractMethodDeclaration && ((AbstractMethodDeclaration)statements[i]).binding==binding) + if (statements[i] instanceof AbstractMethodDeclaration && ((AbstractMethodDeclaration)statements[i]).getBinding()==binding) return (AbstractMethodDeclaration)statements[i]; else if (statements[i] instanceof Assignment && (((Assignment)statements[i]).expression instanceof FunctionExpression)) { FunctionExpression functionExpression = (FunctionExpression) ((Assignment)statements[i]).expression; - if (functionExpression.methodDeclaration !=null && functionExpression.methodDeclaration.binding==binding) + if (functionExpression.methodDeclaration !=null && functionExpression.methodDeclaration.getBinding()==binding) return functionExpression.methodDeclaration; } } @@ -99,7 +99,7 @@ public class CompilationUnitBinding extends SourceTypeBinding { {this.binding=binding;} public boolean visit(MethodDeclaration methodDeclaration, Scope scope) { - if (methodDeclaration.binding==this.binding) + if (methodDeclaration.getBinding()==this.binding) { method=methodDeclaration; return false; diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/CompilationUnitScope.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/CompilationUnitScope.java index 9a3864dc..1784e00a 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/CompilationUnitScope.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/CompilationUnitScope.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -12,21 +12,27 @@ package org.eclipse.wst.jsdt.internal.compiler.lookup; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashSet; +import java.util.List; import org.eclipse.wst.jsdt.core.LibrarySuperType; import org.eclipse.wst.jsdt.core.compiler.CharOperation; import org.eclipse.wst.jsdt.core.compiler.libraries.SystemLibraryLocation; +import org.eclipse.wst.jsdt.core.infer.InferEngine; import org.eclipse.wst.jsdt.core.infer.InferredType; import org.eclipse.wst.jsdt.core.infer.InferrenceManager; import org.eclipse.wst.jsdt.core.infer.InferrenceProvider; +import org.eclipse.wst.jsdt.internal.codeassist.ISearchRequestor; import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor; import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode; +import org.eclipse.wst.jsdt.internal.compiler.ast.Assignment; import org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.wst.jsdt.internal.compiler.ast.FunctionExpression; import org.eclipse.wst.jsdt.internal.compiler.ast.ImportReference; import org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration; import org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration; +import org.eclipse.wst.jsdt.internal.compiler.ast.SingleNameReference; import org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants; import org.eclipse.wst.jsdt.internal.compiler.env.AccessRestriction; import org.eclipse.wst.jsdt.internal.compiler.problem.ProblemReporter; @@ -36,1143 +42,1377 @@ import org.eclipse.wst.jsdt.internal.compiler.util.HashtableOfType; import org.eclipse.wst.jsdt.internal.compiler.util.ObjectVector; import org.eclipse.wst.jsdt.internal.compiler.util.SimpleNameVector; import org.eclipse.wst.jsdt.internal.compiler.util.SimpleSetOfCharArray; +import org.eclipse.wst.jsdt.internal.core.SearchableEnvironment; +import org.eclipse.wst.jsdt.internal.core.search.indexing.IIndexConstants; +import org.eclipse.wst.jsdt.internal.core.util.QualificationHelpers; import org.eclipse.wst.jsdt.internal.core.util.Util; - - public class CompilationUnitScope extends BlockScope { -public LookupEnvironment environment; -public CompilationUnitDeclaration referenceContext; -public char[][] currentPackageName; -public PackageBinding fPackage; -public ImportBinding[] imports; -public HashtableOfObject typeOrPackageCache; // used in Scope.getTypeOrPackage() - -public SourceTypeBinding[] topLevelTypes; + public LookupEnvironment environment; + public CompilationUnitDeclaration referenceContext; + public char[][] currentPackageName; + public PackageBinding fPackage; + public ImportBinding[] imports; + public HashtableOfObject typeOrPackageCache; // used in Scope.getTypeOrPackage() -private CompoundNameVector qualifiedReferences; -private SimpleNameVector simpleNameReferences; -private ObjectVector referencedTypes; -private ObjectVector referencedSuperTypes; + public SourceTypeBinding[] topLevelTypes; + public SourceTypeBinding[] existingTopLevelTypes; -HashtableOfType constantPoolNameUsage; -public int analysisIndex; -private int captureID = 1; + private CompoundNameVector qualifiedReferences; + private SimpleNameVector simpleNameReferences; + private ObjectVector referencedTypes; + private ObjectVector referencedSuperTypes; -/* Allows a compilation unit to inherit fields from a superType */ -public ReferenceBinding superBinding; -private MethodScope methodScope; -private ClassScope classScope; + HashtableOfType constantPoolNameUsage; + public int analysisIndex; + private int captureID = 1; -public int temporaryAnalysisIndex; + /* Allows a compilation unit to inherit fields from a superType */ + public ReferenceBinding superBinding; + + /** + *

+ * true if the {@link #superBinding} is currently being + * built, false otherwise. + *

+ * + * @see #buildSuperType() + * @see #fBuidingSuperBindingLock + */ + private volatile boolean fBuildingSuperBinding; + + /** + *

+ * Lock that should be used when using the {@link #fBuildingSuperBinding} + * property. + *

+ */ + private final Object fBuidingSuperBindingLock = new Object(); + + /** + * boolean flag to determine if we need to build the + * Global Super Type for this scope. + */ + private boolean shouldBuildGlobalSuperType = false; + + private ClassScope classScope; + public int temporaryAnalysisIndex; -public HashSet externalCompilationUnits=new HashSet(); + public HashSet externalCompilationUnits = new HashSet(); -public static final char FILENAME_DOT_SUBSTITUTION='#'; + public static final char FILENAME_DOT_SUBSTITUTION = '#'; + class DeclarationVisitor extends ASTVisitor { + ArrayList methods = new ArrayList(); -class DeclarationVisitor extends ASTVisitor -{ - ArrayList methods=new ArrayList(); - public boolean visit(LocalDeclaration localDeclaration, BlockScope scope) { - if(localDeclaration.initialization instanceof FunctionExpression) { - this.visit(((FunctionExpression)localDeclaration.initialization).getMethodDeclaration(), scope); - } else { - TypeBinding type=localDeclaration.resolveVarType(scope); - LocalVariableBinding binding = new LocalVariableBinding(localDeclaration, type, 0, false); - localDeclaration.binding=binding; - addLocalVariable(binding); + public boolean visit(LocalDeclaration localDeclaration, BlockScope scope) { + if(localDeclaration.initialization instanceof FunctionExpression) { + this.visit(((FunctionExpression) localDeclaration.initialization).getMethodDeclaration(), scope); + } else { + TypeBinding type = localDeclaration.resolveVarType(scope); + LocalVariableBinding binding = new LocalVariableBinding(localDeclaration, type, 0, false); + localDeclaration.binding = binding; + addLocalVariable(binding); + } + return false; } - return false; - } - - public boolean visit(MethodDeclaration methodDeclaration, Scope parentScope) { - - char[] selector = null; - if(methodDeclaration.selector != null) { - selector = methodDeclaration.selector; - } else if(methodDeclaration.inferredMethod != null && methodDeclaration.inferredMethod.isConstructor) { - //this is that inferred constructors get added to the methods list - selector = methodDeclaration.inferredMethod.name; + /** + * @see org.eclipse.wst.jsdt.internal.compiler.ASTVisitor#visit(org.eclipse.wst.jsdt.internal.compiler.ast.Assignment, org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope) + */ + public boolean visit(Assignment assignment, BlockScope scope) { + /* If assigning to single name reference and there is no existing local + * variable binding for that reference, create one. This is for the case + * where their is no variable declaration in the compilation unit but the + * variable is assigned to. + */ + if(assignment.lhs instanceof SingleNameReference) { + SingleNameReference ref = (SingleNameReference)assignment.lhs; + + //only create new binding if one does not already exist + LocalVariableBinding existingBinding = scope.compilationUnitScope().findVariable(ref.getToken()); + if(existingBinding == null) { + LocalDeclaration localDeclaration = new LocalDeclaration(ref.getToken(),ref.sourceStart,ref.sourceEnd); + localDeclaration.inferredType = assignment.getInferredType(); + + TypeBinding binding = null; + if(localDeclaration.inferredType != null) { + binding = localDeclaration.inferredType.resolveType(scope.compilationUnitScope(), assignment); + } + + LocalVariableBinding localBinding = new LocalVariableBinding(localDeclaration, binding, 0, false); + scope.compilationUnitScope().addLocalVariable(localBinding); + } + } + + return super.visit(assignment, scope); } - - if (selector!=null) - { - MethodScope scope = new MethodScope(parentScope,methodDeclaration, false); - MethodBinding methodBinding = scope.createMethod(methodDeclaration,selector,referenceContext.compilationUnitBinding,false,false); - if (methodBinding != null && methodBinding.selector!=null) // is null if binding could not be created - methods.add(methodBinding); - if (methodBinding.selector!=null) - { - environment.defaultPackage.addBinding(methodBinding, methodBinding.selector,Binding.METHOD); - fPackage.addBinding(methodBinding, methodBinding.selector,Binding.METHOD); + + public boolean visit(MethodDeclaration methodDeclaration, Scope parentScope) { + // do not visit functions that are defined in another type, they will be visisted in + // that type + if(methodDeclaration.inferredMethod == null || methodDeclaration.inferredMethod.inType == null || methodDeclaration.inferredMethod.isConstructor) { + char[] selector = methodDeclaration.getName(); + boolean isConstructor = false; + + if(methodDeclaration.inferredMethod != null && methodDeclaration.inferredMethod.isConstructor) { + isConstructor = true; + } + + MethodScope scope = new MethodScope(parentScope, methodDeclaration, false); + if(selector != null && !methodDeclaration.hasBinding()) { + MethodBinding methodBinding = + scope.createMethod(methodDeclaration, selector, referenceContext.compilationUnitBinding, + isConstructor, false); + + // is null if binding could not be created + if(methodBinding != null && methodBinding.selector != null) { + methods.add(methodBinding); + } + if(methodBinding.selector != null) { + environment.defaultPackage.addBinding(methodBinding, methodBinding.selector, Binding.METHOD); + fPackage.addBinding(methodBinding, methodBinding.selector, Binding.METHOD); + } + methodDeclaration.setBinding(methodBinding); + } else { + methodDeclaration.setScope(scope); + } + if(fPackage != environment.defaultPackage) { + fPackage.addBinding(referenceContext.compilationUnitBinding, referenceContext.getMainTypeName(), + Binding.COMPILATION_UNIT); + } + + methodDeclaration.bindArguments(); } - methodDeclaration.binding=methodBinding; - methodDeclaration.bindArguments(); + return false; } - return false; } -} + public CompilationUnitScope(CompilationUnitDeclaration unit, LookupEnvironment environment) { + super(COMPILATION_UNIT_SCOPE, null); + this.environment = environment; + this.referenceContext = unit; + unit.scope = this; + + char[][] pkgName = + unit.currentPackage == null ? (unit.compilationResult != null ? unit.compilationResult.getPackageName() + : null) : unit.currentPackage.tokens; + this.currentPackageName = pkgName == null ? CharOperation.NO_CHAR_CHAR : pkgName; + + this.referencedTypes = new ObjectVector(); + if(compilerOptions().produceReferenceInfo) { + this.qualifiedReferences = new CompoundNameVector(); + this.simpleNameReferences = new SimpleNameVector(); + this.referencedSuperTypes = new ObjectVector(); + } else { + this.qualifiedReferences = null; // used to test if dependencies should be recorded + this.simpleNameReferences = null; + this.referencedSuperTypes = null; + } -public CompilationUnitScope(CompilationUnitDeclaration unit, LookupEnvironment environment) { - super(COMPILATION_UNIT_SCOPE, null); + this.fBuildingSuperBinding = false; + } - this.environment = environment; - this.referenceContext = unit; - unit.scope = this; + protected CompilationUnitScope(LookupEnvironment environment) { + super(COMPILATION_UNIT_SCOPE, null); + this.environment = environment; - /* bc - start bug 218398 - NPE when doing source->cleanup */ - - char [][]pkgName= unit.currentPackage == null ? - (unit.compilationResult!=null? unit.compilationResult.getPackageName():null) - : unit.currentPackage.tokens; - this.currentPackageName = pkgName == null ? CharOperation.NO_CHAR_CHAR : pkgName; -// this.currentPackageName = CharOperation.NO_CHAR_CHAR; - /* bc - end bug 218398 - NPE when doing source->cleanup */ - - - this.referencedTypes = new ObjectVector(); - if (compilerOptions().produceReferenceInfo) { - this.qualifiedReferences = new CompoundNameVector(); - this.simpleNameReferences = new SimpleNameVector(); - this.referencedSuperTypes = new ObjectVector(); - } else { - this.qualifiedReferences = null; // used to test if dependencies should be recorded - this.simpleNameReferences = null; -// this.referencedTypes = null; - this.referencedSuperTypes = null; + this.referencedTypes = new ObjectVector(); + if(compilerOptions().produceReferenceInfo) { + this.qualifiedReferences = new CompoundNameVector(); + this.simpleNameReferences = new SimpleNameVector(); + this.referencedSuperTypes = new ObjectVector(); + } else { + this.qualifiedReferences = null; // used to test if dependencies should be recorded + this.simpleNameReferences = null; + this.referencedSuperTypes = null; + } + + this.fBuildingSuperBinding = false; } -} - -protected CompilationUnitScope(LookupEnvironment environment) -{ - super(COMPILATION_UNIT_SCOPE, null); - this.environment = environment; - - this.referencedTypes = new ObjectVector(); - if (compilerOptions().produceReferenceInfo) { - this.qualifiedReferences = new CompoundNameVector(); - this.simpleNameReferences = new SimpleNameVector(); - this.referencedSuperTypes = new ObjectVector(); - } else { - this.qualifiedReferences = null; // used to test if dependencies should be recorded - this.simpleNameReferences = null; -// this.referencedTypes = null; - this.referencedSuperTypes = null; + public ClassScope classScope() { + if(this.classScope != null) + return this.classScope; + return super.classScope(); } -} -//public MethodScope methodScope() { -// if(superBinding!=null && methodScope==null) { -// methodScope = new MethodScope(classScope,referenceContext(),false); -// } -// -// return methodScope; -//} - -public ClassScope classScope() { - if (this.classScope!=null) return this.classScope; - return super.classScope(); -} + void buildFieldsAndMethods() { + for(int i = 0, length = topLevelTypes.length; i < length; i++) { + if(topLevelTypes[i] != null) { + topLevelTypes[i].buildFieldsAndMethods(); + } + } + } -void buildFieldsAndMethods() { - for (int i = 0, length = topLevelTypes.length; i < length; i++) - topLevelTypes[i].buildFieldsAndMethods(); -} - -void buildTypeBindings(AccessRestriction accessRestriction) { - buildTypeBindings(new char[0][0], accessRestriction); -} + void buildTypeBindings(AccessRestriction accessRestriction) { + buildTypeBindings(CharOperation.NO_CHAR_CHAR, accessRestriction); + } -void buildTypeBindings(char[][] restrictToNames, AccessRestriction accessRestriction) { - topLevelTypes = new SourceTypeBinding[0]; // want it initialized if the package cannot be resolved - if (referenceContext.compilationResult.compilationUnit != null) { - char[][] expectedPackageName = referenceContext.compilationResult.compilationUnit.getPackageName(); - if (expectedPackageName != null - && !CharOperation.equals(currentPackageName, expectedPackageName)) { - currentPackageName = expectedPackageName.length == 0 ? CharOperation.NO_CHAR_CHAR : expectedPackageName; + void buildTypeBindings(char[][] restrictToNames, AccessRestriction accessRestriction) { + existingTopLevelTypes = topLevelTypes; + topLevelTypes = new SourceTypeBinding[0]; // want it initialized if the package cannot be + // resolved + if(referenceContext.compilationResult.compilationUnit != null) { + char[][] expectedPackageName = referenceContext.compilationResult.compilationUnit.getPackageName(); + if(expectedPackageName != null && !CharOperation.equals(currentPackageName, expectedPackageName)) { + currentPackageName = expectedPackageName.length == 0 ? CharOperation.NO_CHAR_CHAR : expectedPackageName; + } } - } - if (currentPackageName == CharOperation.NO_CHAR_CHAR) { - fPackage = environment.defaultPackage; - } else { - if ((fPackage = environment.createPackage(currentPackageName)) == null) { -// problemReporter().packageCollidesWithType(referenceContext); -// return; -// } else if (referenceContext.isPackageInfo()) { -// // resolve package annotations now if this is "package-info.js". -// if (referenceContext.types == null || referenceContext.types.length == 0) { -// referenceContext.types = new TypeDeclaration[1]; -// TypeDeclaration declaration = new TypeDeclaration(referenceContext.compilationResult); -// referenceContext.types[0] = declaration; -// declaration.name = TypeConstants.PACKAGE_INFO_NAME; -// declaration.modifiers = ClassFileConstants.AccDefault | ClassFileConstants.AccInterface; -// firstIsSynthetic = true; -// } + if(currentPackageName == CharOperation.NO_CHAR_CHAR) { + fPackage = environment.defaultPackage; + } else { + fPackage = environment.createPackage(currentPackageName); } -// recordQualifiedReference(currentPackageName); // always dependent on your own package - } -// // Skip typeDeclarations which know of previously reported errors -// TypeDeclaration[] types = referenceContext.types; -// int typeLength = (types == null) ? 0 : types.length; -// topLevelTypes = new SourceTypeBinding[typeLength]; -// int count = 0; -// nextType: for (int i = 0; i < typeLength; i++) { -// TypeDeclaration typeDecl = types[i]; -// ReferenceBinding typeBinding = fPackage.getType0(typeDecl.name); -// recordSimpleReference(typeDecl.name); // needed to detect collision cases -// if (typeBinding != null && !(typeBinding instanceof UnresolvedReferenceBinding)) { -// // if a type exists, it must be a valid type - cannot be a NotFound problem type -// // unless its an unresolved type which is now being defined -// problemReporter().duplicateTypes(referenceContext, typeDecl); -// continue nextType; -// } -// if (fPackage != environment.defaultPackage && fPackage.getPackage(typeDecl.name) != null) { -// // if a package exists, it must be a valid package - cannot be a NotFound problem package -// problemReporter().typeCollidesWithPackage(referenceContext, typeDecl); -// continue nextType; -// } -// -// if ((typeDecl.modifiers & ClassFileConstants.AccPublic) != 0) { -// char[] mainTypeName; -// if ((mainTypeName = referenceContext.getMainTypeName()) != null // mainTypeName == null means that implementor of IJavaScriptUnit decided to return null -// && !CharOperation.equals(mainTypeName, typeDecl.name)) { -// problemReporter().publicClassMustMatchFileName(referenceContext, typeDecl); -// // tolerate faulty main type name (91091), allow to proceed into type construction -// } -// } -// -// ClassScope child = new ClassScope(this, typeDecl); -// SourceTypeBinding type = child.buildType(null, fPackage, accessRestriction); -// if (firstIsSynthetic && i == 0) -// type.modifiers |= ClassFileConstants.AccSynthetic; -// if (type != null) -// topLevelTypes[count++] = type; -// } -// -// // shrink topLevelTypes... only happens if an error was reported -// if (count != topLevelTypes.length) -// System.arraycopy(topLevelTypes, 0, topLevelTypes = new SourceTypeBinding[count], 0, count); -// - - this.faultInImports(); - - // Skip typeDeclarations which know of previously reported errors - int typeLength = referenceContext.numberInferredTypes; - - /* Include super type whild building */ -// if(superTypeName!=null) { -// superType = environment.askForType(new char[][] {superTypeName}); -// } - -// //((SourceTypeBinding)superType).classScope.buildInferredType(null, environment.defaultPackage,accessRestriction); -// //((SourceTypeBinding)superType).classScope.connectTypeHierarchy(); -// //FieldBinding[] fields = superType.fields(); -// //addSubscope(((SourceTypeBinding)superType).classScope); -// -// -// // this.parent = ((SourceTypeBinding)superType).classScope; -// -// -// } -// -// -// } - - /* may need to get the actual binding here */ -// if(libSuperType!=null) { -// //JsGlobalScopeContainerInitializer cinit = libSuperType.getContainerInitializer(); -// //IIncludePathEntry[] entries = libSuperType.getClasspathEntries(); -// IPackageFragment[] fragments = libSuperType.getPackageFragments(); -// for(int i = 0;i 0) { + List newlyBuiltTypes = new ArrayList(); + + SimpleSetOfCharArray addTypes = new SimpleSetOfCharArray(10); + boolean shouldTraverse = true; + String fileName = new String(this.referenceContext.getFileName()); + // do an initial pass through the types to be built and add their super types to the list, so they get + // built in the event they are anonymous. + for(int i = 0; i < typeLength; i++) { + InferredType typeDecl = referenceContext.inferredTypes[i]; + + if(typeDecl.isDefinition()) { + if (restrictToNames != null && restrictToNames.length > 0) { + boolean continueBuilding = false; + for(int j = 0; !continueBuilding && j < restrictToNames.length; j++) { + if(CharOperation.equals(typeDecl.getName(), restrictToNames[j])) + continueBuilding = true; + } + if(continueBuilding && typeDecl.getSuperType() != null && !typeDecl.getSuperType().isIndexed()) { + System.arraycopy(restrictToNames, 0, restrictToNames = new char[restrictToNames.length + 1][], 0, restrictToNames.length - 1); + restrictToNames[restrictToNames.length - 1] = typeDecl.getSuperClassName(); + } + } + } + } + nextType: for(int i = 0; i < typeLength; i++) { + InferredType typeDecl = referenceContext.inferredTypes[i]; + + if(typeDecl.isDefinition()) { + if (restrictToNames != null && restrictToNames.length > 0) { boolean continueBuilding = false; - for (int j = 0; !continueBuilding - && j < restrictToNames.length; j++) { - if (CharOperation.equals(typeDecl.getName(), - restrictToNames[j])) + for(int j = 0; !continueBuilding && j < restrictToNames.length; j++) { + if(CharOperation.equals(typeDecl.getName(), restrictToNames[j])) continueBuilding = true; } - if (!continueBuilding) + if(!continueBuilding) continue nextType; + + } + ReferenceBinding typeBinding = null; + // check that the type is not already built + if(existingTopLevelTypes != null && restrictToNames != null && restrictToNames.length > 0) { + for(int j = 0; j < existingTopLevelTypes.length; j++) { + /* use #sourceName here because it does not check through all the linked types + * for SourceTypeBindings, which in this case we do not want to do because it is + * not needed and is a performance drag */ + if(existingTopLevelTypes[j] != null && CharOperation.equals(typeDecl.getName(), existingTopLevelTypes[j].sourceName())) { + typeBinding = environment.defaultPackage.getType0(typeDecl.getName()); + if(typeBinding == null) { + environment.defaultPackage.addType(existingTopLevelTypes[j]); + fPackage.addType(existingTopLevelTypes[j]); + } + shouldTraverse = false; + continue nextType; + } + } + } + + shouldTraverse = false; + // build the type and its synonyms + SourceTypeBinding originalSourceType = null; + int numberOfTypesToBuild = 1 + (referenceContext.inferredTypes[i].getSynonyms() == null ? 0 : referenceContext.inferredTypes[i].getSynonyms().length); + for (int j = 0; j < numberOfTypesToBuild; j++) { + if (j > 0) { + // main type has been built, now build associated synonyms + typeDecl = referenceContext.inferredTypes[i].getSynonyms()[j - 1]; + if(typeDecl.binding != null) + break; + } + + typeBinding = environment.defaultPackage.getType0(typeDecl.getName()); + recordSimpleReference(typeDecl.getName()); // needed to detect collision cases + SourceTypeBinding existingBinding = null; + if(typeBinding != null && !(typeBinding instanceof UnresolvedReferenceBinding)) { + /* if a type exists, it must be a valid type - cannot + * be a NotFound problem type unless it's an unresolved + * type which is now being defined + */ + if(typeBinding instanceof SourceTypeBinding) { + existingBinding = (SourceTypeBinding) typeBinding; + } + } + ClassScope child = new ClassScope(this, typeDecl); + SourceTypeBinding type = child.buildInferredType(null, environment.defaultPackage, accessRestriction); + if(type != null) { + if (j == 0) { + originalSourceType = type; + } + + if (existingBinding != null && typeDecl.isIndexed()) { + existingBinding.addLinkedBinding(type); + environment.defaultPackage.addType(existingBinding); + fPackage.addType(existingBinding); + } + else if(typeDecl.isIndexed()) { + addTypes.add(typeDecl.getName()); + } + + // set the original type as a nextType on this synonym + if (j > 0 && originalSourceType != null) { + type.addLinkedBinding(originalSourceType); + } + newlyBuiltTypes.add(type); + } + } } - ReferenceBinding typeBinding = environment.defaultPackage - .getType0(typeDecl.getName()); - recordSimpleReference(typeDecl.getName()); // needed to detect collision cases - SourceTypeBinding existingBinding=null; - if (typeBinding != null - && !(typeBinding instanceof UnresolvedReferenceBinding)) { - // if a type exists, it must be a valid type - cannot be a NotFound problem type - // unless its an unresolved type which is now being defined -// problemReporter().duplicateTypes(referenceContext, typeDecl); -// continue nextType; - if (typeBinding instanceof SourceTypeBinding) - existingBinding=(SourceTypeBinding)typeBinding; + } + + /* shrink topLevelTypes... + * happens if error reported or if only building restricted type names */ + int count = newlyBuiltTypes.size(); + topLevelTypes = (SourceTypeBinding[]) newlyBuiltTypes.toArray(new SourceTypeBinding[count]); + + if(existingTopLevelTypes != null && restrictToNames != null && restrictToNames.length > 0) { + System.arraycopy(topLevelTypes, 0, topLevelTypes = new SourceTypeBinding[count + existingTopLevelTypes.length], 0, count); + System.arraycopy(existingTopLevelTypes, 0, topLevelTypes, count, existingTopLevelTypes.length); + existingTopLevelTypes = null; + } + + /* set up context, needs to be done before super type can be built + * since building super type may refer back to this contexts binding */ + char[] path = CharOperation.concatWith(this.currentPackageName, '/'); + if(referenceContext.compilationUnitBinding == null) { + referenceContext.compilationUnitBinding = + new CompilationUnitBinding(this, environment.defaultPackage, path); + + if(fPackage != environment.defaultPackage) + fPackage.addBinding(referenceContext.compilationUnitBinding, referenceContext.getMainTypeName(), + Binding.COMPILATION_UNIT); + } + + // build the super type + if(shouldBuildGlobalSuperType()) + buildSuperType(); + + //set the super type on the binding + this.referenceContext.compilationUnitBinding.setSuperBinding(this.superBinding); + + //add new type bindings + char[][] typeNames = new char[addTypes.elementSize][]; + addTypes.asArray(typeNames); + environment.addUnitsContainingBindings(typeNames, Binding.TYPE, fileName); + + // connect synonymous types, now that their synonyms should have bindings + for (int i = 0; i < typeLength; i++) { + char[] inferredTypeName = referenceContext.inferredTypes[i].getName(); + + //determine if the inferredTypeName is in the restrict to list + boolean isResctrictToName = true; + if (restrictToNames != null && restrictToNames.length > 0) { + isResctrictToName = false; + for(int j = 0; !isResctrictToName && j < restrictToNames.length; j++) { + isResctrictToName = CharOperation.equals(inferredTypeName, restrictToNames[j]); + } } - ClassScope child = new ClassScope(this, typeDecl); - SourceTypeBinding type = child.buildInferredType(null, environment.defaultPackage, - accessRestriction); - // SourceTypeBinding type = buildType(typeDecl,null, fPackage, accessRestriction); - if (type != null) - { - if (existingBinding!=null && typeDecl.isNamed() ) - { - if (existingBinding.nextType!=null) - { - existingBinding.addNextType(type); - } - else - { - if (!CharOperation.equals(type.fileName, existingBinding.fileName)) - existingBinding.addNextType(type); + + //if inferred type is on restricted list and any linked synonyms + if (isResctrictToName && referenceContext.inferredTypes[i].getSynonyms() != null) { + ReferenceBinding binding = environment.defaultPackage.getType0(inferredTypeName); + if (binding != null && binding instanceof SourceTypeBinding) { + for (int j = 0; j < referenceContext.inferredTypes[i].getSynonyms().length; j++) { + ReferenceBinding synonymBinding = environment.defaultPackage.getType0(referenceContext.inferredTypes[i].getSynonyms()[j].getName()); + if (synonymBinding != null && synonymBinding instanceof SourceTypeBinding) { + ((SourceTypeBinding) binding).addLinkedBinding((SourceTypeBinding) synonymBinding); + } } - environment.defaultPackage.addType(existingBinding); - fPackage.addType(existingBinding); } - else - if (typeDecl.isNamed() ) - addTypes.add(typeDecl.getName()); -// environment.addUnitsContainingBinding(null, typeDecl.getName(), Binding.TYPE,fileName); - topLevelTypes[count++] = type; + } + } + + if((restrictToNames == null || restrictToNames.length == 0) || shouldTraverse) { + if(referenceContext.compilationUnitBinding.methods == Binding.NO_METHODS) { + DeclarationVisitor visitor = new DeclarationVisitor(); + this.referenceContext.traverse(visitor, this); + MethodBinding[] methods = + (MethodBinding[]) visitor.methods.toArray(new MethodBinding[visitor.methods.size()]); + referenceContext.compilationUnitBinding.setMethods(methods); } } } - - char [][] typeNames= new char [addTypes.elementSize] []; - addTypes.asArray(typeNames); - environment.addUnitsContainingBindings(typeNames, Binding.TYPE, fileName); - + /** + *

+ * Builds the super type for this scope. This also includes adding the + * "global" type to the global type type hierarchy. + *

+ *

+ * If the super type has already been built then this is a no-op. + *

+ */ + public void buildSuperType() { + //be sure to only build the super once and not allow an infinite loop of building to occur + synchronized (this.fBuidingSuperBindingLock) { + if(this.fBuildingSuperBinding || this.superBinding != null) { + return; + } else { + this.fBuildingSuperBinding = true; + } + } + + try { + char[] superTypeName = null; + LibrarySuperType libSuperType = null; + if(this.referenceContext.compilationResult!=null && this.referenceContext.compilationResult.compilationUnit!=null) { + libSuperType = this.referenceContext.compilationResult.compilationUnit.getCommonSuperType(); + if(libSuperType==null) { + return; + } else { + superTypeName = libSuperType.getSuperTypeName().toCharArray(); + } + } + + if (superTypeName==null) { + return; + } - // shrink topLevelTypes... only happens if an error was reported - if (count != topLevelTypes.length) - System.arraycopy(topLevelTypes, 0, topLevelTypes = new SourceTypeBinding[count], 0, count); - - - buildSuperType(); - - - char [] path=CharOperation.concatWith(this.currentPackageName, '/'); - referenceContext.compilationUnitBinding=new CompilationUnitBinding(this,environment.defaultPackage,path, superBinding); - - if (fPackage!=environment.defaultPackage) - fPackage.addBinding(referenceContext.compilationUnitBinding, referenceContext.getMainTypeName(), Binding.COMPILATION_UNIT); - - DeclarationVisitor visitor = new DeclarationVisitor(); - this.referenceContext.traverse(visitor, this); - MethodBinding[] methods = (MethodBinding[])visitor.methods.toArray(new MethodBinding[visitor.methods.size()]); - referenceContext.compilationUnitBinding.setMethods(methods); -} - -public void buildSuperType() { - - char[] superTypeName = null; - LibrarySuperType libSuperType = null; - if(this.referenceContext.compilationResult!=null && this.referenceContext.compilationResult.compilationUnit!=null) { - libSuperType = this.referenceContext.compilationResult.compilationUnit.getCommonSuperType(); - if(libSuperType==null) { - superTypeName = null; - return; - }else - superTypeName = libSuperType.getSuperTypeName().toCharArray(); + this.superBinding = findType(superTypeName, environment.defaultPackage, environment.defaultPackage); + + if(this.superBinding==null || !this.superBinding.isValidBinding()) { + superTypeName = null; + return ; + } + + /* If super type is combined source type, search through SourceTypes for the specific instance */ + if( (this.superBinding instanceof SourceTypeBinding)) { + this.classScope = ((SourceTypeBinding)this.superBinding).classScope; + } else if(this.superBinding!=null) { + InferredType te = this.superBinding.getInferredType(); + this.classScope = new ClassScope(this, te); + } + + if(this.superBinding != null && this.classScope != null) { + SourceTypeBinding sourceType = null; + + if(this.superBinding instanceof SourceTypeBinding) { + sourceType = (SourceTypeBinding)this.superBinding; + } + this.classScope.buildInferredType(sourceType, this.environment.defaultPackage, null); + + //if there is a searchable environment then merge global fields with fields on super binding + if(this.environment().nameEnvironment instanceof SearchableEnvironment) { + //find all of the global fields from the index + SearchableEnvironment env = (SearchableEnvironment)this.environment().nameEnvironment; + final HashtableOfObject globalFields = new HashtableOfObject(); + env.findVariables(null, new char[][]{IIndexConstants.GLOBAL_SYMBOL}, false, new ISearchRequestor() { + + public void acceptVariable(char[] signature, char[] typeQualification, char[] typeSimpleName, char[] declaringQualification, char[] declaringSimpleName, int modifiers, String path) { + //store global field and its type name + globalFields.put(signature, QualificationHelpers.createFullyQualifiedName(typeQualification, typeSimpleName)); + } + + public void acceptType(char[] packageName, char[] fileName, char[] typeName, char[][] enclosingTypeNames, int modifiers, AccessRestriction accessRestriction) { + //ignore + } + + public void acceptPackage(char[] packageName) { + //ignore + } + + public void acceptFunction(char[] signature, char[][] parameterFullyQualifedTypeNames, char[][] parameterNames, char[] returnQualification, char[] returnSimpleName, char[] declaringQualification, char[] declaringSimpleName, int modifiers, String path) { + //ignore + } + + public void acceptConstructor(int modifiers, char[] typeName, char[][] parameterTypes, char[][] parameterNames, String path, AccessRestriction access) { + //ignore + } + + public void acceptBinding(char[] packageName, char[] fileName, char[] bindingName, int bindingType, int modifiers, AccessRestriction accessRestriction) { + //ignore + } + }); + + //merge the global fields with the super binding fields + mergeWithSuperBinding(globalFields); + } + + recordTypeReference(this.superBinding); + recordSuperTypeReference(this.superBinding); + environment().setAccessRestriction(this.superBinding, null); + } + + //check to see if the special "global" type was created in this scope, if so make it the super binding + if(this.topLevelTypes != null) { + TypeBinding globalType = null; + for(int i = 0; i < this.topLevelTypes.length && globalType == null; ++i) { + if(this.topLevelTypes[i] != null && CharOperation.equals(this.topLevelTypes[i].sourceName,IIndexConstants.GLOBAL_SYMBOL)) { + globalType = this.topLevelTypes[i]; + } + } + + if(globalType instanceof ReferenceBinding) { + if(this.superBinding == null) { + this.superBinding = (ReferenceBinding)globalType; + } else if (this.superBinding instanceof SourceTypeBinding) { + ReferenceBinding currentSuper = this.superBinding; + ReferenceBinding previousSuper = this.superBinding; + /* need to find the type with no super type or with Object as its super type, + * so that the "fake" Global object can be injected in there */ + while(currentSuper != null && !CharOperation.equals(currentSuper.sourceName, IIndexConstants.OBJECT)) { + previousSuper = currentSuper; + if(currentSuper instanceof SourceTypeBinding) { + currentSuper = ((SourceTypeBinding)currentSuper).getSuperBinding0(); + } + else { + break; + } + } + + // if we found the null class just add the global object + if(currentSuper == null) { + if(!CharOperation.equals(previousSuper.sourceName, globalType.sourceName())) { + ((SourceTypeBinding)previousSuper).setSuperBinding((ReferenceBinding)globalType); + } + } + else if(CharOperation.equals(currentSuper.sourceName, IIndexConstants.OBJECT)){ + // if we found the object case, set object as the parent of global first + ((SourceTypeBinding)globalType).setSuperBinding(currentSuper); + + if(!CharOperation.equals(previousSuper.sourceName, globalType.sourceName())) { + ((SourceTypeBinding)previousSuper).setSuperBinding((ReferenceBinding)globalType); + } + } + } + } + } + } finally { + //finished building super + synchronized (this.fBuidingSuperBindingLock) { + this.fBuildingSuperBinding = false; + } + } } - if (superTypeName==null) - return; - -// superBinding = environment.askForType(new char[][] {superTypeName}); - superBinding = findType(superTypeName, environment.defaultPackage, environment.defaultPackage); - - if(superBinding==null || !superBinding.isValidBinding()) { - superTypeName = null; - return ; + + /** + *

+ * Merges the table of global field names to their types with the fields of the super binding. + *

+ * + * @param globalFields table of global field names to their types to merge with the fields of + * the super binding + */ + private void mergeWithSuperBinding(HashtableOfObject globalFields) { + //list of the super fields to iterate through + List superBindingFields = new ArrayList(); + superBindingFields.addAll(Arrays.asList(this.superBinding.fields())); + + //set of the super field names so that duplicates do not get added to the list + SimpleSetOfCharArray superBindingFieldsNames = new SimpleSetOfCharArray(superBindingFields.size()); + for(int i = 0; i < superBindingFields.size(); ++i) { + superBindingFieldsNames.add(((FieldBinding)superBindingFields.get(i)).name); } - - - /* If super type is combined source type, search through SourceTypes for the specific instance */ - if( (superBinding instanceof SourceTypeBinding) && ((SourceTypeBinding)superBinding).nextType!=null) { - + + /* for each super binding field check if there is an existing global + * field with the same name to merge it with */ + for(int superBindingFieldIndex = 0; + superBindingFieldIndex < superBindingFields.size(); + ++superBindingFieldIndex) { - classScope = ((SourceTypeBinding)superBinding).classScope; - - SourceTypeBinding sourceType = null; - - if(superBinding instanceof SourceTypeBinding) { - sourceType = (SourceTypeBinding)superBinding; + FieldBinding superBindingField = (FieldBinding)superBindingFields.get(superBindingFieldIndex); + + //check if there is an existing global field with the same name as the super type field + char[] globalFieldType = (char[])globalFields.get(superBindingField.name); + + /* if no global field then guess that their might be an anonymous + * global type for the super binding. + * + * IE: + * navigator.foo = 42 + * + * This creates a global anonymous type for navigator but does not + * add it to the global type for performance reasons. */ + if(globalFieldType == null || globalFieldType.length == 0) { + globalFieldType = InferEngine.createAnonymousGlobalTypeName(superBindingField.name); + } + + /* if the type for the global field can be found and is valid then + * merge it with the super binding field */ + ReferenceBinding globalFieldBinding = this.findType(globalFieldType, + this.getCurrentPackage(), this.getCurrentPackage()); + if(globalFieldBinding != null && + globalFieldBinding instanceof SourceTypeBinding && + globalFieldBinding.isValidBinding() && + !globalFieldBinding.isAnyType()) { + + /* if the type of the super binding field is the same as the super binding + * then the fields of the super binding field should also be considered + * super binding fields + * + * IE: there is a field on the Window type named window that has a + * type of Window. Thus any fields of the window field also need to be + * merged with the super binding (this example is assuming window is the super + * type) */ + if(superBindingField.type != null && superBindingField.type.isEquivalentTo(this.superBinding)) { + FieldBinding[] fieldsOnGlobalField = globalFieldBinding.fields(); + for(int fieldsOnGlobalFieldIndex = 0; + fieldsOnGlobalFieldIndex < fieldsOnGlobalField.length; + ++fieldsOnGlobalFieldIndex) { + + //only add if field with name that is not already added + if(!superBindingFieldsNames.includes(fieldsOnGlobalField[fieldsOnGlobalFieldIndex].name)) { + superBindingFields.add(fieldsOnGlobalField[fieldsOnGlobalFieldIndex]); + } + } + } + + /* if the super field type is a SourceTypeBinding then link it with that of the global field + * else if the super field does not have a type or is the any type set it to be the type + * of the global field */ + if(superBindingField.type != null && superBindingField.type instanceof SourceTypeBinding) { + ((SourceTypeBinding)superBindingField.type).addLinkedBinding((SourceTypeBinding)globalFieldBinding); + } else if(superBindingField.type == null || superBindingField.type.isAnyType() ){ + superBindingField.type = globalFieldBinding; } - classScope.buildInferredType(sourceType, environment.defaultPackage, null); - - - recordTypeReference(superBinding); - recordSuperTypeReference(superBinding); - environment().setAccessRestriction(superBinding, null); - }else if(superBinding!=null) { - InferredType te = superBinding.getInferredType(); - classScope = new ClassScope(this, te); - - SourceTypeBinding sourceType = null; - - if(superBinding instanceof SourceTypeBinding) { - sourceType = (SourceTypeBinding)superBinding; } - classScope.buildInferredType(sourceType, environment.defaultPackage, null); - - - recordTypeReference(superBinding); - recordSuperTypeReference(superBinding); - environment().setAccessRestriction(superBinding, null); } - - - - - - - - if(superTypeName!=null && superTypeName.length==0) { - superTypeName=null; } -} -SourceTypeBinding buildType(InferredType inferredType, SourceTypeBinding enclosingType, PackageBinding packageBinding, AccessRestriction accessRestriction) { - // provide the typeDeclaration with needed scopes + SourceTypeBinding buildType(InferredType inferredType, SourceTypeBinding enclosingType, + PackageBinding packageBinding, AccessRestriction accessRestriction) { + + // provide the typeDeclaration with needed scopes + if(enclosingType == null) { + char[][] className = CharOperation.arrayConcat(packageBinding.compoundName, inferredType.getName()); + inferredType.binding = new SourceTypeBinding(className, packageBinding, this); - if (enclosingType == null) { - char[][] className = CharOperation.arrayConcat(packageBinding.compoundName, inferredType.getName()); - inferredType.binding = new SourceTypeBinding(className, packageBinding, this); + // @GINO: Anonymous set bits + if(!inferredType.isNamed()) + inferredType.binding.tagBits |= TagBits.AnonymousTypeMask; - //@GINO: Anonymous set bits - if( inferredType.isAnonymous ) - inferredType.binding.tagBits |= TagBits.AnonymousTypeMask; + } - } else { -// char[][] className = CharOperation.deepCopy(enclosingType.compoundName); -// className[className.length - 1] = -// CharOperation.concat(className[className.length - 1], inferredType.getName(), '$'); -// inferredType.binding = new MemberTypeBinding(className, this, enclosingType); + SourceTypeBinding sourceType = inferredType.binding; + environment().setAccessRestriction(sourceType, accessRestriction); + environment().defaultPackage.addType(sourceType); + sourceType.fPackage.addType(sourceType); + return sourceType; } - SourceTypeBinding sourceType = inferredType.binding; - environment().setAccessRestriction(sourceType, accessRestriction); - environment().defaultPackage.addType(sourceType); - sourceType.fPackage.addType(sourceType); - return sourceType; -} - - -public PackageBinding getDefaultPackage() { + public PackageBinding getDefaultPackage() { return environment.defaultPackage; -} - -public void addLocalVariable(LocalVariableBinding binding) { - super.addLocalVariable(binding); - environment.defaultPackage.addBinding(binding, binding.name, Binding.VARIABLE); - fPackage.addBinding(binding, binding.name, Binding.VARIABLE); -} - -void checkAndSetImports() { - if (referenceContext.imports == null) { - imports = getDefaultImports(); - return; } - // allocate the import array, add java.lang.* by default - int numberOfStatements = referenceContext.imports.length; - int numberOfImports = numberOfStatements + 1; - for (int i = 0; i < numberOfStatements; i++) { - ImportReference importReference = referenceContext.imports[i]; - if (((importReference.bits & ASTNode.OnDemand) != 0) && CharOperation.equals(JAVA_LANG, importReference.tokens)) { - numberOfImports--; - break; - } + public void addLocalVariable(LocalVariableBinding binding) { + super.addLocalVariable(binding); + environment.defaultPackage.addBinding(binding, binding.name, Binding.VARIABLE); + fPackage.addBinding(binding, binding.name, Binding.VARIABLE); } - ImportBinding[] resolvedImports = new ImportBinding[numberOfImports]; - resolvedImports[0] = getDefaultImports()[0]; - int index = 1; - - nextImport : for (int i = 0; i < numberOfStatements; i++) { - ImportReference importReference = referenceContext.imports[i]; - char[][] compoundName = importReference.tokens; - - // skip duplicates or imports of the current package - for (int j = 0; j < index; j++) { - ImportBinding resolved = resolvedImports[j]; - if (resolved.onDemand == ((importReference.bits & ASTNode.OnDemand) != 0)) - if (CharOperation.equals(compoundName, resolvedImports[j].compoundName)) - continue nextImport; - } - if ((importReference.bits & ASTNode.OnDemand) != 0) { - if (CharOperation.equals(compoundName, currentPackageName)) - continue nextImport; + void checkAndSetImports() { + if(referenceContext.imports == null) { + imports = getDefaultImports(); + return; + } - Binding importBinding = findImport(compoundName, compoundName.length); - if (!importBinding.isValidBinding()) - continue nextImport; // we report all problems in faultInImports() - resolvedImports[index++] = new ImportBinding(compoundName, true, importBinding, importReference); - } else { - // resolve single imports only when the last name matches - resolvedImports[index++] = new ImportBinding(compoundName, false, null, importReference); + // allocate the import array, add java.lang.* by default + int numberOfStatements = referenceContext.imports.length; + int numberOfImports = numberOfStatements + 1; + for(int i = 0; i < numberOfStatements; i++) { + ImportReference importReference = referenceContext.imports[i]; + if(((importReference.bits & ASTNode.OnDemand) != 0) + && CharOperation.equals(JAVA_LANG, importReference.tokens)) { + numberOfImports--; + break; + } } - } + ImportBinding[] resolvedImports = new ImportBinding[numberOfImports]; + resolvedImports[0] = getDefaultImports()[0]; + int index = 1; + + nextImport: for(int i = 0; i < numberOfStatements; i++) { + ImportReference importReference = referenceContext.imports[i]; + char[][] compoundName = importReference.tokens; + + // skip duplicates or imports of the current package + for(int j = 0; j < index; j++) { + ImportBinding resolved = resolvedImports[j]; + if(resolved.onDemand == ((importReference.bits & ASTNode.OnDemand) != 0)) + if(CharOperation.equals(compoundName, resolvedImports[j].compoundName)) + continue nextImport; + } - // shrink resolvedImports... only happens if an error was reported - if (resolvedImports.length > index) - System.arraycopy(resolvedImports, 0, resolvedImports = new ImportBinding[index], 0, index); - imports = resolvedImports; -} + if((importReference.bits & ASTNode.OnDemand) != 0) { + if(CharOperation.equals(compoundName, currentPackageName)) + continue nextImport; -/* - * INTERNAL USE-ONLY - * Innerclasses get their name computed as they are generated, since some may not - * be actually outputed if sitting inside unreachable code. - */ -public char[] computeConstantPoolName(LocalTypeBinding localType) { - if (localType.constantPoolName() != null) { - return localType.constantPoolName(); - } - // delegates to the outermost enclosing classfile, since it is the only one with a global vision of its innertypes. - - if (constantPoolNameUsage == null) - constantPoolNameUsage = new HashtableOfType(); - - ReferenceBinding outerMostEnclosingType = localType.scope.outerMostClassScope().enclosingSourceType(); - - // ensure there is not already such a local type name defined by the user - int index = 0; - char[] candidateName; - boolean isCompliant15 = compilerOptions().complianceLevel >= ClassFileConstants.JDK1_5; - while(true) { - if (localType.isMemberType()){ - if (index == 0){ - candidateName = CharOperation.concat( - localType.enclosingType().constantPoolName(), - localType.sourceName, - '$'); + Binding importBinding = findImport(compoundName, compoundName.length); + if(!importBinding.isValidBinding()) + continue nextImport; // we report all problems in faultInImports() + resolvedImports[index++] = new ImportBinding(compoundName, true, importBinding, importReference); } else { - // in case of collision, then member name gets extra $1 inserted - // e.g. class X { { class L{} new X(){ class L{} } } } - candidateName = CharOperation.concat( - localType.enclosingType().constantPoolName(), - '$', - String.valueOf(index).toCharArray(), - '$', - localType.sourceName); + // resolve single imports only when the last name matches + resolvedImports[index++] = new ImportBinding(compoundName, false, null, importReference); } - } else if (localType.isAnonymousType()){ - if (isCompliant15) { - // from 1.5 on, use immediately enclosing type name - candidateName = CharOperation.concat( - localType.enclosingType.constantPoolName(), - String.valueOf(index+1).toCharArray(), - '$'); + } + + // shrink resolvedImports... only happens if an error was reported + if(resolvedImports.length > index) + System.arraycopy(resolvedImports, 0, resolvedImports = new ImportBinding[index], 0, index); + imports = resolvedImports; + } + + /* INTERNAL USE-ONLY + * Innerclasses get their name computed as they are generated, since some may not + * be actually outputed if sitting inside unreachable code. */ + public char[] computeConstantPoolName(LocalTypeBinding localType) { + if(localType.constantPoolName() != null) { + return localType.constantPoolName(); + } + // delegates to the outermost enclosing classfile, since it is the only one with a global + // vision of its innertypes. + + if(constantPoolNameUsage == null) + constantPoolNameUsage = new HashtableOfType(); + + ReferenceBinding outerMostEnclosingType = localType.scope.outerMostClassScope().enclosingSourceType(); + + // ensure there is not already such a local type name defined by the user + int index = 0; + char[] candidateName; + boolean isCompliant15 = compilerOptions().complianceLevel >= ClassFileConstants.JDK1_5; + while(true) { + if(localType.isMemberType()) { + if(index == 0) { + candidateName = + CharOperation.concat(localType.enclosingType().constantPoolName(), localType.sourceName, + '.'); + } else { + // in case of collision, then member name gets extra $1 inserted + // e.g. class X { { class L{} new X(){ class L{} } } } + candidateName = + CharOperation.concat(localType.enclosingType().constantPoolName(), '.', String.valueOf( + index).toCharArray(), '.', localType.sourceName); + } + } else if(localType.isAnonymousType()) { + if(isCompliant15) { + // from 1.5 on, use immediately enclosing type name + candidateName = + CharOperation.concat(localType.enclosingType.constantPoolName(), + String.valueOf(index + 1).toCharArray(), '.'); + } else { + candidateName = + CharOperation.concat(outerMostEnclosingType.constantPoolName(), + String.valueOf(index + 1).toCharArray(), '.'); + } } else { - candidateName = CharOperation.concat( - outerMostEnclosingType.constantPoolName(), - String.valueOf(index+1).toCharArray(), - '$'); + // local type + if(isCompliant15) { + candidateName = + CharOperation.concat(CharOperation.concat(localType.enclosingType().constantPoolName(), + String.valueOf(index + 1).toCharArray(), '.'), localType.sourceName); + } else { + candidateName = + CharOperation.concat(outerMostEnclosingType.constantPoolName(), '.', String.valueOf( + index + 1).toCharArray(), '.', localType.sourceName); + } } - } else { - // local type - if (isCompliant15) { - candidateName = CharOperation.concat( - CharOperation.concat( - localType.enclosingType().constantPoolName(), - String.valueOf(index+1).toCharArray(), - '$'), - localType.sourceName); + if(constantPoolNameUsage.get(candidateName) != null) { + index++; } else { - candidateName = CharOperation.concat( - outerMostEnclosingType.constantPoolName(), - '$', - String.valueOf(index+1).toCharArray(), - '$', - localType.sourceName); + constantPoolNameUsage.put(candidateName, localType); + break; } } - if (constantPoolNameUsage.get(candidateName) != null) { - index ++; - } else { - constantPoolNameUsage.put(candidateName, localType); - break; - } + return candidateName; } - return candidateName; -} -void connectTypeHierarchy(char[][] typeNames) { - // if(superType!=null) { - // if(superType instanceof SourceTypeBinding) { - // ((SourceTypeBinding)superType).classScope.buildFieldsAndMethods(); - // ((SourceTypeBinding)superType).classScope.connectTypeHierarchy(); - // - // } - // ReferenceBinding[] memberTypes = superType.memberTypes(); - // ReferenceBinding[] memberFields = superType.typeVariables(); - // FunctionBinding[] memberMethods = superType.availableMethods(); - // for(int i=0;i 0) { boolean continueBuilding = false; - for (int j = 0; !continueBuilding - && j < typeNames.length; j++) { - if (CharOperation.equals(inferredType.getName(), - typeNames[j])) + for(int j = 0; !continueBuilding && j < typeNames.length; j++) { + if(CharOperation.equals(inferredType.getName(), typeNames[j])) continueBuilding = true; } - if (!continueBuilding) + if(!continueBuilding) continue nextType; - - } - if (inferredType.binding != null) + } + if(inferredType.binding != null && inferredType.binding.classScope != null) { inferredType.binding.classScope.connectTypeHierarchy(); - + } } -} -void connectTypeHierarchy() { - connectTypeHierarchy(new char[0][0]); -} -void faultInImports() { - if (this.typeOrPackageCache != null) - return; // can be called when a field constant is resolved before static imports - if (referenceContext.imports == null) { - this.typeOrPackageCache = new HashtableOfObject(1); - return; } - // collect the top level type names if a single type import exists - int numberOfStatements = referenceContext.imports.length; - HashtableOfType typesBySimpleNames = null; - for (int i = 0; i < numberOfStatements; i++) { - if ((referenceContext.imports[i].bits & ASTNode.OnDemand) == 0) { - typesBySimpleNames = new HashtableOfType(topLevelTypes.length + numberOfStatements); - for (int j = 0, length = topLevelTypes.length; j < length; j++) - typesBySimpleNames.put(topLevelTypes[j].sourceName, topLevelTypes[j]); - break; - } + void connectTypeHierarchy() { + connectTypeHierarchy(CharOperation.NO_CHAR_CHAR); } - // allocate the import array, add java.lang.* by default - ImportBinding[] defaultImports = getDefaultImports(); - int numberOfImports = numberOfStatements + defaultImports.length; - for (int i = 0; i < numberOfStatements; i++) { - ImportReference importReference = referenceContext.imports[i]; - if (((importReference.bits & ASTNode.OnDemand) != 0) && CharOperation.equals(JAVA_LANG, importReference.tokens)) { - numberOfImports--; - break; + void faultInImports() { + if(this.typeOrPackageCache != null) + return; // can be called when a field constant is resolved before static imports + if(referenceContext.imports == null) { + this.typeOrPackageCache = new HashtableOfObject(1); + return; } - } - ImportBinding[] resolvedImports = new ImportBinding[numberOfImports]; - System.arraycopy(defaultImports, 0, resolvedImports, 0, defaultImports.length); - int index = defaultImports.length; - - // keep static imports with normal imports until there is a reason to split them up - // on demand imports continue to be packages & types. need to check on demand type imports for fields/methods - // single imports change from being just types to types or fields - nextImport : for (int i = 0; i < numberOfStatements; i++) { - ImportReference importReference = referenceContext.imports[i]; - char[][] compoundName = importReference.tokens; - - // skip duplicates or imports of the current package - for (int j = 0; j < index; j++) { - ImportBinding resolved = resolvedImports[j]; - if (resolved.onDemand == ((importReference.bits & ASTNode.OnDemand) != 0)) { - if (CharOperation.equals(compoundName, resolved.compoundName)) { - continue nextImport; - } + + // collect the top level type names if a single type import exists + int numberOfStatements = referenceContext.imports.length; + HashtableOfType typesBySimpleNames = null; + for(int i = 0; i < numberOfStatements; i++) { + if((referenceContext.imports[i].bits & ASTNode.OnDemand) == 0) { + typesBySimpleNames = new HashtableOfType(topLevelTypes.length + numberOfStatements); + for(int j = 0, length = topLevelTypes.length; j < length; j++) + typesBySimpleNames.put(topLevelTypes[j].sourceName, topLevelTypes[j]); + break; } } - if ((importReference.bits & ASTNode.OnDemand) != 0) { - if (CharOperation.equals(compoundName, currentPackageName)) { - continue nextImport; - } - Binding importBinding = findImport(compoundName, compoundName.length); - if (!importBinding.isValidBinding()) { - continue nextImport; - } - resolvedImports[index++] = new ImportBinding(compoundName, true, importBinding, importReference); - } else { - Binding importBinding = findSingleImport(compoundName); - if (!importBinding.isValidBinding()) { - continue nextImport; + // allocate the import array, add java.lang.* by default + ImportBinding[] defaultImports = getDefaultImports(); + int numberOfImports = numberOfStatements + defaultImports.length; + for(int i = 0; i < numberOfStatements; i++) { + ImportReference importReference = referenceContext.imports[i]; + if(((importReference.bits & ASTNode.OnDemand) != 0) + && CharOperation.equals(JAVA_LANG, importReference.tokens)) { + numberOfImports--; + break; } - ReferenceBinding conflictingType = null; - if (importBinding instanceof MethodBinding) { - conflictingType = (ReferenceBinding) getType(compoundName, compoundName.length); - if (!conflictingType.isValidBinding()) - conflictingType = null; + } + ImportBinding[] resolvedImports = new ImportBinding[numberOfImports]; + System.arraycopy(defaultImports, 0, resolvedImports, 0, defaultImports.length); + int index = defaultImports.length; + + // keep static imports with normal imports until there is a reason to split them up + // on demand imports continue to be packages & types. need to check on demand type imports + // for fields/methods + // single imports change from being just types to types or fields + nextImport: for(int i = 0; i < numberOfStatements; i++) { + ImportReference importReference = referenceContext.imports[i]; + char[][] compoundName = importReference.tokens; + + // skip duplicates or imports of the current package + for(int j = 0; j < index; j++) { + ImportBinding resolved = resolvedImports[j]; + if(resolved.onDemand == ((importReference.bits & ASTNode.OnDemand) != 0)) { + if(CharOperation.equals(compoundName, resolved.compoundName)) { + continue nextImport; + } + } } - // collisions between an imported static field & a type should be checked according to spec... but currently not by javac - if (importBinding instanceof ReferenceBinding || conflictingType != null) { - ReferenceBinding referenceBinding = conflictingType == null ? (ReferenceBinding) importBinding : conflictingType; - if (importReference.isTypeUseDeprecated(referenceBinding, this)) - problemReporter().deprecatedType(referenceBinding, importReference); - - ReferenceBinding existingType = typesBySimpleNames.get(compoundName[compoundName.length - 1]); - if (existingType != null) { + if((importReference.bits & ASTNode.OnDemand) != 0) { + if(CharOperation.equals(compoundName, currentPackageName)) { continue nextImport; } - typesBySimpleNames.put(compoundName[compoundName.length - 1], referenceBinding); - } - resolvedImports[index++] = conflictingType == null - ? new ImportBinding(compoundName, false, importBinding, importReference) - : new ImportConflictBinding(compoundName, importBinding, conflictingType, importReference); + + Binding importBinding = findImport(compoundName, compoundName.length); + if(!importBinding.isValidBinding()) { + continue nextImport; + } + resolvedImports[index++] = new ImportBinding(compoundName, true, importBinding, importReference); + } else { + Binding importBinding = findSingleImport(compoundName); + if(!importBinding.isValidBinding()) { + continue nextImport; + } + ReferenceBinding conflictingType = null; + if(importBinding instanceof MethodBinding) { + conflictingType = (ReferenceBinding) getType(compoundName, compoundName.length); + if(!conflictingType.isValidBinding()) + conflictingType = null; + } + // collisions between an imported static field & a type should be checked according + // to spec... but currently not by javac + if(importBinding instanceof ReferenceBinding || conflictingType != null) { + ReferenceBinding referenceBinding = + conflictingType == null ? (ReferenceBinding) importBinding : conflictingType; + if(importReference.isTypeUseDeprecated(referenceBinding, this)) + problemReporter().deprecatedType(referenceBinding, importReference); + + ReferenceBinding existingType = typesBySimpleNames.get(compoundName[compoundName.length - 1]); + if(existingType != null) { + continue nextImport; + } + typesBySimpleNames.put(compoundName[compoundName.length - 1], referenceBinding); + } + resolvedImports[index++] = + conflictingType == null ? new ImportBinding(compoundName, false, importBinding, importReference) + : new ImportConflictBinding(compoundName, importBinding, conflictingType, + importReference); + } } - } - // shrink resolvedImports... only happens if an error was reported - if (resolvedImports.length > index) - System.arraycopy(resolvedImports, 0, resolvedImports = new ImportBinding[index], 0, index); - imports = resolvedImports; - - int length = imports.length; - this.typeOrPackageCache = new HashtableOfObject(length); - for (int i = 0; i < length; i++) { - ImportBinding binding = imports[i]; - if (!binding.onDemand && binding.resolvedImport instanceof ReferenceBinding || binding instanceof ImportConflictBinding) - this.typeOrPackageCache.put(binding.compoundName[binding.compoundName.length - 1], binding); + // shrink resolvedImports... only happens if an error was reported + if(resolvedImports.length > index) + System.arraycopy(resolvedImports, 0, resolvedImports = new ImportBinding[index], 0, index); + imports = resolvedImports; + + int length = imports.length; + this.typeOrPackageCache = new HashtableOfObject(length); + for(int i = 0; i < length; i++) { + ImportBinding binding = imports[i]; + if(!binding.onDemand && binding.resolvedImport instanceof ReferenceBinding + || binding instanceof ImportConflictBinding) + this.typeOrPackageCache.put(binding.compoundName[binding.compoundName.length - 1], binding); + } } -} -public void faultInTypes() { - faultInImports(); - this.referenceContext.compilationUnitBinding.faultInTypesForFieldsAndMethods(); - for (int i = 0, length = topLevelTypes.length; i < length; i++) - topLevelTypes[i].faultInTypesForFieldsAndMethods(); -} + public void faultInTypes() { + faultInImports(); -//this API is for code assist purpose -public Binding findImport(char[][] compoundName, boolean onDemand) { - if(onDemand) { - return findImport(compoundName, compoundName.length); - } else { - return findSingleImport(compoundName); + this.referenceContext.compilationUnitBinding.faultInTypesForFieldsAndMethods(); + for(int i = 0, length = topLevelTypes.length; i < length; i++) + topLevelTypes[i].faultInTypesForFieldsAndMethods(); } -} -private Binding findImport(char[][] compoundName, int length) { - recordQualifiedReference(compoundName); - - Binding binding = environment.getTopLevelPackage(compoundName[0]); - int i = 1; - foundNothingOrType: if (binding != null) { - PackageBinding packageBinding = (PackageBinding) binding; - while (i < length) { - int type = (i+1==length)?Binding.COMPILATION_UNIT: Binding.PACKAGE; - binding = packageBinding.getTypeOrPackage(compoundName[i++], type); - if (binding == null || !binding.isValidBinding()) { - binding = null; - break foundNothingOrType; + /** + * this API is for code assist purpose + * + * @param compoundName + * @param onDemand + * @return + */ + public Binding findImport(char[][] compoundName, boolean onDemand) { + if(onDemand) { + return findImport(compoundName, compoundName.length); + } else { + return findSingleImport(compoundName); + } + } + + private Binding findImport(char[][] compoundName, int length) { + recordQualifiedReference(compoundName); + + Binding binding = environment.getTopLevelPackage(compoundName[0]); + int i = 1; + foundNothingOrType: if(binding != null) { + PackageBinding packageBinding = (PackageBinding) binding; + while(i < length) { + int type = (i + 1 == length) ? Binding.COMPILATION_UNIT : Binding.PACKAGE; + binding = packageBinding.getTypeOrPackage(compoundName[i++], type); + if(binding == null || !binding.isValidBinding()) { + binding = null; + break foundNothingOrType; + } + if(i == length && (binding instanceof CompilationUnitBinding)) + return binding; + if(!(binding instanceof PackageBinding)) + break foundNothingOrType; + + packageBinding = (PackageBinding) binding; } - if (i==length && (binding instanceof CompilationUnitBinding)) - return binding; - if (!(binding instanceof PackageBinding)) - break foundNothingOrType; + return packageBinding; + } - packageBinding = (PackageBinding) binding; + ReferenceBinding type; + if(binding == null) { + if(environment.defaultPackage == null || compilerOptions().complianceLevel >= ClassFileConstants.JDK1_4) + return new ProblemReferenceBinding(CharOperation.subarray(compoundName, 0, i), null, + ProblemReasons.NotFound); + type = findType(compoundName[0], environment.defaultPackage, environment.defaultPackage); + if(type == null || !type.isValidBinding()) + return new ProblemReferenceBinding(CharOperation.subarray(compoundName, 0, i), null, + ProblemReasons.NotFound); + i = 1; // reset to look for member types inside the default package type + } else { + type = (ReferenceBinding) binding; } - return packageBinding; - } - ReferenceBinding type; - if (binding == null) { - if (environment.defaultPackage == null || compilerOptions().complianceLevel >= ClassFileConstants.JDK1_4) - return new ProblemReferenceBinding(CharOperation.subarray(compoundName, 0, i), null, ProblemReasons.NotFound); - type = findType(compoundName[0], environment.defaultPackage, environment.defaultPackage); - if (type == null || !type.isValidBinding()) - return new ProblemReferenceBinding(CharOperation.subarray(compoundName, 0, i), null, ProblemReasons.NotFound); - i = 1; // reset to look for member types inside the default package type - } else { - type = (ReferenceBinding) binding; + while(i < length) { + if(!type.canBeSeenBy(environment.defaultPackage)) + return new ProblemReferenceBinding(CharOperation.subarray(compoundName, 0, i), type, + ProblemReasons.NotVisible); + + char[] name = compoundName[i++]; + // does not look for inherited member types on purpose, only immediate members + type = type.getMemberType(name); + if(type == null) + return new ProblemReferenceBinding(CharOperation.subarray(compoundName, 0, i), null, + ProblemReasons.NotFound); + } + if(!type.canBeSeenBy(environment.defaultPackage)) + return new ProblemReferenceBinding(compoundName, type, ProblemReasons.NotVisible); + return type; } - while (i < length) { - if (!type.canBeSeenBy(environment.defaultPackage)) - return new ProblemReferenceBinding(CharOperation.subarray(compoundName, 0, i), type, ProblemReasons.NotVisible); + private Binding findSingleImport(char[][] compoundName) { + if(compoundName.length == 1) { + // findType records the reference + // the name cannot be a package + if(environment.defaultPackage == null || compilerOptions().complianceLevel >= ClassFileConstants.JDK1_4) + return new ProblemReferenceBinding(compoundName, null, ProblemReasons.NotFound); + ReferenceBinding typeBinding = + findType(compoundName[0], environment.defaultPackage, environment.defaultPackage); + if(typeBinding == null) + return new ProblemReferenceBinding(compoundName, null, ProblemReasons.NotFound); + return typeBinding; + } - char[] name = compoundName[i++]; - // does not look for inherited member types on purpose, only immediate members - type = type.getMemberType(name); - if (type == null) - return new ProblemReferenceBinding(CharOperation.subarray(compoundName, 0, i), null, ProblemReasons.NotFound); - } - if (!type.canBeSeenBy(environment.defaultPackage)) - return new ProblemReferenceBinding(compoundName, type, ProblemReasons.NotVisible); - return type; -} -private Binding findSingleImport(char[][] compoundName) { - if (compoundName.length == 1) { - // findType records the reference - // the name cannot be a package - if (environment.defaultPackage == null || compilerOptions().complianceLevel >= ClassFileConstants.JDK1_4) - return new ProblemReferenceBinding(compoundName, null, ProblemReasons.NotFound); - ReferenceBinding typeBinding = findType(compoundName[0], environment.defaultPackage, environment.defaultPackage); - if (typeBinding == null) - return new ProblemReferenceBinding(compoundName, null, ProblemReasons.NotFound); - return typeBinding; + return findImport(compoundName, compoundName.length); } - return findImport(compoundName, compoundName.length); -} + MethodBinding findStaticMethod(ReferenceBinding currentType, char[] selector) { + if(!currentType.canBeSeenBy(this)) + return null; + + do { + MethodBinding[] methods = currentType.getMethods(selector); + if(methods != Binding.NO_METHODS) { + for(int i = methods.length; --i >= 0;) { + MethodBinding method = methods[i]; + if(method.isStatic() && method.canBeSeenBy(environment.defaultPackage)) + return method; + } + } -MethodBinding findStaticMethod(ReferenceBinding currentType, char[] selector) { - if (!currentType.canBeSeenBy(this)) + ((SourceTypeBinding) currentType).classScope.connectTypeHierarchy(); + } while((currentType = currentType.getSuperBinding()) != null); return null; + } + + ImportBinding[] getDefaultImports() { + // initialize the default imports if necessary... share the default java.lang.* import + Binding importBinding = environment.defaultPackage; - do { - MethodBinding[] methods = currentType.getMethods(selector); - if (methods != Binding.NO_METHODS) { - for (int i = methods.length; --i >= 0;) { - MethodBinding method = methods[i]; - if (method.isStatic() && method.canBeSeenBy(environment.defaultPackage)) - return method; + // abort if java.lang cannot be found... + if(importBinding == null || !importBinding.isValidBinding()) { + // create a proxy for the missing BinaryType + MissingBinaryTypeBinding missingObject = + environment.cacheMissingBinaryType(JAVA_LANG_OBJECT, this.referenceContext); + importBinding = missingObject.fPackage; + } + ImportBinding systemJSBinding = null; + if(environment.defaultImports != null) { + systemJSBinding = environment.defaultImports[0]; + } else { + systemJSBinding = + new ImportBinding(new char[][] { SystemLibraryLocation.SYSTEM_LIBARAY_NAME }, true, importBinding, + (ImportReference) null); + environment.defaultImports = new ImportBinding[] { systemJSBinding }; + } + + ImportBinding[] defaultImports = null; + String[] contextIncludes = null; + InferrenceProvider[] inferenceProviders = + InferrenceManager.getInstance().getInferenceProviders(this.referenceContext); + if(inferenceProviders != null && inferenceProviders.length > 0) { + for(int i = 0; i < inferenceProviders.length; i++) { + if(contextIncludes == null) { + contextIncludes = inferenceProviders[i].getResolutionConfiguration().getContextIncludes(); + } else { + String[] contextIncludesTemp = + inferenceProviders[0].getResolutionConfiguration().getContextIncludes(); + if(contextIncludesTemp != null) { + String[] contextIncludesOld = contextIncludes; + contextIncludes = new String[contextIncludesTemp.length + contextIncludesOld.length]; + System.arraycopy(contextIncludesOld, 0, contextIncludes, 0, contextIncludesOld.length); + System.arraycopy(contextIncludesTemp, 0, contextIncludes, contextIncludesOld.length - 1, + contextIncludesTemp.length); + } + } } + } - - ((SourceTypeBinding) currentType).classScope.connectTypeHierarchy(); - } while ((currentType = currentType.superclass()) != null); - return null; -} -ImportBinding[] getDefaultImports() { - // initialize the default imports if necessary... share the default java.lang.* import - Binding importBinding = environment.defaultPackage; -// if (importBinding != null) -// importBinding = ((PackageBinding) importBinding).getTypeOrPackage(JAVA_LANG[1]); - - // abort if java.lang cannot be found... - if (importBinding == null || !importBinding.isValidBinding()) { - // create a proxy for the missing BinaryType - MissingBinaryTypeBinding missingObject = environment.cacheMissingBinaryType(JAVA_LANG_OBJECT, this.referenceContext); - importBinding = missingObject.fPackage; + if(contextIncludes != null && contextIncludes.length > 0) { + ArrayList list = new ArrayList(); + list.add(systemJSBinding); + for(int i = 0; i < contextIncludes.length; i++) { + String include = contextIncludes[i]; + if(include != null) { + int index = Util.indexOfJavaLikeExtension(include); + if(index >= 0) + include = include.substring(0, index); + include = include.replace('.', FILENAME_DOT_SUBSTITUTION); + char[][] qualifiedName = CharOperation.splitOn('/', include.toCharArray()); + Binding binding = findImport(qualifiedName, qualifiedName.length); + if(binding.isValidBinding()) { + list.add(new ImportBinding(qualifiedName, true, binding, null)); + } + } + } + defaultImports = (ImportBinding[]) list.toArray(new ImportBinding[list.size()]); + } else + defaultImports = new ImportBinding[] { systemJSBinding }; + return defaultImports; } - ImportBinding systemJSBinding = null; - if (environment.defaultImports != null) - { - systemJSBinding=environment.defaultImports[0]; + + + /** + *

NOTE: NOT Public API

+ * + * @param compoundName + * @param onDemand + * @return + */ + public final Binding getImport(char[][] compoundName, boolean onDemand) { + if(onDemand) + return findImport(compoundName, compoundName.length); + return findSingleImport(compoundName); } - else - { - systemJSBinding=new ImportBinding(new char[][] {SystemLibraryLocation.SYSTEM_LIBARAY_NAME}, true, importBinding, (ImportReference)null); - environment.defaultImports=new ImportBinding[]{systemJSBinding}; + + public int nextCaptureID() { + return this.captureID++; } - - - ImportBinding[] defaultImports=null; - String[] contextIncludes=null; - InferrenceProvider[] inferenceProviders = InferrenceManager.getInstance().getInferenceProviders(this.referenceContext); - if (inferenceProviders!=null &&inferenceProviders.length>0) - { - for(int i = 0; i < inferenceProviders.length; i++) { - if(contextIncludes == null) { - contextIncludes = inferenceProviders[i].getResolutionConfiguration().getContextIncludes(); - } else { - String[] contextIncludesTemp = inferenceProviders[0].getResolutionConfiguration().getContextIncludes(); - if(contextIncludesTemp != null) { - String[] contextIncludesOld = contextIncludes; - contextIncludes = new String[contextIncludesTemp.length + contextIncludesOld.length]; - System.arraycopy(contextIncludesOld, 0, contextIncludes, 0, contextIncludesOld.length); - System.arraycopy(contextIncludesTemp, 0, contextIncludes, contextIncludesOld.length - 1, contextIncludesTemp.length); - } - } - } - - } - if (contextIncludes!=null && contextIncludes.length>0) - { - ArrayList list = new ArrayList(); - list.add(systemJSBinding); - for (int i = 0; i < contextIncludes.length; i++) { - String include=contextIncludes[i]; - if (include!=null) - { - int index=Util.indexOfJavaLikeExtension(include); - if (index>=0) - include=include.substring(0,index); - include=include.replace('.', FILENAME_DOT_SUBSTITUTION); - char [][] qualifiedName=CharOperation.splitOn('/', include.toCharArray()); - Binding binding=findImport(qualifiedName, qualifiedName.length); - if (binding.isValidBinding()) - { - list.add(new ImportBinding(qualifiedName, true, binding, null)); + /** + * Answer the problem reporter to use for raising new problems. + * + * Note that as a side-effect, this updates the current reference context + * (unit, type or method) in case the problem handler decides it is necessary + * to abort. + */ + public ProblemReporter problemReporter() { + ProblemReporter problemReporter = referenceContext.problemReporter; + problemReporter.referenceContext = referenceContext; + return problemReporter; + } + + /** + * What do we hold onto: + * + * 1. when we resolve 'a.b.c', say we keep only 'a.b.c' + * & when we fail to resolve 'c' in 'a.b', lets keep 'a.b.c' + * THEN when we come across a new/changed/removed item named 'a.b.c', + * we would find all references to 'a.b.c' + * -> This approach fails because every type is resolved in every onDemand import to + * detect collision cases... so the references could be 10 times bigger than necessary. + * + * 2. when we resolve 'a.b.c', lets keep 'a.b' & 'c' + * & when we fail to resolve 'c' in 'a.b', lets keep 'a.b' & 'c' + * THEN when we come across a new/changed/removed item named 'a.b.c', + * we would find all references to 'a.b' & 'c' + * -> This approach does not have a space problem but fails to handle collision cases. + * What happens if a type is added named 'a.b'? We would search for 'a' & 'b' but + * would not find a match. + * + * 3. when we resolve 'a.b.c', lets keep 'a', 'a.b' & 'a', 'b', 'c' + * & when we fail to resolve 'c' in 'a.b', lets keep 'a', 'a.b' & 'a', 'b', 'c' + * THEN when we come across a new/changed/removed item named 'a.b.c', + * we would find all references to 'a.b' & 'c' + * OR 'a.b' -> 'a' & 'b' + * OR 'a' -> '' & 'a' + * -> As long as each single char[] is interned, we should not have a space problem + * and can handle collision cases. + * + * 4. when we resolve 'a.b.c', lets keep 'a.b' & 'a', 'b', 'c' + * & when we fail to resolve 'c' in 'a.b', lets keep 'a.b' & 'a', 'b', 'c' + * THEN when we come across a new/changed/removed item named 'a.b.c', + * we would find all references to 'a.b' & 'c' + * OR 'a.b' -> 'a' & 'b' in the simple name collection + * OR 'a' -> 'a' in the simple name collection + * -> As long as each single char[] is interned, we should not have a space problem + * and can handle collision cases. + */ + void recordQualifiedReference(char[][] qualifiedName) { + if(qualifiedReferences == null) + return; // not recording dependencies + + int length = qualifiedName.length; + if(length > 1) { + while(!qualifiedReferences.contains(qualifiedName)) { + qualifiedReferences.add(qualifiedName); + if(length == 2) { + recordSimpleReference(qualifiedName[0]); + recordSimpleReference(qualifiedName[1]); + return; + } + length--; + recordSimpleReference(qualifiedName[length]); + System.arraycopy(qualifiedName, 0, qualifiedName = new char[length][], 0, length); } + } else if(length == 1) { + recordSimpleReference(qualifiedName[0]); } - } - defaultImports = ( ImportBinding[])list.toArray( new ImportBinding[list.size()]); - } - else - defaultImports = new ImportBinding[] {systemJSBinding}; - return defaultImports ; -} -// NOT Public API -public final Binding getImport(char[][] compoundName, boolean onDemand) { - if (onDemand) - return findImport(compoundName, compoundName.length); - return findSingleImport(compoundName); -} + } -public int nextCaptureID() { - return this.captureID++; -} + void recordReference(char[][] qualifiedEnclosingName, char[] simpleName) { + recordQualifiedReference(qualifiedEnclosingName); + recordSimpleReference(simpleName); + } -/* Answer the problem reporter to use for raising new problems. -* -* Note that as a side-effect, this updates the current reference context -* (unit, type or method) in case the problem handler decides it is necessary -* to abort. -*/ - -public ProblemReporter problemReporter() { - ProblemReporter problemReporter = referenceContext.problemReporter; - problemReporter.referenceContext = referenceContext; - return problemReporter; -} + void recordReference(ReferenceBinding type, char[] simpleName) { + ReferenceBinding actualType = typeToRecord(type); + if(actualType != null) + recordReference(actualType.compoundName, simpleName); + } -/* -What do we hold onto: - -1. when we resolve 'a.b.c', say we keep only 'a.b.c' - & when we fail to resolve 'c' in 'a.b', lets keep 'a.b.c' -THEN when we come across a new/changed/removed item named 'a.b.c', - we would find all references to 'a.b.c' --> This approach fails because every type is resolved in every onDemand import to - detect collision cases... so the references could be 10 times bigger than necessary. - -2. when we resolve 'a.b.c', lets keep 'a.b' & 'c' - & when we fail to resolve 'c' in 'a.b', lets keep 'a.b' & 'c' -THEN when we come across a new/changed/removed item named 'a.b.c', - we would find all references to 'a.b' & 'c' --> This approach does not have a space problem but fails to handle collision cases. - What happens if a type is added named 'a.b'? We would search for 'a' & 'b' but - would not find a match. - -3. when we resolve 'a.b.c', lets keep 'a', 'a.b' & 'a', 'b', 'c' - & when we fail to resolve 'c' in 'a.b', lets keep 'a', 'a.b' & 'a', 'b', 'c' -THEN when we come across a new/changed/removed item named 'a.b.c', - we would find all references to 'a.b' & 'c' -OR 'a.b' -> 'a' & 'b' -OR 'a' -> '' & 'a' --> As long as each single char[] is interned, we should not have a space problem - and can handle collision cases. - -4. when we resolve 'a.b.c', lets keep 'a.b' & 'a', 'b', 'c' - & when we fail to resolve 'c' in 'a.b', lets keep 'a.b' & 'a', 'b', 'c' -THEN when we come across a new/changed/removed item named 'a.b.c', - we would find all references to 'a.b' & 'c' -OR 'a.b' -> 'a' & 'b' in the simple name collection -OR 'a' -> 'a' in the simple name collection --> As long as each single char[] is interned, we should not have a space problem - and can handle collision cases. -*/ -void recordQualifiedReference(char[][] qualifiedName) { - if (qualifiedReferences == null) return; // not recording dependencies - - int length = qualifiedName.length; - if (length > 1) { - while (!qualifiedReferences.contains(qualifiedName)) { - qualifiedReferences.add(qualifiedName); - if (length == 2) { - recordSimpleReference(qualifiedName[0]); - recordSimpleReference(qualifiedName[1]); - return; - } - length--; - recordSimpleReference(qualifiedName[length]); - System.arraycopy(qualifiedName, 0, qualifiedName = new char[length][], 0, length); - } - } else if (length == 1) { - recordSimpleReference(qualifiedName[0]); + void recordSimpleReference(char[] simpleName) { + if(simpleNameReferences == null) + return; // not recording dependencies + + if(!simpleNameReferences.contains(simpleName)) + simpleNameReferences.add(simpleName); } -} -void recordReference(char[][] qualifiedEnclosingName, char[] simpleName) { - recordQualifiedReference(qualifiedEnclosingName); - recordSimpleReference(simpleName); -} -void recordReference(ReferenceBinding type, char[] simpleName) { - ReferenceBinding actualType = typeToRecord(type); - if (actualType != null) - recordReference(actualType.compoundName, simpleName); -} -void recordSimpleReference(char[] simpleName) { - if (simpleNameReferences == null) return; // not recording dependencies - if (!simpleNameReferences.contains(simpleName)) - simpleNameReferences.add(simpleName); -} -void recordSuperTypeReference(TypeBinding type) { - if (referencedSuperTypes == null) return; // not recording dependencies + void recordSuperTypeReference(TypeBinding type) { + if(referencedSuperTypes == null) + return; // not recording dependencies - ReferenceBinding actualType = typeToRecord(type); - if (actualType != null && !referencedSuperTypes.containsIdentical(actualType)) - referencedSuperTypes.add(actualType); -} -public void recordTypeConversion(TypeBinding superType, TypeBinding subType) { - recordSuperTypeReference(subType); // must record the hierarchy of the subType that is converted to the superType -} -void recordTypeReference(TypeBinding type) { - if (referencedTypes == null) return; // not recording dependencies + ReferenceBinding actualType = typeToRecord(type); + if(actualType != null && !referencedSuperTypes.containsIdentical(actualType)) + referencedSuperTypes.add(actualType); + } - ReferenceBinding actualType = typeToRecord(type); - if (actualType != null && !referencedTypes.containsIdentical(actualType)) - referencedTypes.add(actualType); -} -void recordTypeReferences(TypeBinding[] types) { - if (referencedTypes == null) return; // not recording dependencies - if (types == null || types.length == 0) return; - - for (int i = 0, max = types.length; i < max; i++) { - // No need to record supertypes of method arguments & thrown exceptions, just the compoundName - // If a field/method is retrieved from such a type then a separate call does the job - ReferenceBinding actualType = typeToRecord(types[i]); - if (actualType != null && !referencedTypes.containsIdentical(actualType)) + public void recordTypeConversion(TypeBinding superType, TypeBinding subType) { + // must record the hierarchy of the subType that is converted to the superType + recordSuperTypeReference(subType); + } + + void recordTypeReference(TypeBinding type) { + if(referencedTypes == null) + return; // not recording dependencies + + ReferenceBinding actualType = typeToRecord(type); + if(actualType != null && !referencedTypes.containsIdentical(actualType)) referencedTypes.add(actualType); } -} -Binding resolveSingleImport(ImportBinding importBinding) { - if (importBinding.resolvedImport == null) { - importBinding.resolvedImport = findSingleImport(importBinding.compoundName); - if (!importBinding.resolvedImport.isValidBinding() || importBinding.resolvedImport instanceof PackageBinding) { - if (this.imports != null) { - ImportBinding[] newImports = new ImportBinding[imports.length - 1]; - for (int i = 0, n = 0, max = this.imports.length; i < max; i++) - if (this.imports[i] != importBinding) - newImports[n++] = this.imports[i]; - this.imports = newImports; - } - return null; + + void recordTypeReferences(TypeBinding[] types) { + if(referencedTypes == null) + return; // not recording dependencies + if(types == null || types.length == 0) + return; + + for(int i = 0, max = types.length; i < max; i++) { + // No need to record supertypes of method arguments & thrown exceptions, just the + // compoundName + // If a field/method is retrieved from such a type then a separate call does the job + ReferenceBinding actualType = null; + if(types[i] != null) + actualType = typeToRecord(types[i]); + if(actualType != null && !referencedTypes.containsIdentical(actualType)) + referencedTypes.add(actualType); } } - return importBinding.resolvedImport; -} -public void storeDependencyInfo() { - // add the type hierarchy of each referenced supertype - // cannot do early since the hierarchy may not be fully resolved - for (int i = 0; i < referencedSuperTypes.size; i++) { // grows as more types are added - ReferenceBinding type = (ReferenceBinding) referencedSuperTypes.elementAt(i); - if (!referencedTypes.containsIdentical(type)) - referencedTypes.add(type); - - if (!type.isLocalType()) { - ReferenceBinding enclosing = type.enclosingType(); - if (enclosing != null) - recordSuperTypeReference(enclosing); + + Binding resolveSingleImport(ImportBinding importBinding) { + if(importBinding.resolvedImport == null) { + importBinding.resolvedImport = findSingleImport(importBinding.compoundName); + if(!importBinding.resolvedImport.isValidBinding() || importBinding.resolvedImport instanceof PackageBinding) { + if(this.imports != null) { + ImportBinding[] newImports = new ImportBinding[imports.length - 1]; + for(int i = 0, n = 0, max = this.imports.length; i < max; i++) + if(this.imports[i] != importBinding) + newImports[n++] = this.imports[i]; + this.imports = newImports; + } + return null; + } } - ReferenceBinding superclass = type.superclass(); - if (superclass != null) - recordSuperTypeReference(superclass); + return importBinding.resolvedImport; } - for (int i = 0, l = referencedTypes.size; i < l; i++) { - ReferenceBinding type = (ReferenceBinding) referencedTypes.elementAt(i); - if (type instanceof MultipleTypeBinding) - { - ReferenceBinding[] types = ((MultipleTypeBinding)type).types; - for (int j = 0; j < types.length; j++) { - if (!types[j].isLocalType()) - recordQualifiedReference(types[j].isMemberType() - ? CharOperation.splitOn('.', types[j].readableName()) - : types[j].compoundName); - + public void storeDependencyInfo() { + // add the type hierarchy of each referenced supertype + // cannot do early since the hierarchy may not be fully resolved + for(int i = 0; i < referencedSuperTypes.size; i++) { // grows as more types are added + ReferenceBinding type = (ReferenceBinding) referencedSuperTypes.elementAt(i); + if(!referencedTypes.containsIdentical(type)) + referencedTypes.add(type); + + if(!type.isLocalType()) { + ReferenceBinding enclosing = type.enclosingType(); + if(enclosing != null) + recordSuperTypeReference(enclosing); } + ReferenceBinding superclass = type.getSuperBinding(); + if(superclass != null) + recordSuperTypeReference(superclass); + } + + for(int i = 0, l = referencedTypes.size; i < l; i++) { + ReferenceBinding type = (ReferenceBinding) referencedTypes.elementAt(i); + if(type instanceof MultipleTypeBinding) { + ReferenceBinding[] types = ((MultipleTypeBinding) type).types; + for(int j = 0; j < types.length; j++) { + if(!types[j].isLocalType()) + recordQualifiedReference(types[j].isMemberType() ? CharOperation.splitOn('.', + types[j].readableName()) : types[j].compoundName); + + } + } else if(!type.isLocalType()) + recordQualifiedReference(type.isMemberType() ? CharOperation.splitOn('.', type.readableName()) + : type.compoundName); } - else - if (!type.isLocalType()) - recordQualifiedReference(type.isMemberType() - ? CharOperation.splitOn('.', type.readableName()) - : type.compoundName); + + int size = qualifiedReferences.size; + char[][][] qualifiedRefs = new char[size][][]; + for(int i = 0; i < size; i++) + qualifiedRefs[i] = qualifiedReferences.elementAt(i); + referenceContext.compilationResult.qualifiedReferences = qualifiedRefs; + + size = simpleNameReferences.size; + char[][] simpleRefs = new char[size][]; + for(int i = 0; i < size; i++) + simpleRefs[i] = simpleNameReferences.elementAt(i); + referenceContext.compilationResult.simpleNameReferences = simpleRefs; } - int size = qualifiedReferences.size; - char[][][] qualifiedRefs = new char[size][][]; - for (int i = 0; i < size; i++) - qualifiedRefs[i] = qualifiedReferences.elementAt(i); - referenceContext.compilationResult.qualifiedReferences = qualifiedRefs; - - size = simpleNameReferences.size; - char[][] simpleRefs = new char[size][]; - for (int i = 0; i < size; i++) - simpleRefs[i] = simpleNameReferences.elementAt(i); - referenceContext.compilationResult.simpleNameReferences = simpleRefs; -} -public String toString() { - return "--- JavaScriptUnit Scope : " + new String(referenceContext.getFileName()); //$NON-NLS-1$ -} -private ReferenceBinding typeToRecord(TypeBinding type) { - while (type.isArrayType()) - type = ((ArrayBinding) type).leafComponentType; + public String toString() { + return "--- JavaScriptUnit Scope : " + new String(referenceContext.getFileName()); //$NON-NLS-1$ + } + + private ReferenceBinding typeToRecord(TypeBinding type) { + while(type.isArrayType()) + type = ((ArrayBinding) type).leafComponentType; - switch (type.kind()) { - case Binding.BASE_TYPE : + switch(type.kind()) { + case Binding.BASE_TYPE: + return null; + } + if(type instanceof CompilationUnitBinding) + return null; + ReferenceBinding refType = (ReferenceBinding) type; + if(refType.isLocalType()) return null; + return refType; } - if (type instanceof CompilationUnitBinding) - return null; - ReferenceBinding refType = (ReferenceBinding) type; - if (refType.isLocalType()) return null; - return refType; -} -public void verifyMethods(MethodVerifier verifier) { - for (int i = 0, length = topLevelTypes.length; i < length; i++) - topLevelTypes[i].verifyMethods(verifier); - } - -public void cleanup() -{ - - if (this.referencedTypes!=null) - for (int i = 0, l = referencedTypes.size; i < l; i++) { - Object obj=referencedTypes.elementAt(i); - if (obj instanceof SourceTypeBinding) - { - SourceTypeBinding type = (SourceTypeBinding) obj; - type.cleanup(); - } + + public void cleanup() { + + if(this.referencedTypes != null) + for(int i = 0, l = referencedTypes.size; i < l; i++) { + Object obj = referencedTypes.elementAt(i); + if(obj instanceof SourceTypeBinding) { + SourceTypeBinding type = (SourceTypeBinding) obj; + type.cleanup(); + } + } } -} -public void addExternalVar(LocalVariableBinding binding) { - externalCompilationUnits.add(binding.declaringScope.compilationUnitScope()); -} + public void addExternalVar(LocalVariableBinding binding) { + externalCompilationUnits.add(binding.declaringScope.compilationUnitScope()); + } + + /** + * @return the shouldBuildGlobalSuperType + */ + public boolean shouldBuildGlobalSuperType() { + return shouldBuildGlobalSuperType; + } + + /** + * @param shouldBuildGlobalSuperType the shouldBuildGlobalSuperType to set + */ + public void setShouldBuildGlobalSuperType(boolean shouldBuild) { + this.shouldBuildGlobalSuperType = shouldBuild; + } + + } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ExtraCompilerModifiers.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ExtraCompilerModifiers.java index f097e1ce..12e7fc93 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ExtraCompilerModifiers.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ExtraCompilerModifiers.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/FieldBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/FieldBinding.java index ab6daf66..c183e376 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/FieldBinding.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/FieldBinding.java @@ -61,15 +61,16 @@ public final boolean canBeSeenBy(PackageBinding invocationPackage) { */ public final boolean canBeSeenBy(TypeBinding receiverType, InvocationSite invocationSite, Scope scope) { - if (isPublic() || !JavaScriptCore.IS_ECMASCRIPT4) return true; + if (isPublic() || !JavaScriptCore.IS_ECMASCRIPT4) { + return true; + } SourceTypeBinding invocationType = scope.enclosingSourceType(); - if (invocationType == declaringClass && invocationType == receiverType) return true; - - if( (receiverType instanceof SourceTypeBinding) && ((SourceTypeBinding)receiverType).nextType!=null) { - SourceTypeBinding combinedBinding = (SourceTypeBinding) receiverType; - if (combinedBinding.contains(declaringClass) && combinedBinding.contains(invocationType)) return true; - + if(receiverType instanceof SourceTypeBinding) { + SourceTypeBinding receiverSourceType = (SourceTypeBinding)receiverType; + if (receiverSourceType.isLinkedType(declaringClass) && receiverSourceType.isLinkedType(invocationType)) { + return true; + } } if (invocationType == null) // static import call @@ -152,7 +153,7 @@ public final boolean canBeSeenBy(TypeBinding receiverType, InvocationSite invoca PackageBinding currentPackage = currentType.fPackage; // package could be null for wildcards/intersection types, ignore and recurse in superclass if (currentPackage != null && currentPackage != declaringPackage) return false; - } while ((currentType = currentType.superclass()) != null); + } while ((currentType = currentType.getSuperBinding()) != null); return false; } /* diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/FunctionTypeBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/FunctionTypeBinding.java index e1fc3ae0..0418b81d 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/FunctionTypeBinding.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/FunctionTypeBinding.java @@ -125,18 +125,13 @@ public class FunctionTypeBinding extends SourceTypeBinding { } - public ReferenceBinding superclass() { - return functionTypeBinding.superclass(); + public ReferenceBinding getSuperBinding() { + return functionTypeBinding.getSuperBinding(); } public String toString() { return functionTypeBinding.toString(); } - - void verifyMethods(MethodVerifier verifier) { - functionTypeBinding.verifyMethods(verifier); - } - public boolean isFunctionType() { diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/GlobalBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/GlobalBinding.java index 12a3f4a9..380573a8 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/GlobalBinding.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/GlobalBinding.java @@ -1,3 +1,13 @@ +/******************************************************************************* + * Copyright (c) 2011 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ package org.eclipse.wst.jsdt.internal.compiler.lookup; import org.eclipse.wst.jsdt.internal.compiler.util.HashtableOfBinding; diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ImportBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ImportBinding.java index 1dd2bfe1..de5d5e2f 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ImportBinding.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ImportBinding.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/LibraryAPIsBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/LibraryAPIsBinding.java index 432cc387..a5feefad 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/LibraryAPIsBinding.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/LibraryAPIsBinding.java @@ -56,7 +56,7 @@ public class LibraryAPIsBinding extends SourceTypeBinding { } } shortName=fileName; - this.path=new char[0]; + this.path=CharOperation.NO_CHAR; } public int kind() { diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/LibraryAPIsScope.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/LibraryAPIsScope.java index 6cd0d4db..2fbb4cb2 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/LibraryAPIsScope.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/LibraryAPIsScope.java @@ -46,7 +46,7 @@ public LibraryAPIsScope(LibraryAPIs apis, LookupEnvironment environment) { translations.put("string".toCharArray(), "String".toCharArray()); translations.put("array".toCharArray(), "Array".toCharArray()); - CompilationResult result = new CompilationResult(apis.fileName,new char[][]{},0,0,0); + CompilationResult result = new CompilationResult(apis.fileName, new char[][]{},0,0,0); CompilationUnitDeclaration unit = new CompilationUnitDeclaration(environment.problemReporter,result,0); unit.scope=this; this.referenceContext=unit; diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/LocalTypeBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/LocalTypeBinding.java index 2e7dbbe6..1e75c669 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/LocalTypeBinding.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/LocalTypeBinding.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -38,7 +38,7 @@ public LocalTypeBinding(ClassScope scope, SourceTypeBinding enclosingType, CaseS MethodScope methodScope = scope.enclosingMethodScope(); AbstractMethodDeclaration declaration = methodScope.referenceMethod(); if (declaration != null) { - this.enclosingMethod = declaration.binding; + this.enclosingMethod = declaration.getBinding(); } } /* Record a dependency onto a source target type which may be altered @@ -108,25 +108,10 @@ ArrayBinding createArrayType(int dimensionCount, LookupEnvironment lookupEnviron return localArrayBindings[length] = new ArrayBinding(this, dimensionCount, lookupEnvironment); } -/* - * Overriden for code assist. In this case, the constantPoolName() has not been computed yet. - * Slam the source name so that the signature is syntactically correct. - * (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=99686) - */ -public char[] genericTypeSignature() { - if (this.genericReferenceTypeSignature == null && constantPoolName() == null) { - if (isAnonymousType()) - setConstantPoolName(superclass().sourceName()); - else - setConstantPoolName(sourceName()); - } - return super.signature(); -} - public char[] readableName() /*java.lang.Object, p.X */ { char[] readableName; if (isAnonymousType()) { - readableName = CharOperation.concat(TypeConstants.ANONYM_PREFIX, superclass.readableName(), TypeConstants.ANONYM_SUFFIX); + readableName = CharOperation.concat(TypeConstants.ANONYM_PREFIX, this.getSuperBinding0().readableName(), TypeConstants.ANONYM_SUFFIX); } else if (isMemberType()) { readableName = CharOperation.concat(enclosingType().readableName(), this.sourceName, '.'); } else { @@ -138,7 +123,7 @@ public char[] readableName() /*java.lang.Object, p.X */ { public char[] shortReadableName() /*Object*/ { char[] shortReadableName; if (isAnonymousType()) { - shortReadableName = CharOperation.concat(TypeConstants.ANONYM_PREFIX, superclass.shortReadableName(), TypeConstants.ANONYM_SUFFIX); + shortReadableName = CharOperation.concat(TypeConstants.ANONYM_PREFIX, this.getSuperBinding0().shortReadableName(), TypeConstants.ANONYM_SUFFIX); } else if (isMemberType()) { shortReadableName = CharOperation.concat(enclosingType().shortReadableName(), sourceName, '.'); } else { @@ -163,7 +148,7 @@ public void setConstantPoolName(char[] computedConstantPoolName) /* java/lang/Ob public char[] signature() { if (this.signature == null && constantPoolName() == null) { if (isAnonymousType()) - setConstantPoolName(superclass().sourceName()); + setConstantPoolName(getSuperBinding().sourceName()); else setConstantPoolName(sourceName()); } @@ -171,7 +156,7 @@ public char[] signature() { } public char[] sourceName() { if (isAnonymousType()) { - return CharOperation.concat(TypeConstants.ANONYM_PREFIX, superclass.sourceName(), TypeConstants.ANONYM_SUFFIX); + return CharOperation.concat(TypeConstants.ANONYM_PREFIX, this.getSuperBinding0().sourceName(), TypeConstants.ANONYM_SUFFIX); } else return sourceName; } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/LocalVariableBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/LocalVariableBinding.java index 8b4dd299..c88a5b2c 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/LocalVariableBinding.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/LocalVariableBinding.java @@ -70,28 +70,38 @@ public class LocalVariableBinding extends VariableBinding { if (scope instanceof CompilationUnitScope) { CompilationUnitScope compilationUnitScope = (CompilationUnitScope) scope; - buffer.append(compilationUnitScope.referenceContext.compilationUnitBinding.computeUniqueKey(false)); + buffer.append(compilationUnitScope.referenceContext.compilationUnitBinding + .computeUniqueKey(false)); } else { ReferenceContext referenceContext = null; - MethodScope methodScope = scope instanceof MethodScope ? (MethodScope) scope : scope.enclosingMethodScope(); + MethodScope methodScope = scope instanceof MethodScope ? (MethodScope) scope + : scope.enclosingMethodScope(); if (methodScope != null) { referenceContext = methodScope.referenceContext; } else - referenceContext = scope.enclosingCompilationUnit().scope.referenceCompilationUnit(); + referenceContext = scope.enclosingCompilationUnit().scope + .referenceCompilationUnit(); if (referenceContext instanceof AbstractMethodDeclaration) { - MethodBinding methodBinding = ((AbstractMethodDeclaration) referenceContext).binding; + MethodBinding methodBinding = ((AbstractMethodDeclaration) referenceContext).getBinding(); if (methodBinding != null) { - buffer.append(methodBinding.computeUniqueKey(false/*not a leaf*/)); + buffer.append(methodBinding.computeUniqueKey(false/* + * not a + * leaf + */)); } } else if (referenceContext instanceof TypeDeclaration) { TypeBinding typeBinding = ((TypeDeclaration) referenceContext).binding; if (typeBinding != null) { - buffer.append(typeBinding.computeUniqueKey(false/*not a leaf*/)); + buffer.append(typeBinding.computeUniqueKey(false/* + * not a + * leaf + */)); } } else if (referenceContext instanceof CompilationUnitDeclaration) { CompilationUnitBinding compilationUnitBinding = ((CompilationUnitDeclaration) referenceContext).compilationUnitBinding; if (compilationUnitBinding != null) { - buffer.append(compilationUnitBinding.computeUniqueKey(false/*not a leaf*/)); + buffer.append(compilationUnitBinding + .computeUniqueKey(false/* not a leaf */)); } } } @@ -99,6 +109,7 @@ public class LocalVariableBinding extends VariableBinding { getScopeKey(scope, buffer); } + // variable name buffer.append('#'); buffer.append(this.name); diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/LookupEnvironment.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/LookupEnvironment.java index 31bf3f51..427f4271 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/LookupEnvironment.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/LookupEnvironment.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -62,948 +62,1095 @@ public class LookupEnvironment implements ProblemReasons, TypeConstants { public ITypeRequestor typeRequestor; private ArrayBinding[][] uniqueArrayBindings; - public CompilationUnitDeclaration unitBeingCompleted = null; // only set while completing units - public Object missingClassFileLocation = null; // only set when resolving certain references, to help locating problems + public CompilationUnitDeclaration unitBeingCompleted = null; // only set + // while completing units + public Object missingClassFileLocation = null; // only set when resolving + // certain references, to help locating problems private CompilationUnitDeclaration[] units = new CompilationUnitDeclaration[4]; private MethodVerifier verifier; - SimpleSetOfCharArray acceptedCompilationUnits=new SimpleSetOfCharArray(); + SimpleSetOfCharArray acceptedCompilationUnits = new SimpleSetOfCharArray(); private boolean fAddingUnits; - Stack fAskingForTypeBinding = new Stack(); - - -public LookupEnvironment(ITypeRequestor typeRequestor, CompilerOptions globalOptions, ProblemReporter problemReporter, INameEnvironment nameEnvironment) { - this.typeRequestor = typeRequestor; - this.globalOptions = globalOptions; - this.problemReporter = problemReporter; - this.defaultPackage = new PackageBinding(this); // assume the default package always exists - this.defaultImports = null; - this.nameEnvironment = nameEnvironment; - this.knownPackages = new HashtableOfPackage(); - this.uniqueArrayBindings = new ArrayBinding[5][]; - this.uniqueArrayBindings[0] = new ArrayBinding[50]; // start off the most common 1 dimension array @ 50 - this.accessRestrictions = new HashMap(3); -} - -/** - * Ask the name environment for a type which corresponds to the compoundName. - * Answer null if the name cannot be found. - */ - -public ReferenceBinding askForType(char[][] compoundName) { - NameEnvironmentAnswer answer = nameEnvironment.findType(compoundName,this.typeRequestor); - if (answer == null) - return null; + Stack fAskingForTypeBinding = new CharArrayStack(); + + public boolean shouldBuildFieldsAndMethods = true; + + + public LookupEnvironment(ITypeRequestor typeRequestor, CompilerOptions globalOptions, ProblemReporter problemReporter, INameEnvironment nameEnvironment) { + this.typeRequestor = typeRequestor; + this.globalOptions = globalOptions; + this.problemReporter = problemReporter; + this.defaultPackage = new PackageBinding(this); // assume the default + // package always exists + this.defaultImports = null; + this.nameEnvironment = nameEnvironment; + this.knownPackages = new HashtableOfPackage(); + this.uniqueArrayBindings = new ArrayBinding[5][]; + this.uniqueArrayBindings[0] = new ArrayBinding[50]; // start off the + // most common 1 dimension array @ 50 + this.accessRestrictions = new HashMap(3); + } - if (answer.isBinaryType()) - // the type was found as a .class file - typeRequestor.accept(answer.getBinaryType(), computePackageFrom(compoundName), answer.getAccessRestriction()); - else if (answer.isCompilationUnit()) { - ICompilationUnit compilationUnit = answer.getCompilationUnit(); -// if (!acceptedCompilationUnits.includes(compilationUnit.getFileName())) - { - // the type was found as a .js file, try to build it then search the cache + /** + * Ask the name environment for a type which corresponds to the + * compoundName. Answer null if the name cannot be found. + */ + public ReferenceBinding askForType(char[][] compoundName) { + NameEnvironmentAnswer answer = nameEnvironment.findType(compoundName, this.typeRequestor); + if (answer == null) { + return null; + } + + if (answer.isBinaryType()) { + // the type was found as a .class file + typeRequestor.accept(answer.getBinaryType(), computePackageFrom(compoundName), answer.getAccessRestriction()); + } else if (answer.isCompilationUnit()) { + ICompilationUnit compilationUnit = answer.getCompilationUnit(); + + // the type was found as a .js file, try to build it then search the cache acceptedCompilationUnits.add(compilationUnit.getFileName()); typeRequestor.accept(compilationUnit, answer.getAccessRestriction()); - } - } else if (answer.isSourceType()) - // the type was found as a source model - typeRequestor.accept(answer.getSourceTypes(), computePackageFrom(compoundName), answer.getAccessRestriction()); - else if (answer.isMetaData()) - { - LibraryAPIs metadata= answer.getLibraryMetadata(); - //if (!acceptedCompilationUnits.includes(metadata.fileName)) - //{ - // the type was found as a .js file, try to build it then search the cache - acceptedCompilationUnits.add(metadata.fileName); - typeRequestor.accept(metadata); - //} + } else if (answer.isSourceType()) { + // the type was found as a source model + typeRequestor.accept(answer.getSourceTypes(), computePackageFrom(compoundName), answer.getAccessRestriction()); + } else if (answer.isMetaData()) { + LibraryAPIs metadata = answer.getLibraryMetadata(); + // the type was found as a .js file, try to build it then search the cache + acceptedCompilationUnits.add(metadata.fileName); + typeRequestor.accept(metadata); } - - return getCachedType(compoundName); -} -/* Ask the oracle for a type named name in the packageBinding. -* Answer null if the name cannot be found. -*/ + return getCachedType(compoundName); + } -ReferenceBinding askForType(PackageBinding packageBinding, char[] name) { - return (ReferenceBinding)askForBinding(packageBinding, name, Binding.TYPE|Binding.PACKAGE); -} + /** + * Ask the oracle for a type named name in the packageBinding. Answer null if + * the name cannot be found. + */ + ReferenceBinding askForType(PackageBinding packageBinding, char[] name) { + return (ReferenceBinding) askForBinding(packageBinding, name, Binding.TYPE | Binding.PACKAGE); + } + void addUnitsContainingBindings(char[][] types, int kind, String excludePath) { + if (fAddingUnits) { + return; + } + fAddingUnits = true; + try { + // set used for performance reasons, prevents building the same file multiple times for the + // same set of input types. + SimpleSetOfCharArray currentAcceptedCompilationUnits = new SimpleSetOfCharArray(); + for (int i = 0; i < types.length; i++) { + //skip bindings that have already asked for to avoid infinite recursion + if((kind & Binding.TYPE) > 1 && this.alreadyAskedForBinding(types[i])) { + continue; + } + + NameEnvironmentAnswer answer = nameEnvironment.findBinding(types[i], defaultPackage.compoundName, kind, this.typeRequestor, true, excludePath); + if (answer == null) + continue; + + if (answer.isBinaryType()) + // the type was found as a .class file + typeRequestor.accept(answer.getBinaryType(), defaultPackage, answer.getAccessRestriction()); + else if (answer.isSourceType()) + // the type was found as a source model + typeRequestor.accept(answer.getSourceTypes(), defaultPackage, answer.getAccessRestriction()); + else if (answer.isCompilationUnit()) { + ICompilationUnit compilationUnit = answer.getCompilationUnit(); + + /* + * the type was found as a .js file, try to build it then + * search the cache + */ + acceptedCompilationUnits.add(compilationUnit.getFileName()); + if (typeRequestor instanceof ITypeRequestor2) { + ((ITypeRequestor2) typeRequestor).accept(compilationUnit, types, answer.getAccessRestriction()); + } else { + typeRequestor.accept(compilationUnit, answer.getAccessRestriction()); + } -void addUnitsContainingBindings(char[][] types, int kind, String excludePath) { - if(fAddingUnits)return; - if (types.length == 1 && (kind & Binding.TYPE) > 1 && !fAskingForTypeBinding.isEmpty() && CharOperation.equals(types[0], (char[])fAskingForTypeBinding.peek())) - return; + } + else if (answer.isCompilationUnits()) { + ICompilationUnit[] compilationUnits = answer.getCompilationUnits(); + for (int j = 0; j < compilationUnits.length; j++) { + // the type was found as a .js file, try to build it then search the cache + acceptedCompilationUnits.add(compilationUnits[j].getFileName()); + if (!currentAcceptedCompilationUnits.includes(compilationUnits[j].getFileName())) { + currentAcceptedCompilationUnits.add(compilationUnits[j].getFileName()); + if (typeRequestor instanceof ITypeRequestor2) { + ((ITypeRequestor2) typeRequestor).accept(compilationUnits[j], types, answer.getAccessRestriction()); + } else { + typeRequestor.accept(compilationUnits[j], answer.getAccessRestriction()); + } + } + } + } + } + } + finally { + fAddingUnits = false; + } + } + - fAddingUnits=true; - try{ - for (int i = 0; i < types.length; i++) { - NameEnvironmentAnswer answer = nameEnvironment.findBinding(types[i], defaultPackage.compoundName, kind, this.typeRequestor, true, excludePath); + void addUnitsContainingBinding(PackageBinding packageBinding, char[] type, int mask, String excludePath) { + if (packageBinding == null) { + if (defaultPackage == null) { + return; + } + packageBinding = defaultPackage; + } + NameEnvironmentAnswer answer = nameEnvironment.findBinding(type, packageBinding.compoundName, mask, this.typeRequestor, true, excludePath); if (answer == null) - continue; + return; + - if (answer.isBinaryType()) + if (answer.isBinaryType()) { // the type was found as a .class file - typeRequestor.accept(answer.getBinaryType(), defaultPackage, answer.getAccessRestriction()); - else if (answer.isSourceType()) - // the type was found as a source model - typeRequestor.accept(answer.getSourceTypes(), defaultPackage, answer.getAccessRestriction()); - else if (answer.isCompilationUnit()) { + typeRequestor.accept(answer.getBinaryType(), packageBinding, answer.getAccessRestriction()); + } else if (answer.isCompilationUnit()) { ICompilationUnit compilationUnit = answer.getCompilationUnit(); -// if (!acceptedCompilationUnits.includes(compilationUnit.getFileName())) { - /* the type was found as a .js file, try to build it then search the cache */ + if (!acceptedCompilationUnits.includes(compilationUnit.getFileName())) { + // the type was found as a .js file, try to build it then search the cache acceptedCompilationUnits.add(compilationUnit.getFileName()); - if (typeRequestor instanceof ITypeRequestor2) - ((ITypeRequestor2) typeRequestor).accept(compilationUnit, types, answer.getAccessRestriction()); - else - typeRequestor.accept(compilationUnit, answer.getAccessRestriction()); -// } + typeRequestor.accept(compilationUnit, answer.getAccessRestriction()); + } } else if (answer.isCompilationUnits()) { ICompilationUnit[] compilationUnits = answer.getCompilationUnits(); - for (int j = 0; j < compilationUnits.length; j++) { -// if (!acceptedCompilationUnits.includes(compilationUnits[j].getFileName())) { - // the type was found as a .js file, try to build it - // then search the cache - acceptedCompilationUnits.add(compilationUnits[j].getFileName()); - // if (compilationUnits[i] instanceof MetadataFile) - // typeRequestor.accept(((MetadataFile)compilationUnits[i]).getAPIs()); - // else - if (typeRequestor instanceof ITypeRequestor2) - ((ITypeRequestor2) typeRequestor).accept(compilationUnits[j], types, answer.getAccessRestriction()); - else - typeRequestor.accept(compilationUnits[j], answer.getAccessRestriction()); -// } + for (int i = 0; i < compilationUnits.length; i++) { + if (!acceptedCompilationUnits.includes(compilationUnits[i].getFileName())) { + // the type was found as a .js file, try to build it then search the cache + acceptedCompilationUnits.add(compilationUnits[i].getFileName()); + typeRequestor.accept(compilationUnits[i], answer.getAccessRestriction()); + } } } + else if (answer.isSourceType()) { + // the type was found as a source model + typeRequestor.accept(answer.getSourceTypes(), packageBinding, answer.getAccessRestriction()); + } + } - } - finally { - fAddingUnits = false; - } -} -void addUnitsContainingBinding(PackageBinding packageBinding, char[] type, int mask, String excludePath) { - if (packageBinding == null) { - if (defaultPackage == null) - return; - packageBinding = defaultPackage; + Binding askForBinding(GlobalBinding globalBinding, char[] name, int mask) { + return null; } - NameEnvironmentAnswer answer = nameEnvironment.findBinding(type, packageBinding.compoundName,mask, - this.typeRequestor, true, excludePath); - if (answer == null) - return; + Binding askForBinding(PackageBinding packageBinding, char[] name, int mask) { + if (packageBinding == null) { + if (defaultPackage == null) { + return null; + } + packageBinding = defaultPackage; + } + if (mask == Binding.PACKAGE && (name == null || name.length == 0) && this.defaultPackage.compoundName.length == 0) + return this.defaultPackage; + NameEnvironmentAnswer answer = nameEnvironment.findBinding(name, packageBinding.compoundName, mask, this.typeRequestor, true, null); + if (answer == null) + return null; + + if ((mask & Binding.TYPE) > 1) { + //if already asked for, return null to avoid infinite recursion + if(this.alreadyAskedForBinding(name)) { + return null; + } - if (answer.isBinaryType()) - // the type was found as a .class file - typeRequestor.accept(answer.getBinaryType(), packageBinding, answer.getAccessRestriction()); - else if (answer.isCompilationUnit()) { - ICompilationUnit compilationUnit = answer.getCompilationUnit(); - if (!acceptedCompilationUnits.includes(compilationUnit.getFileName())) - { - // the type was found as a .js file, try to build it then search the cache - acceptedCompilationUnits.add(compilationUnit.getFileName()); - typeRequestor.accept(compilationUnit, answer.getAccessRestriction()); + fAskingForTypeBinding.push(name); } - }else if (answer.isCompilationUnits()) { - ICompilationUnit[] compilationUnits = answer.getCompilationUnits(); - for (int i = 0; i < compilationUnits.length; i++) { - if (!acceptedCompilationUnits.includes(compilationUnits[i].getFileName())) { + try { + if (answer.isBinaryType()) + // the type was found as a .class file + typeRequestor.accept(answer.getBinaryType(), packageBinding, answer.getAccessRestriction()); + else if (answer.isCompilationUnit()) { + ICompilationUnit compilationUnit = answer.getCompilationUnit(); + // the type was found as a .js file, try to build it then search the cache + acceptedCompilationUnits.add(compilationUnit.getFileName()); + if (!compilationUnit.equals(unitBeingCompleted)) + if (typeRequestor instanceof ITypeRequestor2) { + ((ITypeRequestor2) typeRequestor).accept(compilationUnit, new char[][]{name}, answer.getAccessRestriction()); + } + else { + typeRequestor.accept(compilationUnit, answer.getAccessRestriction()); + } + } + else if (answer.isCompilationUnits()) { + ICompilationUnit[] compilationUnits = answer.getCompilationUnits(); + for (int i = 0; i < compilationUnits.length; i++) { // the type was found as a .js file, try to build it then search the cache acceptedCompilationUnits.add(compilationUnits[i].getFileName()); -// if (compilationUnits[i] instanceof MetadataFile) -// { -// typeRequestor.accept(((MetadataFile)compilationUnits[i]).getAPIs()); -// } -// else - typeRequestor.accept(compilationUnits[i], answer - .getAccessRestriction()); + if (!compilationUnits[i].equals(unitBeingCompleted)) { + if (typeRequestor instanceof ITypeRequestor2) { + ((ITypeRequestor2) typeRequestor).accept(compilationUnits[i], new char[][]{name}, answer.getAccessRestriction()); + } + else { + typeRequestor.accept(compilationUnits[i], answer.getAccessRestriction()); + } + } } } - } else if (answer.isSourceType()) - // the type was found as a source model - typeRequestor.accept(answer.getSourceTypes(), packageBinding, answer.getAccessRestriction()); + else if (answer.isSourceType()) { + // the type was found as a source model + typeRequestor.accept(answer.getSourceTypes(), packageBinding, answer.getAccessRestriction()); + } else if (answer.isMetaData()) { + LibraryAPIs metadata = answer.getLibraryMetadata(); -} + // the type was found as a .js file, try to build it then search the cache + acceptedCompilationUnits.add(metadata.fileName); + typeRequestor.accept(metadata); + } + } + finally { + if (mask == Binding.TYPE) { + fAskingForTypeBinding.pop(); + } + } + return packageBinding.getBinding0(name, mask); + } -Binding askForBinding(GlobalBinding globalBinding, char[] name, int mask) { - return null; -} -Binding askForBinding(PackageBinding packageBinding, char[] name, int mask) { - if (packageBinding == null) { - if (defaultPackage == null) - return null; - packageBinding = defaultPackage; + /** + * Create the initial type bindings for the compilation unit. + * + * See completeTypeBindings() for a description of the remaining steps + * + * NOTE: This method can be called multiple times as additional source files + * are needed + */ + public void buildTypeBindings(CompilationUnitDeclaration unit, AccessRestriction accessRestriction) { + buildTypeBindings(unit, CharOperation.NO_CHAR_CHAR, accessRestriction, false); + } + + public void buildTypeBindings(CompilationUnitDeclaration unit, AccessRestriction accessRestriction, boolean shouldBuildGlobalSuperType) { + buildTypeBindings(unit, CharOperation.NO_CHAR_CHAR, accessRestriction, shouldBuildGlobalSuperType); + } + + public void buildTypeBindings(CompilationUnitDeclaration unit, char[][] typeNames, AccessRestriction accessRestriction) { + buildTypeBindings(unit, typeNames, accessRestriction, false); } - if (mask==Binding.PACKAGE && (name==null || name.length==0)&& this.defaultPackage.compoundName.length==0) - return this.defaultPackage; - NameEnvironmentAnswer answer = nameEnvironment.findBinding(name, packageBinding.compoundName,mask,this.typeRequestor, true, null); - if (answer == null) - return null; - if((mask & Binding.TYPE) > 1) { - if (!fAskingForTypeBinding.isEmpty() && CharOperation.equals(name, (char[]) fAskingForTypeBinding.peek())) - return null; - fAskingForTypeBinding.push(name); - } - try { - if (answer.isBinaryType()) - // the type was found as a .class file - typeRequestor.accept(answer.getBinaryType(), packageBinding, answer.getAccessRestriction()); - else if (answer.isCompilationUnit()) { - ICompilationUnit compilationUnit = answer.getCompilationUnit(); - //if (!acceptedCompilationUnits.includes(compilationUnit.getFileName())) - // { - // the type was found as a .js file, try to build it then search the cache - acceptedCompilationUnits.add(compilationUnit.getFileName()); - if(!compilationUnit.equals(unitBeingCompleted)) - if (typeRequestor instanceof ITypeRequestor2) { - ((ITypeRequestor2)typeRequestor).accept(compilationUnit, new char[][]{name}, answer - .getAccessRestriction()); - } else - typeRequestor.accept(compilationUnit, answer.getAccessRestriction()); - //} - } else if (answer.isCompilationUnits()) { - ICompilationUnit[] compilationUnits = answer.getCompilationUnits(); - for (int i = 0; i < compilationUnits.length; i++) { - //if (!acceptedCompilationUnits.includes(compilationUnits[i].getFileName())) { - // the type was found as a .js file, try to build it then search the cache - acceptedCompilationUnits.add(compilationUnits[i].getFileName()); - if(!compilationUnits[i].equals(unitBeingCompleted)) - if (typeRequestor instanceof ITypeRequestor2) { - ((ITypeRequestor2)typeRequestor).accept(compilationUnits[i], new char[][]{name}, answer - .getAccessRestriction()); - } else - typeRequestor.accept(compilationUnits[i], answer - .getAccessRestriction()); - //} - } - } else if (answer.isSourceType()) - // the type was found as a source model - typeRequestor.accept(answer.getSourceTypes(), packageBinding, answer.getAccessRestriction()); - else if (answer.isMetaData()) - { - LibraryAPIs metadata= answer.getLibraryMetadata(); -// if (!acceptedCompilationUnits.includes(metadata.fileName)) - { - // the type was found as a .js file, try to build it then search the cache - acceptedCompilationUnits.add(metadata.fileName); - typeRequestor.accept(metadata); + public void buildTypeBindings(CompilationUnitDeclaration unit, char[][] typeNames, AccessRestriction accessRestriction, boolean shouldBuildGlobalSuperType) { + CompilationUnitScope scope = unit.scope; + boolean addUnit = false; + if (scope == null) { + scope = new CompilationUnitScope(unit, this); + addUnit = true; + } + + scope.setShouldBuildGlobalSuperType(shouldBuildGlobalSuperType); + scope.buildTypeBindings(typeNames, accessRestriction); + + if (addUnit) { + int unitsLength = units.length; + if (++lastUnitIndex >= unitsLength) { + System.arraycopy(units, 0, units = new CompilationUnitDeclaration[2 * unitsLength], 0, unitsLength); + } + units[lastUnitIndex] = unit; + } + } + + /** + * Cache the binary type since we know it is needed during this compile. + * + * Answer the created BinaryTypeBinding or null if the type is already in the + * cache. + */ + public BinaryTypeBinding cacheBinaryType(ISourceType binaryType, AccessRestriction accessRestriction) { + return cacheBinaryType(binaryType, true, accessRestriction); + } + + /** + * Cache the binary type since we know it is needed during this compile. + * + * Answer the created BinaryTypeBinding or null if the type is already in the + * cache. + */ + public BinaryTypeBinding cacheBinaryType(ISourceType binaryType, boolean needFieldsAndMethods, AccessRestriction accessRestriction) { + char[][] compoundName = CharOperation.splitOn('/', binaryType.getName()); + ReferenceBinding existingType = getCachedType(compoundName); + + if (existingType == null || existingType instanceof UnresolvedReferenceBinding) { + // only add the binary type if its not already in the cache + return createBinaryTypeFrom(binaryType, computePackageFrom(compoundName), needFieldsAndMethods, accessRestriction); } + // the type already exists & can be retrieved from the cache + return null; } + + public MissingBinaryTypeBinding cacheMissingBinaryType(char[][] compoundName, CompilationUnitDeclaration unit) { + PackageBinding packageBinding = computePackageFrom(compoundName); + if (unit == null) { + return null; + } + + // create a proxy for the missing BinaryType + MissingBinaryTypeBinding type = new MissingBinaryTypeBinding(packageBinding, compoundName, this, unit.scope); + if (type.id != TypeIds.T_JavaLangObject) { + // make Object be its superclass - it could in turn be missing as well + ReferenceBinding objectType = getType(TypeConstants.JAVA_LANG_OBJECT); + if (objectType == null) { + objectType = cacheMissingBinaryType(TypeConstants.JAVA_LANG_OBJECT, unit); // create + } + + // a proxy for the missing Object type + type.setMissingSuperclass(objectType); + } + packageBinding.addType(type); + return type; } - finally { - if(mask == Binding.TYPE) { - fAskingForTypeBinding.pop(); - } - } - return packageBinding.getBinding0(name,mask); -} -/* Create the initial type bindings for the compilation unit. -* -* See completeTypeBindings() for a description of the remaining steps -* -* NOTE: This method can be called multiple times as additional source files are needed -*/ - -public void buildTypeBindings(CompilationUnitDeclaration unit, AccessRestriction accessRestriction) { - buildTypeBindings(unit, new char[0][0], accessRestriction); -} -public void buildTypeBindings(CompilationUnitDeclaration unit, char[][] typeNames, AccessRestriction accessRestriction) { - CompilationUnitScope scope = new CompilationUnitScope(unit, this); - scope.buildTypeBindings(typeNames, accessRestriction); - - int unitsLength = units.length; - if (++lastUnitIndex >= unitsLength) - System.arraycopy(units, 0, units = new CompilationUnitDeclaration[2 * unitsLength], 0, unitsLength); - units[lastUnitIndex] = unit; -} -/* Cache the binary type since we know it is needed during this compile. -* -* Answer the created BinaryTypeBinding or null if the type is already in the cache. -*/ - -public BinaryTypeBinding cacheBinaryType(ISourceType binaryType, AccessRestriction accessRestriction) { - return cacheBinaryType(binaryType, true, accessRestriction); -} -/* Cache the binary type since we know it is needed during this compile. -* -* Answer the created BinaryTypeBinding or null if the type is already in the cache. -*/ - -public BinaryTypeBinding cacheBinaryType(ISourceType binaryType, boolean needFieldsAndMethods, AccessRestriction accessRestriction) { - char[][] compoundName = CharOperation.splitOn('/', binaryType.getName()); - ReferenceBinding existingType = getCachedType(compoundName); - - if (existingType == null || existingType instanceof UnresolvedReferenceBinding) - // only add the binary type if its not already in the cache - return createBinaryTypeFrom(binaryType, computePackageFrom(compoundName), needFieldsAndMethods, accessRestriction); - return null; // the type already exists & can be retrieved from the cache -} -public MissingBinaryTypeBinding cacheMissingBinaryType(char[][] compoundName, CompilationUnitDeclaration unit) { - PackageBinding packageBinding = computePackageFrom(compoundName); - if(unit == null) - return null; - // create a proxy for the missing BinaryType - MissingBinaryTypeBinding type = new MissingBinaryTypeBinding(packageBinding, compoundName, this,unit.scope); - if (type.id != TypeIds.T_JavaLangObject) { - // make Object be its superclass - it could in turn be missing as well - ReferenceBinding objectType = getType(TypeConstants.JAVA_LANG_OBJECT); - if (objectType == null) - objectType = cacheMissingBinaryType(TypeConstants.JAVA_LANG_OBJECT, unit); // create a proxy for the missing Object type - type.setMissingSuperclass(objectType); - } - packageBinding.addType(type); - return type; -} -/* -* 1. Connect the type hierarchy for the type bindings created for parsedUnits. -* 2. Create the field bindings -* 3. Create the method bindings -*/ - -/* We know each known compilationUnit is free of errors at this point... -* -* Each step will create additional bindings unless a problem is detected, in which -* case either the faulty import/superinterface/field/method will be skipped or a -* suitable replacement will be substituted (such as Object for a missing superclass) -*/ - -public void completeTypeBindings() { - stepCompleted = BUILD_TYPE_HIERARCHY; - - for (int i = this.lastCompletedUnitIndex + 1; i <= this.lastUnitIndex; i++) { - (this.unitBeingCompleted = this.units[i]).scope.checkAndSetImports(); - } - stepCompleted = CHECK_AND_SET_IMPORTS; - - for (int i = this.lastCompletedUnitIndex + 1; i <= this.lastUnitIndex; i++) { - (this.unitBeingCompleted = this.units[i]).scope.connectTypeHierarchy(); - } - stepCompleted = CONNECT_TYPE_HIERARCHY; - - for (int i = this.lastCompletedUnitIndex + 1; i <= this.lastUnitIndex; i++) { - CompilationUnitScope unitScope = (this.unitBeingCompleted = this.units[i]).scope; - unitScope.buildFieldsAndMethods(); - this.units[i] = null; // release unnecessary reference to the parsed unit - } - stepCompleted = BUILD_FIELDS_AND_METHODS; - this.lastCompletedUnitIndex = this.lastUnitIndex; - this.unitBeingCompleted = null; -} -public void completeTypeBindings(char[][] types) { - stepCompleted = BUILD_TYPE_HIERARCHY; - - for (int i = this.lastCompletedUnitIndex + 1; i <= this.lastUnitIndex; i++) { - (this.unitBeingCompleted = this.units[i]).scope.checkAndSetImports(); - } - stepCompleted = CHECK_AND_SET_IMPORTS; - - for (int i = this.lastCompletedUnitIndex + 1; i <= this.lastUnitIndex; i++) { - (this.unitBeingCompleted = this.units[i]).scope.connectTypeHierarchy(types); - } - stepCompleted = CONNECT_TYPE_HIERARCHY; - - for (int i = this.lastCompletedUnitIndex + 1; i <= this.lastUnitIndex; i++) { - CompilationUnitScope unitScope = (this.unitBeingCompleted = this.units[i]).scope; - unitScope.buildFieldsAndMethods(); - this.units[i] = null; // release unnecessary reference to the parsed unit - } - stepCompleted = BUILD_FIELDS_AND_METHODS; - this.lastCompletedUnitIndex = this.lastUnitIndex; - this.unitBeingCompleted = null; -} -/* -* 1. Connect the type hierarchy for the type bindings created for parsedUnits. -* 2. Create the field bindings -* 3. Create the method bindings -*/ - -/* -* Each step will create additional bindings unless a problem is detected, in which -* case either the faulty import/superinterface/field/method will be skipped or a -* suitable replacement will be substituted (such as Object for a missing superclass) -*/ - -public void completeTypeBindings(CompilationUnitDeclaration parsedUnit) { - completeTypeBindings(parsedUnit, new char[0][0]); -} - -public void completeTypeBindings(CompilationUnitDeclaration parsedUnit, char[][] typeNames) { - if (stepCompleted == BUILD_FIELDS_AND_METHODS) { - // This can only happen because the original set of units are completely built and - // are now being processed, so we want to treat all the additional units as a group - // until they too are completely processed. - completeTypeBindings(); - } else { - if (parsedUnit.scope == null) return; // parsing errors were too severe - - if (stepCompleted >= CHECK_AND_SET_IMPORTS) - (this.unitBeingCompleted = parsedUnit).scope.checkAndSetImports(); - - if (stepCompleted >= CONNECT_TYPE_HIERARCHY) - (this.unitBeingCompleted = parsedUnit).scope.connectTypeHierarchy(typeNames); + /** + * 1. Connect the type hierarchy for the type bindings created for + * parsedUnits. 2. Create the field bindings 3. Create the method bindings + * + * We know each known compilationUnit is free of errors at this point... + * + * Each step will create additional bindings unless a problem is detected, in + * which case either the faulty import/superinterface/field/method will be + * skipped or a suitable replacement will be substituted (such as Object for a + * missing superclass) + */ + public void completeTypeBindings() { + stepCompleted = BUILD_TYPE_HIERARCHY; + + for (int i = this.lastCompletedUnitIndex + 1; i <= this.lastUnitIndex; i++) { + (this.unitBeingCompleted = this.units[i]).scope.checkAndSetImports(); + } + stepCompleted = CHECK_AND_SET_IMPORTS; + + for (int i = this.lastCompletedUnitIndex + 1; i <= this.lastUnitIndex; i++) { + (this.unitBeingCompleted = this.units[i]).scope.connectTypeHierarchy(); + } + stepCompleted = CONNECT_TYPE_HIERARCHY; + + for (int i = this.lastCompletedUnitIndex + 1; i <= this.lastUnitIndex; i++) { + CompilationUnitScope unitScope = (this.unitBeingCompleted = this.units[i]).scope; + unitScope.buildFieldsAndMethods(); + this.units[i] = null; // release unnecessary reference to the parsed unit + } + stepCompleted = BUILD_FIELDS_AND_METHODS; + this.lastCompletedUnitIndex = this.lastUnitIndex; this.unitBeingCompleted = null; } -} -/* -* Used by other compiler tools which do not start by calling completeTypeBindings(). -* -* 1. Connect the type hierarchy for the type bindings created for parsedUnits. -* 2. Create the field bindings -* 3. Create the method bindings -*/ - -public void completeTypeBindings(CompilationUnitDeclaration parsedUnit, char[][] typeNames, boolean buildFieldsAndMethods) { - if (parsedUnit.scope == null) return; // parsing errors were too severe - - (this.unitBeingCompleted = parsedUnit).scope.checkAndSetImports(); - parsedUnit.scope.connectTypeHierarchy(typeNames); - if (buildFieldsAndMethods) - parsedUnit.scope.buildFieldsAndMethods(); - this.unitBeingCompleted = null; -} - -public void completeTypeBindings(CompilationUnitDeclaration parsedUnit, boolean buildFieldsAndMethods) { - completeTypeBindings(parsedUnit, new char[0][0], buildFieldsAndMethods); -} -public TypeBinding computeBoxingType(TypeBinding type) { - TypeBinding boxedType; - switch (type.id) { - case TypeIds.T_JavaLangBoolean : - return TypeBinding.BOOLEAN; - case TypeIds.T_JavaLangCharacter : - return TypeBinding.CHAR; - case TypeIds.T_JavaLangShort : - return TypeBinding.SHORT; - case TypeIds.T_JavaLangDouble : - return TypeBinding.DOUBLE; - case TypeIds.T_JavaLangFloat : - return TypeBinding.FLOAT; - case TypeIds.T_JavaLangInteger : - return TypeBinding.INT; - case TypeIds.T_JavaLangLong : - return TypeBinding.LONG; - - case TypeIds.T_int : - boxedType = getType(JAVA_LANG_INTEGER); - if (boxedType != null) return boxedType; - return new ProblemReferenceBinding(JAVA_LANG_INTEGER, null, NotFound); - case TypeIds.T_short : - boxedType = getType(JAVA_LANG_SHORT); - if (boxedType != null) return boxedType; - return new ProblemReferenceBinding(JAVA_LANG_SHORT, null, NotFound); - case TypeIds.T_char : - boxedType = getType(JAVA_LANG_CHARACTER); - if (boxedType != null) return boxedType; - return new ProblemReferenceBinding(JAVA_LANG_CHARACTER, null, NotFound); - case TypeIds.T_long : - boxedType = getType(JAVA_LANG_LONG); - if (boxedType != null) return boxedType; - return new ProblemReferenceBinding(JAVA_LANG_LONG, null, NotFound); - case TypeIds.T_float : - boxedType = getType(JAVA_LANG_FLOAT); - if (boxedType != null) return boxedType; - return new ProblemReferenceBinding(JAVA_LANG_FLOAT, null, NotFound); - case TypeIds.T_double : - boxedType = getType(JAVA_LANG_DOUBLE); - if (boxedType != null) return boxedType; - return new ProblemReferenceBinding(JAVA_LANG_DOUBLE, null, NotFound); - case TypeIds.T_boolean : - boxedType = getType(JAVA_LANG_BOOLEAN); - if (boxedType != null) return boxedType; - return new ProblemReferenceBinding(JAVA_LANG_BOOLEAN, null, NotFound); -// case TypeIds.T_int : -// return getResolvedType(JAVA_LANG_INTEGER, null); -// case TypeIds.T_byte : -// return getResolvedType(JAVA_LANG_BYTE, null); -// case TypeIds.T_short : -// return getResolvedType(JAVA_LANG_SHORT, null); -// case TypeIds.T_char : -// return getResolvedType(JAVA_LANG_CHARACTER, null); -// case TypeIds.T_long : -// return getResolvedType(JAVA_LANG_LONG, null); -// case TypeIds.T_float : -// return getResolvedType(JAVA_LANG_FLOAT, null); -// case TypeIds.T_double : -// return getResolvedType(JAVA_LANG_DOUBLE, null); -// case TypeIds.T_boolean : -// return getResolvedType(JAVA_LANG_BOOLEAN, null); - } - return type; -} -private PackageBinding computePackageFrom(char[][] constantPoolName) { - return defaultPackage; -// if (constantPoolName.length == 1) -// return defaultPackage; -// -// PackageBinding packageBinding = getPackage0(constantPoolName[0]); -// if (packageBinding == null || packageBinding == TheNotFoundPackage) { -// packageBinding = new PackageBinding(constantPoolName[0], this); -// knownPackages.put(constantPoolName[0], packageBinding); -// -// } -// -// for (int i = 1, length = constantPoolName.length - 1; i < length; i++) { -// PackageBinding parent = packageBinding; -// if ((packageBinding = parent.getPackage0(constantPoolName[i])) == null || packageBinding == TheNotFoundPackage) { -// packageBinding = new PackageBinding(CharOperation.subarray(constantPoolName, 0, i + 1), parent, this); -// parent.addPackage(packageBinding); -// } -// } -// return packageBinding; -} - -/* Used to guarantee array type identity. -*/ -public ArrayBinding createArrayType(TypeBinding leafComponentType, int dimensionCount) { - if (leafComponentType instanceof LocalTypeBinding) // cache local type arrays with the local type itself - return ((LocalTypeBinding) leafComponentType).createArrayType(dimensionCount,this); - - // find the array binding cache for this dimension - int dimIndex = dimensionCount - 1; - int length = uniqueArrayBindings.length; - ArrayBinding[] arrayBindings; - if (dimIndex < length) { - if ((arrayBindings = uniqueArrayBindings[dimIndex]) == null) - uniqueArrayBindings[dimIndex] = arrayBindings = new ArrayBinding[10]; - } else { - System.arraycopy( - uniqueArrayBindings, 0, - uniqueArrayBindings = new ArrayBinding[dimensionCount][], 0, - length); - uniqueArrayBindings[dimIndex] = arrayBindings = new ArrayBinding[10]; - } - - // find the cached array binding for this leaf component type (if any) - int index = -1; - length = arrayBindings.length; - while (++index < length) { - ArrayBinding currentBinding = arrayBindings[index]; - if (currentBinding == null) // no matching array, but space left - return arrayBindings[index] = new ArrayBinding(leafComponentType, dimensionCount, this); - if (currentBinding.leafComponentType == leafComponentType) - return currentBinding; - } - - // no matching array, no space left - System.arraycopy( - arrayBindings, 0, - (arrayBindings = new ArrayBinding[length * 2]), 0, - length); - uniqueArrayBindings[dimIndex] = arrayBindings; - return arrayBindings[length] = new ArrayBinding(leafComponentType, dimensionCount, this); -} -public BinaryTypeBinding createBinaryTypeFrom(ISourceType binaryType, PackageBinding packageBinding, AccessRestriction accessRestriction) { - return createBinaryTypeFrom(binaryType, packageBinding, true, accessRestriction); -} -public BinaryTypeBinding createBinaryTypeFrom(ISourceType binaryType, PackageBinding packageBinding, boolean needFieldsAndMethods, AccessRestriction accessRestriction) { - BinaryTypeBinding binaryBinding = new BinaryTypeBinding(packageBinding, binaryType, this); - - // resolve any array bindings which reference the unresolvedType - ReferenceBinding cachedType = packageBinding.getType0(binaryBinding.compoundName[binaryBinding.compoundName.length - 1]); - if (cachedType != null) { // update reference to unresolved binding after having read classfile (knows whether generic for raw conversion) - if (cachedType instanceof UnresolvedReferenceBinding) { - ((UnresolvedReferenceBinding) cachedType).setResolvedType(binaryBinding, this); - } else { - if (cachedType.isBinaryBinding()) // sanity check... at this point the cache should ONLY contain unresolved types - return (BinaryTypeBinding) cachedType; - // it is possible with a large number of source files (exceeding AbstractImageBuilder.MAX_AT_ONCE) that a member type can be in the cache as an UnresolvedType, - // but because its enclosingType is resolved while its created (call to BinaryTypeBinding constructor), its replaced with a source type - return null; + + public void completeTypeBindings(char[][] types) { + stepCompleted = BUILD_TYPE_HIERARCHY; + + for (int i = this.lastCompletedUnitIndex + 1; i <= this.lastUnitIndex; i++) { + (this.unitBeingCompleted = this.units[i]).scope.checkAndSetImports(); + } + stepCompleted = CHECK_AND_SET_IMPORTS; + + for (int i = this.lastCompletedUnitIndex + 1; i <= this.lastUnitIndex; i++) { + (this.unitBeingCompleted = this.units[i]).scope.connectTypeHierarchy(types); + } + stepCompleted = CONNECT_TYPE_HIERARCHY; + + for (int i = this.lastCompletedUnitIndex + 1; i <= this.lastUnitIndex; i++) { + CompilationUnitScope unitScope = (this.unitBeingCompleted = this.units[i]).scope; + unitScope.buildFieldsAndMethods(); + this.units[i] = null; // release unnecessary reference to the parsed unit } + stepCompleted = BUILD_FIELDS_AND_METHODS; + this.lastCompletedUnitIndex = this.lastUnitIndex; + this.unitBeingCompleted = null; + } + + /** + * 1. Connect the type hierarchy for the type bindings created for + * parsedUnits. 2. Create the field bindings 3. Create the method bindings + * + * Each step will create additional bindings unless a problem is detected, in + * which case either the faulty import/superinterface/field/method will be + * skipped or a suitable replacement will be substituted (such as Object for a + * missing superclass) + */ + public void completeTypeBindings(CompilationUnitDeclaration parsedUnit) { + completeTypeBindings(parsedUnit, CharOperation.NO_CHAR_CHAR); } - packageBinding.addType(binaryBinding); - setAccessRestriction(binaryBinding, accessRestriction); - binaryBinding.cachePartsFrom(binaryType, needFieldsAndMethods); - return binaryBinding; -} -/* Used to create packages from the package statement. -*/ + public void completeTypeBindings(CompilationUnitDeclaration parsedUnit, char[][] typeNames) { + if (stepCompleted == BUILD_FIELDS_AND_METHODS) { + /* This can only happen because the original set of units are completely built and + * are now being processed, so we want to treat all the additional units as a group + * until they too are completely processed. */ + completeTypeBindings(); + } + else { + if (parsedUnit.scope == null) { + return; // parsing errors were too severe + } -public PackageBinding createPackage(char[][] compoundName) { - PackageBinding packageBinding = getPackage0(compoundName[0]); - if (packageBinding == null) { - packageBinding = new PackageBinding(compoundName[0], this); - //knownPackages.put(compoundName[0], packageBinding); + if (stepCompleted >= CHECK_AND_SET_IMPORTS) { + (this.unitBeingCompleted = parsedUnit).scope.checkAndSetImports(); + } + if (stepCompleted >= CONNECT_TYPE_HIERARCHY) { + (this.unitBeingCompleted = parsedUnit).scope.connectTypeHierarchy(typeNames); + } + this.unitBeingCompleted = null; + } } - for (int i = 1, length = compoundName.length; i < length; i++) { - // check to see if it collides with a known type... - // this case can only happen if the package does not exist as a directory in the file system - // otherwise when the source type was defined, the correct error would have been reported - // unless its an unresolved type which is referenced from an inconsistent class file - // NOTE: empty packages are not packages according to changes in JLS v2, 7.4.3 - // so not all types cause collision errors when they're created even though the package did exist - ReferenceBinding type = packageBinding.getType0(compoundName[i]); - if (type != null && type != TheNotFoundType && !(type instanceof UnresolvedReferenceBinding)) - return null; + /** + * Used by other compiler tools which do not start by calling + * completeTypeBindings(). + * + * 1. Connect the type hierarchy for the type bindings created for + * parsedUnits. 2. Create the field bindings 3. Create the method bindings + */ + public void completeTypeBindings(CompilationUnitDeclaration parsedUnit, char[][] typeNames, boolean buildFieldsAndMethods) { + if (parsedUnit.scope == null) { + return; // parsing errors were too severe + } - PackageBinding parent = packageBinding; - if ((packageBinding = parent.getPackage0(compoundName[i])) == null) { - // if the package is unknown, check to see if a type exists which would collide with the new package - // catches the case of a package statement of: package java.lang.Object; - // since the package can be added after a set of source files have already been compiled, - // we need to check whenever a package is created -// if (nameEnvironment.findType(compoundName[i], parent.compoundName,this.typeRequestor) != null) -// return null; - - packageBinding = new PackageBinding(CharOperation.subarray(compoundName, 0, i + 1), parent, this); - parent.addPackage(packageBinding); - } - } - return packageBinding; -} - -/** - * Returns the access restriction associated to a given type, or null if none - */ -public AccessRestriction getAccessRestriction(TypeBinding type) { - return (AccessRestriction) this.accessRestrictions.get(type); -} - -/** - * Answer the type for the compoundName if it exists in the cache. - * Answer theNotFoundType if it could not be resolved the first time - * it was looked up, otherwise answer null. - * - * NOTE: Do not use for nested types... the answer is NOT the same for a.b.C or a.b.C.D.E - * assuming C is a type in both cases. In the a.b.C.D.E case, null is the answer. - */ + (this.unitBeingCompleted = parsedUnit).scope.checkAndSetImports(); + parsedUnit.scope.connectTypeHierarchy(typeNames); + if (buildFieldsAndMethods) { + shouldBuildFieldsAndMethods = false; + try { + parsedUnit.scope.buildFieldsAndMethods(); + } + finally { + shouldBuildFieldsAndMethods = true; + } + } + this.unitBeingCompleted = null; + } -public ReferenceBinding getCachedType(char[][] compoundName) { - if (compoundName.length == 1) { - if (defaultPackage == null) - return null; - return defaultPackage.getType0(compoundName[0]); + public void completeTypeBindings(CompilationUnitDeclaration parsedUnit, boolean buildFieldsAndMethods) { + completeTypeBindings(parsedUnit, CharOperation.NO_CHAR_CHAR, buildFieldsAndMethods); } - PackageBinding packageBinding = getPackage0(compoundName[0]); - if (packageBinding == null) - return null; + public TypeBinding computeBoxingType(TypeBinding type) { + TypeBinding boxedType; + switch (type.id) { + case TypeIds.T_JavaLangBoolean : + return TypeBinding.BOOLEAN; + case TypeIds.T_JavaLangCharacter : + return TypeBinding.CHAR; + case TypeIds.T_JavaLangShort : + return TypeBinding.SHORT; + case TypeIds.T_JavaLangDouble : + return TypeBinding.DOUBLE; + case TypeIds.T_JavaLangFloat : + return TypeBinding.FLOAT; + case TypeIds.T_JavaLangInteger : + return TypeBinding.INT; + case TypeIds.T_JavaLangLong : + return TypeBinding.LONG; + + case TypeIds.T_int : + boxedType = getType(JAVA_LANG_INTEGER); + if (boxedType != null) + return boxedType; + return new ProblemReferenceBinding(JAVA_LANG_INTEGER, null, NotFound); + case TypeIds.T_short : + boxedType = getType(JAVA_LANG_SHORT); + if (boxedType != null) + return boxedType; + return new ProblemReferenceBinding(JAVA_LANG_SHORT, null, NotFound); + case TypeIds.T_char : + boxedType = getType(JAVA_LANG_CHARACTER); + if (boxedType != null) + return boxedType; + return new ProblemReferenceBinding(JAVA_LANG_CHARACTER, null, NotFound); + case TypeIds.T_long : + boxedType = getType(JAVA_LANG_LONG); + if (boxedType != null) + return boxedType; + return new ProblemReferenceBinding(JAVA_LANG_LONG, null, NotFound); + case TypeIds.T_float : + boxedType = getType(JAVA_LANG_FLOAT); + if (boxedType != null) + return boxedType; + return new ProblemReferenceBinding(JAVA_LANG_FLOAT, null, NotFound); + case TypeIds.T_double : + boxedType = getType(JAVA_LANG_DOUBLE); + if (boxedType != null) + return boxedType; + return new ProblemReferenceBinding(JAVA_LANG_DOUBLE, null, NotFound); + case TypeIds.T_boolean : + boxedType = getType(JAVA_LANG_BOOLEAN); + if (boxedType != null) + return boxedType; + return new ProblemReferenceBinding(JAVA_LANG_BOOLEAN, null, NotFound); + } + return type; + } - for (int i = 1, packageLength = compoundName.length - 1; i < packageLength; i++) - if ((packageBinding = packageBinding.getPackage0(compoundName[i])) == null) - return null; - return packageBinding.getType0(compoundName[compoundName.length - 1]); -} -/* Answer the top level package named name if it exists in the cache. -* Answer theNotFoundPackage if it could not be resolved the first time -* it was looked up, otherwise answer null. -* -* NOTE: Senders must convert theNotFoundPackage into a real problem -* package if its to returned. -*/ - -PackageBinding getPackage0(char[] name) { - if (CharOperation.equals(name, defaultPackage.readableName())) + private PackageBinding computePackageFrom(char[][] constantPoolName) { return defaultPackage; + } + /** + * Used to guarantee array type identity. + */ + public ArrayBinding createArrayType(TypeBinding leafComponentType, int dimensionCount) { + // cache local type arrays with the local type itself + if (leafComponentType instanceof LocalTypeBinding) { + return ((LocalTypeBinding) leafComponentType).createArrayType(dimensionCount, this); + } - return knownPackages.get(name); -} -/* Answer the type corresponding to the compoundName. -* Ask the name environment for the type if its not in the cache. -* Fail with a classpath error if the type cannot be found. -*/ -public ReferenceBinding getResolvedType(char[][] compoundName, Scope scope) { - ReferenceBinding type = getType(compoundName); - if (type != null) return type; - - // create a proxy for the missing BinaryType - return cacheMissingBinaryType( - compoundName, - scope == null ? this.unitBeingCompleted : scope.referenceCompilationUnit()); -} -/* Answer the top level package named name. -* Ask the oracle for the package if its not in the cache. -* Answer null if the package cannot be found. -*/ - -PackageBinding getTopLevelPackage(char[] name) { - if (CharOperation.equals(name, defaultPackage.readableName())) - return defaultPackage; -// return null; -//} - PackageBinding packageBinding = getPackage0(name); - if (packageBinding != null) { - return packageBinding; + // find the array binding cache for this dimension + int dimIndex = dimensionCount - 1; + int length = uniqueArrayBindings.length; + ArrayBinding[] arrayBindings; + if (dimIndex < length) { + if ((arrayBindings = uniqueArrayBindings[dimIndex]) == null) { + uniqueArrayBindings[dimIndex] = arrayBindings = new ArrayBinding[10]; + } + } + else { + System.arraycopy(uniqueArrayBindings, 0, uniqueArrayBindings = new ArrayBinding[dimensionCount][], 0, length); + uniqueArrayBindings[dimIndex] = arrayBindings = new ArrayBinding[10]; + } + + // find the cached array binding for this leaf component type (if any) + int index = -1; + length = arrayBindings.length; + while (++index < length) { + ArrayBinding currentBinding = arrayBindings[index]; + if (currentBinding == null) // no matching array, but space left + return arrayBindings[index] = new ArrayBinding(leafComponentType, dimensionCount, this); + if (currentBinding.leafComponentType == leafComponentType) + return currentBinding; + } + + // no matching array, no space left + System.arraycopy(arrayBindings, 0, (arrayBindings = new ArrayBinding[length * 2]), 0, length); + uniqueArrayBindings[dimIndex] = arrayBindings; + return arrayBindings[length] = new ArrayBinding(leafComponentType, dimensionCount, this); } - if (nameEnvironment.isPackage(null, name)) { - knownPackages.put(name, packageBinding = new PackageBinding(name, this)); + public BinaryTypeBinding createBinaryTypeFrom(ISourceType binaryType, PackageBinding packageBinding, AccessRestriction accessRestriction) { + return createBinaryTypeFrom(binaryType, packageBinding, true, accessRestriction); + } + + public BinaryTypeBinding createBinaryTypeFrom(ISourceType binaryType, PackageBinding packageBinding, boolean needFieldsAndMethods, AccessRestriction accessRestriction) { + BinaryTypeBinding binaryBinding = new BinaryTypeBinding(packageBinding, binaryType, this); + + // resolve any array bindings which reference the unresolvedType + ReferenceBinding cachedType = packageBinding.getType0(binaryBinding.compoundName[binaryBinding.compoundName.length - 1]); + if (cachedType != null) { // update reference to unresolved binding + // after having read classfile (knows whether generic for raw conversion) + if (cachedType instanceof UnresolvedReferenceBinding) { + ((UnresolvedReferenceBinding) cachedType).setResolvedType(binaryBinding, this); + } + else { + // sanity check... at this point the cache should ONLY contain unresolved types + if (cachedType.isBinaryBinding()) { + return (BinaryTypeBinding) cachedType; + } + /* it is possible with a large number of source files + * (exceeding AbstractImageBuilder.MAX_AT_ONCE) that a member type can be in + * the cache as an UnresolvedType, + * but because its enclosingType is resolved while its created + * (call to BinaryTypeBinding constructor), its replaced with a source type */ + return null; + } + } + + packageBinding.addType(binaryBinding); + setAccessRestriction(binaryBinding, accessRestriction); + binaryBinding.cachePartsFrom(binaryType, needFieldsAndMethods); + return binaryBinding; + } + + /** + * Used to create packages from the package statement. + */ + public PackageBinding createPackage(char[][] compoundName) { + PackageBinding packageBinding = getPackage0(compoundName[0]); + if (packageBinding == null) { + packageBinding = new PackageBinding(compoundName[0], this); + } + + for (int i = 1, length = compoundName.length; i < length; i++) { + /* check to see if it collides with a known type... + * this case can only happen if the package does not exist as a + * directory in the file system + * otherwise when the source type was defined, the correct error + * would have been reported + * unless its an unresolved type which is referenced from an + * inconsistent class file + * NOTE: empty packages are not packages according to changes in + * JLS v2, 7.4.3 + * so not all types cause collision errors when they're created + * even though the package did exist */ + ReferenceBinding type = packageBinding.getType0(compoundName[i]); + if (type != null && type != TheNotFoundType && !(type instanceof UnresolvedReferenceBinding)) { + return null; + } + + PackageBinding parent = packageBinding; + if ((packageBinding = parent.getPackage0(compoundName[i])) == null) { + /* if the package is unknown, check to see if a type exists + * which would collide with the new package catches the case + * of a package statement of: package java.lang.Object; since + * the package can be added after a set of source files have + * already been compiled, we need to check whenever a package + * is created + */ + packageBinding = new PackageBinding(CharOperation.subarray(compoundName, 0, i + 1), parent, this); + parent.addPackage(packageBinding); + } + } return packageBinding; } - return null; -} -/* Answer the type corresponding to the compoundName. -* Ask the name environment for the type if its not in the cache. -* Answer null if the type cannot be found. -*/ + /** + * Returns the access restriction associated to a given type, or null if + * none + */ + public AccessRestriction getAccessRestriction(TypeBinding type) { + return (AccessRestriction) this.accessRestrictions.get(type); + } -public ReferenceBinding getType(char[][] compoundName) { - ReferenceBinding referenceBinding; + /** + * Answer the type for the compoundName if it exists in the cache. Answer + * theNotFoundType if it could not be resolved the first time it was + * looked up, otherwise answer null. + * + * NOTE: Do not use for nested types... the answer is NOT the same for + * a.b.C or a.b.C.D.E assuming C is a type in both cases. In the a.b.C.D.E + * case, null is the answer. + */ + public ReferenceBinding getCachedType(char[][] compoundName) { + if (compoundName.length == 1) { + if (defaultPackage == null) { + return null; + } + return defaultPackage.getType0(compoundName[0]); + } - if (compoundName.length == 1) { - if (defaultPackage == null) + PackageBinding packageBinding = getPackage0(compoundName[0]); + if (packageBinding == null) { return null; + } - if ((referenceBinding = defaultPackage.getType0(compoundName[0])) == null) { - PackageBinding packageBinding = getPackage0(compoundName[0]); - if (packageBinding != null) - return null; // collides with a known package... should not call this method in such a case - referenceBinding = askForType(defaultPackage, compoundName[0]); + for (int i = 1, packageLength = compoundName.length - 1; i < packageLength; i++) { + if ((packageBinding = packageBinding.getPackage0(compoundName[i])) == null) { + return null; + } } - } else { - PackageBinding packageBinding = getPackage0(compoundName[0]); + return packageBinding.getType0(compoundName[compoundName.length - 1]); + } + /** + * Answer the top level package named name if it exists in the cache. Answer + * theNotFoundPackage if it could not be resolved the first time it was looked + * up, otherwise answer null. + * + * NOTE: Senders must convert theNotFoundPackage into a real problem package + * if its to returned. + */ + PackageBinding getPackage0(char[] name) { + if (CharOperation.equals(name, defaultPackage.readableName())) { + return defaultPackage; + } + + return knownPackages.get(name); + } + + /** + * Answer the type corresponding to the compoundName. Ask the name environment + * for the type if its not in the cache. Fail with a classpath error if the + * type cannot be found. + */ + public ReferenceBinding getResolvedType(char[][] compoundName, Scope scope) { + ReferenceBinding type = getType(compoundName); + if (type != null) + return type; + + // create a proxy for the missing BinaryType + return cacheMissingBinaryType(compoundName, scope == null ? this.unitBeingCompleted : scope.referenceCompilationUnit()); + } + + /** + * Answer the top level package named name. Ask the oracle for the package if + * its not in the cache. Answer null if the package cannot be found. + */ + PackageBinding getTopLevelPackage(char[] name) { + if (CharOperation.equals(name, defaultPackage.readableName())) { + return defaultPackage; + } + + PackageBinding packageBinding = getPackage0(name); if (packageBinding != null) { - for (int i = 1, packageLength = compoundName.length - 1; i < packageLength; i++) { - if ((packageBinding = packageBinding.getPackage0(compoundName[i])) == null) + return packageBinding; + } + + if (nameEnvironment.isPackage(null, name)) { + knownPackages.put(name, packageBinding = new PackageBinding(name, this)); + return packageBinding; + } + + return null; + } + + /** + * Answer the type corresponding to the compoundName. Ask the name environment + * for the type if its not in the cache. Answer null if the type cannot be + * found. + */ + public ReferenceBinding getType(char[][] compoundName) { + ReferenceBinding referenceBinding; + + if (compoundName.length == 1) { + if (defaultPackage == null) + return null; + + if ((referenceBinding = defaultPackage.getType0(compoundName[0])) == null) { + PackageBinding packageBinding = getPackage0(compoundName[0]); + + // collides with a known package... should not call this method in such a case + if (packageBinding != null) { + return null; + } + referenceBinding = askForType(defaultPackage, compoundName[0]); + } + } + else { + PackageBinding packageBinding = getPackage0(compoundName[0]); + + if (packageBinding != null) { + for (int i = 1, packageLength = compoundName.length - 1; i < packageLength; i++) { + if ((packageBinding = packageBinding.getPackage0(compoundName[i])) == null) { + break; + } + } + } + + if (packageBinding == null) { + referenceBinding = askForType(compoundName); + } else if ((referenceBinding = packageBinding.getType0(compoundName[compoundName.length - 1])) == null) { + referenceBinding = askForType(packageBinding, compoundName[compoundName.length - 1]); + } + } + + if (referenceBinding == null || referenceBinding == TheNotFoundType) { + return null; + } + referenceBinding = BinaryTypeBinding.resolveType(referenceBinding, this, false); // no + // raw conversion for now + // compoundName refers to a nested type incorrectly (for example, package1.A$B) + if (referenceBinding.isNestedType()) { + return new ProblemReferenceBinding(compoundName, referenceBinding, InternalNameProvided); + } + return referenceBinding; + } + + /** + * Answer the type corresponding to the compound name. Does not ask the oracle + * for the type if its not found in the cache... instead an unresolved type is + * returned which must be resolved before used. + * + * NOTE: Does NOT answer base types nor array types! + */ + ReferenceBinding getTypeFromCompoundName(char[][] compoundName, boolean isParameterized) { + ReferenceBinding binding = getCachedType(compoundName); + if (binding == null) { + PackageBinding packageBinding = computePackageFrom(compoundName); + binding = new UnresolvedReferenceBinding(compoundName, packageBinding); + packageBinding.addType(binding); + } + else if (binding == TheNotFoundType) { + // create a proxy for the missing BinaryType + binding = cacheMissingBinaryType(compoundName, this.unitBeingCompleted); + } + return binding; + } + + /** + * Answer the type corresponding to the name from the binary file. Does not + * ask the oracle for the type if its not found in the cache... instead an + * unresolved type is returned which must be resolved before used. + * + * NOTE: Does NOT answer base types nor array types! + */ + ReferenceBinding getTypeFromConstantPoolName(char[] signature, int start, int end, boolean isParameterized) { + if (end == -1) { + end = signature.length; + } + + char[][] compoundName = CharOperation.splitOn('/', signature, start, end); + return getTypeFromCompoundName(compoundName, isParameterized); + } + + /** + * Answer the type corresponding to the signature from the binary file. Does + * not ask the oracle for the type if its not found in the cache... instead an + * unresolved type is returned which must be resolved before used. + * + * NOTE: Does answer base types & array types. + */ + TypeBinding getTypeFromSignature(char[] signature, int start, int end, boolean isParameterized, TypeBinding enclosingType) { + int dimension = 0; + while (signature[start] == '[') { + start++; + dimension++; + } + if (end == -1) + end = signature.length - 1; + + // Just switch on signature[start] - the L case is the else + TypeBinding binding = null; + if (start == end) { + switch (signature[start]) { + case 'I' : + binding = TypeBinding.INT; + break; + case 'Z' : + binding = TypeBinding.BOOLEAN; + break; + case 'V' : + binding = TypeBinding.VOID; + break; + case 'C' : + binding = TypeBinding.CHAR; + break; + case 'D' : + binding = TypeBinding.DOUBLE; break; + case 'F' : + binding = TypeBinding.FLOAT; + break; + case 'J' : + binding = TypeBinding.LONG; + break; + case 'S' : + binding = TypeBinding.SHORT; + break; + default : + problemReporter.corruptedSignature(enclosingType, signature, start); + // will never reach here, since error will cause abort } } + else { + // skip leading 'L' or 'T' + binding = getTypeFromConstantPoolName(signature, start + 1, end, isParameterized); + } - if (packageBinding == null) - referenceBinding = askForType(compoundName); - else if ((referenceBinding = packageBinding.getType0(compoundName[compoundName.length - 1])) == null) - referenceBinding = askForType(packageBinding, compoundName[compoundName.length - 1]); + if (dimension == 0) + return binding; + return createArrayType(binding, dimension); } - if (referenceBinding == null || referenceBinding == TheNotFoundType) - return null; - referenceBinding = BinaryTypeBinding.resolveType(referenceBinding, this, false); // no raw conversion for now - - // compoundName refers to a nested type incorrectly (for example, package1.A$B) - if (referenceBinding.isNestedType()) - return new ProblemReferenceBinding(compoundName, referenceBinding, InternalNameProvided); - return referenceBinding; -} -/* Answer the type corresponding to the compound name. -* Does not ask the oracle for the type if its not found in the cache... instead an -* unresolved type is returned which must be resolved before used. -* -* NOTE: Does NOT answer base types nor array types! -*/ - -ReferenceBinding getTypeFromCompoundName(char[][] compoundName, boolean isParameterized) { - ReferenceBinding binding = getCachedType(compoundName); - if (binding == null) { - PackageBinding packageBinding = computePackageFrom(compoundName); - binding = new UnresolvedReferenceBinding(compoundName, packageBinding); - packageBinding.addType(binding); - } else if (binding == TheNotFoundType) { - // create a proxy for the missing BinaryType - binding = cacheMissingBinaryType(compoundName, this.unitBeingCompleted); - } - return binding; -} -/* Answer the type corresponding to the name from the binary file. -* Does not ask the oracle for the type if its not found in the cache... instead an -* unresolved type is returned which must be resolved before used. -* -* NOTE: Does NOT answer base types nor array types! -*/ - -ReferenceBinding getTypeFromConstantPoolName(char[] signature, int start, int end, boolean isParameterized) { - if (end == -1) - end = signature.length; - - char[][] compoundName = CharOperation.splitOn('/', signature, start, end); - return getTypeFromCompoundName(compoundName, isParameterized); -} -/* Answer the type corresponding to the signature from the binary file. -* Does not ask the oracle for the type if its not found in the cache... instead an -* unresolved type is returned which must be resolved before used. -* -* NOTE: Does answer base types & array types. -*/ - -TypeBinding getTypeFromSignature(char[] signature, int start, int end, boolean isParameterized, TypeBinding enclosingType) { - int dimension = 0; - while (signature[start] == '[') { - start++; - dimension++; - } - if (end == -1) - end = signature.length - 1; - - // Just switch on signature[start] - the L case is the else - TypeBinding binding = null; - if (start == end) { - switch (signature[start]) { - case 'I' : - binding = TypeBinding.INT; - break; - case 'Z' : - binding = TypeBinding.BOOLEAN; - break; - case 'V' : - binding = TypeBinding.VOID; - break; - case 'C' : - binding = TypeBinding.CHAR; - break; - case 'D' : - binding = TypeBinding.DOUBLE; - break; - case 'F' : - binding = TypeBinding.FLOAT; - break; - case 'J' : - binding = TypeBinding.LONG; - break; - case 'S' : - binding = TypeBinding.SHORT; - break; + TypeBinding getTypeFromTypeSignature(SignatureWrapper wrapper, ReferenceBinding enclosingType) { + // TypeVariableSignature = 'T' Identifier ';' + // ArrayTypeSignature = '[' TypeSignature + // ClassTypeSignature = 'L' Identifier TypeArgs(optional) ';' + // or ClassTypeSignature '.' 'L' Identifier TypeArgs(optional) ';' + // TypeArgs = '<' VariantTypeSignature VariantTypeSignatures '>' + int dimension = 0; + while (wrapper.signature[wrapper.start] == '[') { + wrapper.start++; + dimension++; + } + + // cannot reach this, since previous problem will abort compilation + if (wrapper.signature[wrapper.start] == 'T') { + return null; + } + TypeBinding type = getTypeFromSignature(wrapper.signature, wrapper.start, wrapper.computeEnd(), false, enclosingType); + return dimension == 0 ? type : createArrayType(type, dimension); + } + + TypeBinding getTypeFromVariantTypeSignature(SignatureWrapper wrapper, ReferenceBinding enclosingType, ReferenceBinding genericType, int rank) { + // VariantTypeSignature = '-' TypeSignature + // or '+' TypeSignature + // or TypeSignature + // or '*' + switch (wrapper.signature[wrapper.start]) { + case '-' : + // ? super aType + wrapper.start++; + TypeBinding bound = getTypeFromTypeSignature(wrapper, enclosingType); + case '+' : + // ? extends aType + wrapper.start++; + bound = getTypeFromTypeSignature(wrapper, enclosingType); + case '*' : + // ? + wrapper.start++; default : - problemReporter.corruptedSignature(enclosingType, signature, start); - // will never reach here, since error will cause abort + return getTypeFromTypeSignature(wrapper, enclosingType); } - } else { - binding = getTypeFromConstantPoolName(signature, start + 1, end, isParameterized); // skip leading 'L' or 'T' } - if (dimension == 0) - return binding; - return createArrayType(binding, dimension); -} -TypeBinding getTypeFromTypeSignature(SignatureWrapper wrapper, ReferenceBinding enclosingType) { - // TypeVariableSignature = 'T' Identifier ';' - // ArrayTypeSignature = '[' TypeSignature - // ClassTypeSignature = 'L' Identifier TypeArgs(optional) ';' - // or ClassTypeSignature '.' 'L' Identifier TypeArgs(optional) ';' - // TypeArgs = '<' VariantTypeSignature VariantTypeSignatures '>' - int dimension = 0; - while (wrapper.signature[wrapper.start] == '[') { - wrapper.start++; - dimension++; - } - - if (wrapper.signature[wrapper.start] == 'T') { - return null; // cannot reach this, since previous problem will abort compilation - } - TypeBinding type = getTypeFromSignature(wrapper.signature, wrapper.start, wrapper.computeEnd(), false, enclosingType); - return dimension == 0 ? type : createArrayType(type, dimension); -} -TypeBinding getTypeFromVariantTypeSignature( - SignatureWrapper wrapper, - ReferenceBinding enclosingType, - ReferenceBinding genericType, - int rank) { - // VariantTypeSignature = '-' TypeSignature - // or '+' TypeSignature - // or TypeSignature - // or '*' - switch (wrapper.signature[wrapper.start]) { - case '-' : - // ? super aType - wrapper.start++; - TypeBinding bound = getTypeFromTypeSignature(wrapper, enclosingType); - case '+' : - // ? extends aType - wrapper.start++; - bound = getTypeFromTypeSignature(wrapper, enclosingType); - case '*' : - // ? - wrapper.start++; - default : - return getTypeFromTypeSignature(wrapper, enclosingType); - } -} - -/* Ask the oracle if a package exists named name in the package named compoundName. -*/ -boolean isPackage(char[][] compoundName, char[] name) { - if (compoundName == null || compoundName.length == 0) - return nameEnvironment.isPackage(null, name); - return nameEnvironment.isPackage(compoundName, name); -} -// The method verifier is lazily initialized to guarantee the receiver, the compiler & the oracle are ready. - -public MethodVerifier methodVerifier() { - if (verifier == null) - verifier = new MethodVerifier(this); - return verifier; -} -public void reset() { - this.defaultPackage = new PackageBinding(this); // assume the default package always exists - this.defaultImports = null; - //this.knownPackages = new HashtableOfPackage(); - this.accessRestrictions = new HashMap(3); - - this.verifier = null; - for (int i = this.uniqueArrayBindings.length; --i >= 0;) { - ArrayBinding[] arrayBindings = this.uniqueArrayBindings[i]; - if (arrayBindings != null) - for (int j = arrayBindings.length; --j >= 0;) - arrayBindings[j] = null; - } - - for (int i = this.units.length; --i >= 0;) - this.units[i] = null; - this.lastUnitIndex = -1; - this.lastCompletedUnitIndex = -1; - this.unitBeingCompleted = null; // in case AbortException occurred - - // name environment has a longer life cycle, and must be reset in - // the code which created it. - this.acceptedCompilationUnits.clear(); - this.fAskingForTypeBinding.clear(); -} -/** - * Associate a given type with some access restriction - * (did not store the restriction directly into binding, since sparse information) - */ -public void setAccessRestriction(ReferenceBinding type, AccessRestriction accessRestriction) { - if (accessRestriction == null) return; - type.modifiers |= ExtraCompilerModifiers.AccRestrictedAccess; - this.accessRestrictions.put(type, accessRestriction); -} - -public void buildTypeBindings(LibraryAPIs libraryMetaData) { - - ClassData[] classes = libraryMetaData.classes; - PackageBinding packageBinding = this.defaultPackage; - int typeLength=(classes!=null ? classes.length:0); - int count = 0; - - LibraryAPIsScope scope=new LibraryAPIsScope(libraryMetaData,this); - SourceTypeBinding[] topLevelTypes = new SourceTypeBinding[typeLength]; + /** + * Ask the oracle if a package exists named name in the package named + * compoundName. + */ + boolean isPackage(char[][] compoundName, char[] name) { + if (compoundName == null || compoundName.length == 0) { + return nameEnvironment.isPackage(null, name); + } + return nameEnvironment.isPackage(compoundName, name); + } + + /** + * The method verifier is lazily initialized to guarantee the receiver, the + * compiler & the oracle are ready. + * + * @return + */ + public MethodVerifier methodVerifier() { + if (verifier == null) + verifier = new MethodVerifier(this); + return verifier; + } + + public void reset() { + // assume the default package always exists + this.defaultPackage = new PackageBinding(this); + this.defaultImports = null; + this.accessRestrictions = new HashMap(3); + + this.verifier = null; + for (int i = this.uniqueArrayBindings.length; --i >= 0;) { + ArrayBinding[] arrayBindings = this.uniqueArrayBindings[i]; + if (arrayBindings != null) { + for (int j = arrayBindings.length; --j >= 0;) { + arrayBindings[j] = null; + } + } + } + + for (int i = this.units.length; --i >= 0;) { + this.units[i] = null; + } + this.lastUnitIndex = -1; + this.lastCompletedUnitIndex = -1; + this.unitBeingCompleted = null; // in case AbortException occurred + + // name environment has a longer life cycle, and must be reset in + // the code which created it. + this.acceptedCompilationUnits.clear(); + this.fAskingForTypeBinding.clear(); + } + + /** + * Associate a given type with some access restriction (did not store the + * restriction directly into binding, since sparse information) + */ + public void setAccessRestriction(ReferenceBinding type, AccessRestriction accessRestriction) { + if (accessRestriction == null) + return; + type.modifiers |= ExtraCompilerModifiers.AccRestrictedAccess; + this.accessRestrictions.put(type, accessRestriction); + } + + public void buildTypeBindings(LibraryAPIs libraryMetaData) { + + ClassData[] classes = libraryMetaData.classes; + PackageBinding packageBinding = this.defaultPackage; + int typeLength = (classes != null ? classes.length : 0); + int count = 0; + + LibraryAPIsScope scope = new LibraryAPIsScope(libraryMetaData, this); + SourceTypeBinding[] topLevelTypes = new SourceTypeBinding[typeLength]; for (int i = 0; i < typeLength; i++) { - ClassData clazz=classes[i]; - char[][] className = CharOperation.arrayConcat(packageBinding.compoundName,clazz.name.toCharArray()); + ClassData clazz = classes[i]; + char[][] className = CharOperation.arrayConcat(packageBinding.compoundName, clazz.name.toCharArray()); - SourceTypeBinding binding = new MetatdataTypeBinding(className, packageBinding, clazz, scope) ; + SourceTypeBinding binding = new MetatdataTypeBinding(className, packageBinding, clazz, scope); this.defaultPackage.addType(binding); binding.fPackage.addType(binding); topLevelTypes[count++] = binding; } - if (count != topLevelTypes.length) + if (count != topLevelTypes.length) { System.arraycopy(topLevelTypes, 0, topLevelTypes = new SourceTypeBinding[count], 0, count); - - char [] fullFileName=libraryMetaData.fileName; + } + + char[] fullFileName = libraryMetaData.fileName; - LibraryAPIsBinding libraryAPIsBinding=new LibraryAPIsBinding(null,defaultPackage,fullFileName); + LibraryAPIsBinding libraryAPIsBinding = new LibraryAPIsBinding(null, defaultPackage, fullFileName); - if (packageBinding!=this.defaultPackage) + if (packageBinding != this.defaultPackage) { packageBinding.addBinding(libraryAPIsBinding, libraryAPIsBinding.shortReadableName(), Binding.COMPILATION_UNIT); + } + } + public CompilationUnitDeclaration getExistingCompilationUnitDeclaration(char[] fileName) { + for (int i = 0; i <= this.lastUnitIndex; i++) { + if (CharOperation.equals(this.units[i].getFileName(), fileName)) { + return this.units[i]; + } + } + return null; + } + + /** + *

+ * Determines if a binding has already been asked for for the given type + * name. + *

+ * + * @param typeName + * determine if a binding has already been asked for for the + * type with this name + * + * @return true if a type with the given name has already had + * a binding requested, false otherwise. + */ + private boolean alreadyAskedForBinding(char[] typeName) { + return !this.fAskingForTypeBinding.isEmpty() && this.fAskingForTypeBinding.contains(typeName); + } + + /** + *

+ * This stack can handle doing {@link #contains(Object)} and + * {@link #search(Object)}s for char[]s which a normal stack + * could not handle because equals does not work on + * char[]s. + *

+ */ + private static class CharArrayStack extends Stack { + private static final long serialVersionUID = 1L; -} + /** + * @see java.util.Vector#contains(java.lang.Object) + */ + public boolean contains(Object o) { + boolean contains = false; + if (o instanceof char[]) { + contains = this.search(o) != -1; + } + else { + contains = super.contains(o); + } + + return contains; + } + + /** + * @see java.util.Stack#search(java.lang.Object) + */ + public synchronized int search(Object o) { + int index = -1; + + if (o instanceof char[]) { + for (int i = 0; i < this.size() && index == -1; ++i) { + Object curr = this.get(i); + if (curr instanceof char[] && CharOperation.equals((char[]) o, (char[]) curr)) { + index = i; + } + } + } + else { + index = super.search(o); + } -} + return index; + } + } +} \ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MemberTypeBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MemberTypeBinding.java index a2f93291..8f2d4359 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MemberTypeBinding.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MemberTypeBinding.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -26,7 +26,7 @@ public char[] constantPoolName() /* java/lang/Object */ { if (constantPoolName != null) return constantPoolName; - return constantPoolName = CharOperation.concat(enclosingType().constantPoolName(), sourceName, '$'); + return constantPoolName = CharOperation.concat(enclosingType().constantPoolName(), sourceName, '.'); } public String toString() { diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MetatdataTypeBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MetatdataTypeBinding.java index 228d5cdc..883c24ff 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MetatdataTypeBinding.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MetatdataTypeBinding.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -24,942 +24,772 @@ public class MetatdataTypeBinding extends SourceTypeBinding { ClassData classData; LibraryAPIsScope libraryScope; - boolean methodsBuilt=false; - boolean fieldsBuilt=false; - -public MetatdataTypeBinding(char[][] compoundName, PackageBinding fPackage, ClassData classData, LibraryAPIsScope scope) { - this.compoundName = compoundName; - this.fPackage = fPackage; - this.fileName = scope.getFileName(); - this.sourceName = compoundName[0]; - - this.classData=classData; - // expect the fields & methods to be initialized correctly later - this.fields = Binding.NO_FIELDS; - this.methods = Binding.NO_METHODS; - - this.scope=this.libraryScope = scope; - - -} - - - -private void buildFields() { - FieldBinding prototype = new FieldBinding(TypeConstants.PROTOTYPE, TypeBinding.UNKNOWN, modifiers | ExtraCompilerModifiers.AccUnresolved, this); - Property[] classFields = this.classData.getFields(); - int size = classFields.length; - if (size == 0) { - setFields(new FieldBinding[]{prototype}); - return; + boolean methodsBuilt = false; + boolean fieldsBuilt = false; + + public MetatdataTypeBinding(char[][] compoundName, PackageBinding fPackage, ClassData classData, + LibraryAPIsScope scope) { + this.compoundName = compoundName; + this.fPackage = fPackage; + this.fileName = scope.getFileName(); + this.sourceName = compoundName[0]; + + this.classData = classData; + // expect the fields & methods to be initialized correctly later + this.fields = Binding.NO_FIELDS; + this.methods = Binding.NO_METHODS; + + this.scope = this.libraryScope = scope; } - // iterate the field declarations to create the bindings, lose all duplicates - FieldBinding[] fieldBindings = new FieldBinding[size+1]; - HashtableOfObject knownFieldNames = new HashtableOfObject(size); - boolean duplicate = false; - int count = 0; - for (int i = 0; i < size; i++) { - Property field =classFields[i]; - - char [] fieldName=field.name.toCharArray(); - int modifiers=0; - if (field.isStatic()) - modifiers|=ClassFileConstants.AccStatic; + private void buildFields() { + FieldBinding prototype = new FieldBinding(TypeConstants.PROTOTYPE, TypeBinding.UNKNOWN, modifiers + | ExtraCompilerModifiers.AccUnresolved, this); + Property[] classFields = this.classData.getFields(); + int size = classFields.length; + if(size == 0) { + setFields(new FieldBinding[] { prototype }); + return; + } + + // iterate the field declarations to create the bindings, lose all duplicates + FieldBinding[] fieldBindings = new FieldBinding[size + 1]; + HashtableOfObject knownFieldNames = new HashtableOfObject(size); + boolean duplicate = false; + int count = 0; + for(int i = 0; i < size; i++) { + Property field = classFields[i]; + + char[] fieldName = field.name.toCharArray(); + int modifiers = 0; + if(field.isStatic()) + modifiers |= ClassFileConstants.AccStatic; TypeBinding fieldTypeBinding = libraryScope.resolveType(field.dataType); - - FieldBinding fieldBinding = new FieldBinding(fieldName, fieldTypeBinding, modifiers | ExtraCompilerModifiers.AccUnresolved, this); + + FieldBinding fieldBinding = new FieldBinding(fieldName, fieldTypeBinding, modifiers + | ExtraCompilerModifiers.AccUnresolved, this); fieldBinding.id = count; // field's type will be resolved when needed for top level types -// checkAndSetModifiersForField(fieldBinding, field); + // checkAndSetModifiersForField(fieldBinding, field); - if (knownFieldNames.containsKey(fieldName)) { + if(knownFieldNames.containsKey(fieldName)) { duplicate = true; - FieldBinding previousBinding = (FieldBinding) knownFieldNames.get(fieldName); -// if (previousBinding != null) { -// for (int f = 0; f < i; f++) { -// InferredAttribute previousField = inferredType.attributes[f]; -// if (previousField.binding == previousBinding) { -// libraryScope.problemReporter().duplicateFieldInType(this, previousField); -// previousField.binding = null; -// break; -// } -// } -// } knownFieldNames.put(fieldName, null); // ensure that the duplicate field is found & removed -// libraryScope.problemReporter().duplicateFieldInType(this, field); -// field.binding = null; } else { knownFieldNames.put(fieldName, fieldBinding); // remember that we have seen a field with this name - if (fieldBinding != null) - fieldBindings[count++] = fieldBinding; + fieldBindings[count++] = fieldBinding; } - } - fieldBindings[count++]=prototype; - // remove duplicate fields - if (duplicate) { - FieldBinding[] newFieldBindings = new FieldBinding[fieldBindings.length]; - // we know we'll be removing at least 1 duplicate name - size = count; - count = 0; - for (int i = 0; i < size; i++) { - FieldBinding fieldBinding = fieldBindings[i]; - if (knownFieldNames.get(fieldBinding.name) != null) { - fieldBinding.id = count; - newFieldBindings[count++] = fieldBinding; + } + fieldBindings[count++] = prototype; + // remove duplicate fields + if(duplicate) { + FieldBinding[] newFieldBindings = new FieldBinding[fieldBindings.length]; + // we know we'll be removing at least 1 duplicate name + size = count; + count = 0; + for(int i = 0; i < size; i++) { + FieldBinding fieldBinding = fieldBindings[i]; + if(knownFieldNames.get(fieldBinding.name) != null) { + fieldBinding.id = count; + newFieldBindings[count++] = fieldBinding; + } } + fieldBindings = newFieldBindings; + } + if(count != fieldBindings.length) { + System.arraycopy(fieldBindings, 0, fieldBindings = new FieldBinding[count], 0, count); } - fieldBindings = newFieldBindings; + setFields(fieldBindings); } - if (count != fieldBindings.length) - System.arraycopy(fieldBindings, 0, fieldBindings = new FieldBinding[count], 0, count); - setFields(fieldBindings); -} - + private void buildMethods() { + int methodsSize = (this.classData.methods != null) ? this.classData.methods.length : 0; + int constructorsSize = (this.classData.constructors != null) ? this.classData.constructors.length : 0; + if(constructorsSize + methodsSize == 0) { + setMethods(Binding.NO_METHODS); + return; + } + int count = 0; + MethodBinding[] methodBindings = new MethodBinding[methodsSize + constructorsSize]; + // create bindings for source methods + for(int i = 0; i < methodsSize; i++) { + Method method = this.classData.methods[i]; + MethodBinding methodBinding = createMethodBinding(method, false); -private void buildMethods() { + methodBindings[count++] = methodBinding; + } + for(int i = 0; i < constructorsSize; i++) { + Method method = this.classData.constructors[i]; + MethodBinding methodBinding = createMethodBinding(method, true); + methodBindings[count++] = methodBinding; + } + if(count != methodBindings.length) + System.arraycopy(methodBindings, 0, methodBindings = new MethodBinding[count], 0, count); + tagBits &= ~TagBits.AreMethodsSorted; // in case some static imports reached already into this type + setMethods(methodBindings); + } - int methodsSize = (this.classData.methods!=null)?this.classData.methods.length :0; - int constructorsSize = (this.classData.constructors!=null)?this.classData.constructors.length :0; + private MethodBinding createMethodBinding(Method method, boolean isConstructor) { + int modifiers = ExtraCompilerModifiers.AccUnresolved; + if(method.isStatic()) + modifiers |= ClassFileConstants.AccStatic; + modifiers |= ClassFileConstants.AccPublic; + MethodBinding methodBinding = null; + if(isConstructor) { + methodBinding = new MethodBinding(modifiers, null, this); + methodBinding.tagBits |= TagBits.IsConstructor; + } else { + TypeBinding returnType = (method.returns != null) + ? this.libraryScope.resolveType(method.returns.dataType) : TypeBinding.UNKNOWN; - if (constructorsSize + methodsSize ==0 ) { - setMethods(Binding.NO_METHODS); - return; - } + methodBinding = new MethodBinding(modifiers, method.name.toCharArray(), returnType, null, this); + methodBinding.createFunctionTypeBinding(this.libraryScope); - int count = 0; - MethodBinding[] methodBindings = new MethodBinding[methodsSize+constructorsSize]; - // create bindings for source methods - for (int i = 0; i < methodsSize; i++) { - Method method = this.classData.methods[i]; - MethodBinding methodBinding = createMethodBinding(method,false); + } - - methodBindings[count++] = methodBinding; + methodBinding.oaaMethod = method; + return methodBinding; } - for (int i = 0; i < constructorsSize; i++) { - Method method = this.classData.constructors[i]; - MethodBinding methodBinding = createMethodBinding(method,true); - methodBindings[count++] = methodBinding; - } - if (count != methodBindings.length) - System.arraycopy(methodBindings, 0, methodBindings = new MethodBinding[count], 0, count); - tagBits &= ~TagBits.AreMethodsSorted; // in case some static imports reached already into this type - setMethods(methodBindings); -} - - - -private MethodBinding createMethodBinding(Method method, boolean isConstructor) { - int modifiers = ExtraCompilerModifiers.AccUnresolved; - if (method.isStatic()) - modifiers|=ClassFileConstants.AccStatic; - modifiers|=ClassFileConstants.AccPublic; - MethodBinding methodBinding =null; - if (isConstructor) - { - methodBinding =new MethodBinding(modifiers, null, this); - methodBinding.tagBits|=TagBits.IsConstructor; + + public int kind() { + return Binding.TYPE; } - else - { - TypeBinding returnType = (method.returns!=null ) ? this.libraryScope.resolveType(method.returns.dataType) : TypeBinding.UNKNOWN; -// TypeBinding returnType = -// (method instanceof FunctionDeclaration && ((FunctionDeclaration)method).returnType!=null && method.inferredMethod!=null)?method.inferredType.resolveType(this,((FunctionDeclaration)method).returnType):TypeBinding.ANY; - - methodBinding = - new MethodBinding(modifiers, method.name.toCharArray(), returnType, null, this); - methodBinding.createFunctionTypeBinding(this.libraryScope); + public char[] computeUniqueKey(boolean isLeaf) { + char[] uniqueKey = super.computeUniqueKey(isLeaf); + if(uniqueKey.length == 2) + return uniqueKey; // problem type's unique key is "L;" + if(Util.isClassFileName(this.fileName) + || org.eclipse.wst.jsdt.internal.core.util.Util.isMetadataFileName(new String(this.fileName))) + return uniqueKey; // no need to insert compilation unit name for a .class file + + // insert compilation unit name if the type name is not the main type name + int end = CharOperation.lastIndexOf('.', this.fileName); + if(end != -1) { + int start = CharOperation.lastIndexOf('/', this.fileName) + 1; + char[] mainTypeName = CharOperation.subarray(this.fileName, start, end); + start = CharOperation.lastIndexOf('/', uniqueKey) + 1; + if(start == 0) { + start = 1; // start after L + } + + end = CharOperation.indexOf('$', uniqueKey, start); + if(end == -1) { + end = CharOperation.indexOf('<', uniqueKey, start); + } + + if(end == -1) { + end = CharOperation.indexOf(';', uniqueKey, start); + } + + char[] topLevelType = CharOperation.subarray(uniqueKey, start, end); + if(!CharOperation.equals(topLevelType, mainTypeName)) { + StringBuffer buffer = new StringBuffer(); + buffer.append(uniqueKey, 0, start); + buffer.append(mainTypeName); + buffer.append('~'); + buffer.append(topLevelType); + buffer.append(uniqueKey, end, uniqueKey.length - end); + int length = buffer.length(); + uniqueKey = new char[length]; + buffer.getChars(0, length, uniqueKey, 0); + return uniqueKey; + } + } + return uniqueKey; } - methodBinding.oaaMethod=method; - return methodBinding; -} - - - -public int kind() { - return Binding.TYPE; -} -public char[] computeUniqueKey(boolean isLeaf) { - char[] uniqueKey = super.computeUniqueKey(isLeaf); - if (uniqueKey.length == 2) return uniqueKey; // problem type's unique key is "L;" - if (Util.isClassFileName(this.fileName) - ||org.eclipse.wst.jsdt.internal.core.util.Util.isMetadataFileName(new String(this.fileName))) - return uniqueKey; // no need to insert compilation unit name for a .class file - - // insert compilation unit name if the type name is not the main type name - int end = CharOperation.lastIndexOf('.', this.fileName); - if (end != -1) { - int start = CharOperation.lastIndexOf('/', this.fileName) + 1; - char[] mainTypeName = CharOperation.subarray(this.fileName, start, end); - start = CharOperation.lastIndexOf('/', uniqueKey) + 1; - if (start == 0) - start = 1; // start after L - end = CharOperation.indexOf('$', uniqueKey, start); - if (end == -1) - end = CharOperation.indexOf('<', uniqueKey, start); - if (end == -1) - end = CharOperation.indexOf(';', uniqueKey, start); - char[] topLevelType = CharOperation.subarray(uniqueKey, start, end); - if (!CharOperation.equals(topLevelType, mainTypeName)) { - StringBuffer buffer = new StringBuffer(); - buffer.append(uniqueKey, 0, start); - buffer.append(mainTypeName); - buffer.append('~'); - buffer.append(topLevelType); - buffer.append(uniqueKey, end, uniqueKey.length - end); - int length = buffer.length(); - uniqueKey = new char[length]; - buffer.getChars(0, length, uniqueKey, 0); - return uniqueKey; + void faultInTypesForFieldsAndMethods() { + ReferenceBinding enclosingType = this.enclosingType(); + if(enclosingType != null && enclosingType.isViewedAsDeprecated() && !this.isDeprecated()) { + this.modifiers |= ExtraCompilerModifiers.AccDeprecatedImplicitly; } + fields(); + methods(); } - return uniqueKey; -} -void faultInTypesForFieldsAndMethods() { - // check @Deprecated annotation -// getAnnotationTagBits(); // marks as deprecated by side effect - ReferenceBinding enclosingType = this.enclosingType(); - if (enclosingType != null && enclosingType.isViewedAsDeprecated() && !this.isDeprecated()) - this.modifiers |= ExtraCompilerModifiers.AccDeprecatedImplicitly; - fields(); - methods(); - -// for (int i = 0, length = this.memberTypes.length; i < length; i++) -// ((SourceTypeBinding) this.memberTypes[i]).faultInTypesForFieldsAndMethods(); -} - -// NOTE: the type of each field of a source type is resolved when needed -public FieldBinding[] fields() { - if ((this.tagBits & TagBits.AreFieldsComplete) == 0) - { - if (!fieldsBuilt) - { - buildFields(); - fieldsBuilt=true; - } - - int failed = 0; - FieldBinding[] resolvedFields = this.fields; - try { - // lazily sort fields - if ((this.tagBits & TagBits.AreFieldsSorted) == 0) { - int length = this.fields.length; - if (length > 1) - ReferenceBinding.sortFields(this.fields, 0, length); - this.tagBits |= TagBits.AreFieldsSorted; + + // NOTE: the type of each field of a source type is resolved when needed + public FieldBinding[] fields() { + if((this.tagBits & TagBits.AreFieldsComplete) == 0) { + if(!fieldsBuilt) { + buildFields(); + fieldsBuilt = true; } - for (int i = 0, length = this.fields.length; i < length; i++) { - if (resolveTypeFor(this.fields[i]) == null) { - // do not alter original field array until resolution is over, due to reentrance (143259) - if (resolvedFields == this.fields) { - System.arraycopy(this.fields, 0, resolvedFields = new FieldBinding[length], 0, length); + + int failed = 0; + FieldBinding[] resolvedFields = this.fields; + try { + // lazily sort fields + if((this.tagBits & TagBits.AreFieldsSorted) == 0) { + int length = this.fields.length; + if(length > 1) { + ReferenceBinding.sortFields(this.fields, 0, length); } - resolvedFields[i] = null; - failed++; + this.tagBits |= TagBits.AreFieldsSorted; } - } - } finally { - if (failed > 0) { - // ensure fields are consistent reqardless of the error - int newSize = resolvedFields.length - failed; - if (newSize == 0) - return this.fields = Binding.NO_FIELDS; - - FieldBinding[] newFields = new FieldBinding[newSize]; - for (int i = 0, j = 0, length = resolvedFields.length; i < length; i++) { - if (resolvedFields[i] != null) - newFields[j++] = resolvedFields[i]; + for(int i = 0, length = this.fields.length; i < length; i++) { + if(resolveTypeFor(this.fields[i]) == null) { + // do not alter original field array until resolution is over, due to reentrance (143259) + if(resolvedFields == this.fields) { + System.arraycopy(this.fields, 0, resolvedFields = new FieldBinding[length], 0, length); + } + resolvedFields[i] = null; + failed++; + } + } + } finally { + if(failed > 0) { + // ensure fields are consistent reqardless of the error + int newSize = resolvedFields.length - failed; + if(newSize == 0) { + this.setFields(Binding.NO_FIELDS); + return this.fields; + } + + FieldBinding[] newFields = new FieldBinding[newSize]; + for(int i = 0, j = 0, length = resolvedFields.length; i < length; i++) { + if(resolvedFields[i] != null) { + newFields[j++] = resolvedFields[i]; + } + } + this.setFields(newFields); } - this.fields = newFields; } + this.tagBits |= TagBits.AreFieldsComplete; } - this.tagBits |= TagBits.AreFieldsComplete; + return this.fields; } - return this.fields; -} - -public MethodBinding[] getDefaultAbstractMethods() { - int count = 0; - for (int i = this.methods.length; --i >= 0;) - if (this.methods[i].isDefaultAbstract()) - count++; - if (count == 0) return Binding.NO_METHODS; - - MethodBinding[] result = new MethodBinding[count]; - count = 0; - for (int i = this.methods.length; --i >= 0;) - if (this.methods[i].isDefaultAbstract()) - result[count++] = this.methods[i]; - return result; -} - -public MethodBinding getExactConstructor(TypeBinding[] argumentTypes) { - int argCount = argumentTypes.length; - if ((this.tagBits & TagBits.AreMethodsComplete) != 0) { // have resolved all arg types & return type of the methods - long range; - if ((range = ReferenceBinding.binarySearch(TypeConstants.INIT, this.methods)) >= 0) { -// nextMethod: - for (int imethod = (int)range, end = (int)(range >> 32); imethod <= end; imethod++) { - MethodBinding method = this.methods[imethod]; -// if (method.parameters.length == argCount) { -// TypeBinding[] toMatch = method.parameters; -// for (int iarg = 0; iarg < argCount; iarg++) -// if (toMatch[iarg] != argumentTypes[iarg]) -// continue nextMethod; - return method; -// } + + public MethodBinding[] getDefaultAbstractMethods() { + int count = 0; + for(int i = this.methods.length; --i >= 0;) { + if(this.methods[i].isDefaultAbstract()) { + count++; } } - } else { - if (!methodsBuilt) - { - buildMethods(); - methodsBuilt=true; - } - - // lazily sort methods - if ((this.tagBits & TagBits.AreMethodsSorted) == 0) { - int length = this.methods.length; - if (length > 1) - ReferenceBinding.sortMethods(this.methods, 0, length); - this.tagBits |= TagBits.AreMethodsSorted; + + if(count == 0) { + return Binding.NO_METHODS; } - long range; - if ((range = ReferenceBinding.binarySearch(TypeConstants.INIT, this.methods)) >= 0) { -// nextMethod: - for (int imethod = (int)range, end = (int)(range >> 32); imethod <= end; imethod++) { - MethodBinding method = this.methods[imethod]; - if (resolveTypesFor(method) == null || method.returnType == null) { - methods(); - return getExactConstructor(argumentTypes); // try again since the problem methods have been removed - } -// if (method.parameters.length == argCount) { -// TypeBinding[] toMatch = method.parameters; -// for (int iarg = 0; iarg < argCount; iarg++) -// if (toMatch[iarg] != argumentTypes[iarg]) -// continue nextMethod; -// return method; -// } - return method; + + MethodBinding[] result = new MethodBinding[count]; + count = 0; + for(int i = this.methods.length; --i >= 0;) { + if(this.methods[i].isDefaultAbstract()) { + result[count++] = this.methods[i]; } } + return result; } - return null; -} - - -public MethodBinding getExactMethod(char[] selector, TypeBinding[] argumentTypes, CompilationUnitScope refScope) { - // sender from refScope calls recordTypeReference(this) -// int argCount = argumentTypes.length; - boolean foundNothing = true; - - if ((this.tagBits & TagBits.AreMethodsComplete) != 0) { // have resolved all arg types & return type of the methods - long range; - if ((range = ReferenceBinding.binarySearch(selector, this.methods)) >= 0) { -// nextMethod: - for (int imethod = (int)range, end = (int)(range >> 32); imethod <= end; imethod++) { - MethodBinding method = this.methods[imethod]; - foundNothing = false; // inner type lookups must know that a method with this name exists -// if (method.parameters.length == argCount) { -// TypeBinding[] toMatch = method.parameters; -// for (int iarg = 0; iarg < argCount; iarg++) -// if (toMatch[iarg] != argumentTypes[iarg]) -// { -// if (toMatch[iarg].id!=TypeIds.T_any && argumentTypes[iarg].id!=TypeIds.T_any) -// continue nextMethod; -// } -// return method; -// } - return method; + + public MethodBinding getExactConstructor(TypeBinding[] argumentTypes) { + // have resolved all arg types & return type of the methods + if((this.tagBits & TagBits.AreMethodsComplete) != 0) { + long range; + if((range = ReferenceBinding.binarySearch(TypeConstants.INIT, this.methods)) >= 0) { + if((int) range <= (int) (range >> 32)) { + MethodBinding method = this.methods[(int) range]; + return method; + } + } + } else { + if(!methodsBuilt) { + buildMethods(); + methodsBuilt = true; + } + + // lazily sort methods + if((this.tagBits & TagBits.AreMethodsSorted) == 0) { + int length = this.methods.length; + if(length > 1) + ReferenceBinding.sortMethods(this.methods, 0, length); + this.tagBits |= TagBits.AreMethodsSorted; + } + long range; + if((range = ReferenceBinding.binarySearch(TypeConstants.INIT, this.methods)) >= 0) { + + if((int) range <= (int) (range >> 32)) { + MethodBinding method = this.methods[(int) range]; + if(resolveTypesFor(method) == null || method.returnType == null) { + methods(); + // try again since the problem methods have been removed + return getExactConstructor(argumentTypes); + } + return method; + } } } - } else { - if (!methodsBuilt) - { - buildMethods(); - methodsBuilt=true; - } - // lazily sort methods - if ((this.tagBits & TagBits.AreMethodsSorted) == 0) { - int length = this.methods.length; - if (length > 1) - ReferenceBinding.sortMethods(this.methods, 0, length); - this.tagBits |= TagBits.AreMethodsSorted; - } + return null; + } - long range; - if ((range = ReferenceBinding.binarySearch(selector, this.methods)) >= 0) { - // check unresolved method - int start = (int) range, end = (int) (range >> 32); - for (int imethod = start; imethod <= end; imethod++) { - MethodBinding method = this.methods[imethod]; - if (resolveTypesFor(method) == null || method.returnType == null) { - methods(); - return getExactMethod(selector, argumentTypes, refScope); // try again since the problem methods have been removed + public MethodBinding getExactMethod(char[] selector, TypeBinding[] argumentTypes, CompilationUnitScope refScope) { + // sender from refScope calls recordTypeReference(this) + boolean foundNothing = true; + + if((this.tagBits & TagBits.AreMethodsComplete) != 0) { // have resolved all arg types & return type of the methods + long range; + if((range = ReferenceBinding.binarySearch(selector, this.methods)) >= 0) { + if((int) range <= (int) (range >> 32)) { + MethodBinding method = this.methods[(int)range]; + foundNothing = false; // inner type lookups must know that a method with this name exists + return method; } } - // check dup collisions - boolean isSource15 = this.scope.compilerOptions().sourceLevel >= ClassFileConstants.JDK1_5; - for (int i = start; i <= end; i++) { - MethodBinding method1 = this.methods[i]; - for (int j = end; j > i; j--) { - MethodBinding method2 = this.methods[j]; - boolean paramsMatch = isSource15 - ? method1.areParametersEqual(method2) - : method1.areParametersEqual(method2); - if (paramsMatch) { + } else { + if(!methodsBuilt) { + buildMethods(); + methodsBuilt = true; + } + // lazily sort methods + if((this.tagBits & TagBits.AreMethodsSorted) == 0) { + int length = this.methods.length; + if(length > 1) + ReferenceBinding.sortMethods(this.methods, 0, length); + this.tagBits |= TagBits.AreMethodsSorted; + } + + long range; + if((range = ReferenceBinding.binarySearch(selector, this.methods)) >= 0) { + // check unresolved method + int start = (int) range, end = (int) (range >> 32); + for(int imethod = start; imethod <= end; imethod++) { + MethodBinding method = this.methods[imethod]; + if(resolveTypesFor(method) == null || method.returnType == null) { methods(); return getExactMethod(selector, argumentTypes, refScope); // try again since the problem methods have been removed } } + // check dup collisions + boolean isSource15 = this.scope.compilerOptions().sourceLevel >= ClassFileConstants.JDK1_5; + for(int i = start; i <= end; i++) { + MethodBinding method1 = this.methods[i]; + for(int j = end; j > i; j--) { + MethodBinding method2 = this.methods[j]; + boolean paramsMatch = isSource15 + ? method1.areParametersEqual(method2) : method1.areParametersEqual(method2); + if(paramsMatch) { + methods(); + return getExactMethod(selector, argumentTypes, refScope); // try again since the problem methods have been removed + } + } + } + return this.methods[start]; } - return this.methods[start]; -// nextMethod: for (int imethod = start; imethod <= end; imethod++) { -// FunctionBinding method = this.methods[imethod]; -// TypeBinding[] toMatch = method.parameters; -// if (toMatch.length == argCount) { -// for (int iarg = 0; iarg < argCount; iarg++) -// if (toMatch[iarg] != argumentTypes[iarg]) -// continue nextMethod; -// return method; -// } -// } } - } - if (foundNothing) { - if (this.superclass != null && this.superclass!=this) { - if (refScope != null) - refScope.recordTypeReference(this.superclass); - return this.superclass.getExactMethod(selector, argumentTypes, refScope); + if(foundNothing) { + if(this.getSuperBinding0() != null && this.getSuperBinding0() != this) { + if(refScope != null) + refScope.recordTypeReference(this.getSuperBinding0()); + return this.getSuperBinding0().getExactMethod(selector, argumentTypes, refScope); + } } + return null; } - return null; -} - -public FieldBinding getField(char[] fieldName, boolean needResolve) { + public FieldBinding getField(char[] fieldName, boolean needResolve) { - if ((this.tagBits & TagBits.AreFieldsComplete) != 0) - return ReferenceBinding.binarySearch(fieldName, this.fields); + if((this.tagBits & TagBits.AreFieldsComplete) != 0) + return ReferenceBinding.binarySearch(fieldName, this.fields); - if (!fieldsBuilt) - { - buildFields(); - fieldsBuilt=true; - } + if(!fieldsBuilt) { + buildFields(); + fieldsBuilt = true; + } - - // lazily sort fields - if ((this.tagBits & TagBits.AreFieldsSorted) == 0) { - int length = this.fields.length; - if (length > 1) - ReferenceBinding.sortFields(this.fields, 0, length); - this.tagBits |= TagBits.AreFieldsSorted; - } - // always resolve anyway on source types - FieldBinding field = ReferenceBinding.binarySearch(fieldName, this.fields); - if (field != null) { - FieldBinding result = null; - try { - result = resolveTypeFor(field); - return result; - } finally { - if (result == null) { - // ensure fields are consistent reqardless of the error - int newSize = this.fields.length - 1; - if (newSize == 0) { - this.fields = Binding.NO_FIELDS; - } else { - FieldBinding[] newFields = new FieldBinding[newSize]; - int index = 0; - for (int i = 0, length = this.fields.length; i < length; i++) { - FieldBinding f = this.fields[i]; - if (f == field) continue; - newFields[index++] = f; + // lazily sort fields + if((this.tagBits & TagBits.AreFieldsSorted) == 0) { + int length = this.fields.length; + if(length > 1) + ReferenceBinding.sortFields(this.fields, 0, length); + this.tagBits |= TagBits.AreFieldsSorted; + } + // always resolve anyway on source types + FieldBinding field = ReferenceBinding.binarySearch(fieldName, this.fields); + if(field != null) { + FieldBinding result = null; + try { + result = resolveTypeFor(field); + return result; + } finally { + if(result == null) { + // ensure fields are consistent reqardless of the error + int newSize = this.fields.length - 1; + if(newSize == 0) { + this.setFields(Binding.NO_FIELDS); + } else { + FieldBinding[] newFields = new FieldBinding[newSize]; + int index = 0; + for(int i = 0, length = this.fields.length; i < length; i++) { + FieldBinding f = this.fields[i]; + if(f == field) + continue; + newFields[index++] = f; + } + this.setFields(newFields); } - this.fields = newFields; } } } + return null; } - return null; -} -public MethodBinding[] getMethods(char[] selector) { - if ((this.tagBits & TagBits.AreMethodsComplete) != 0) { + public MethodBinding[] getMethods(char[] selector) { + if((this.tagBits & TagBits.AreMethodsComplete) != 0) { + long range; + if((range = ReferenceBinding.binarySearch(selector, this.methods)) >= 0) { + int start = (int) range, end = (int) (range >> 32); + int length = end - start + 1; + MethodBinding[] result; + System.arraycopy(this.methods, start, result = new MethodBinding[length], 0, length); + return result; + } else { + return Binding.NO_METHODS; + } + } + + if(!methodsBuilt) { + buildMethods(); + methodsBuilt = true; + } + + // lazily sort methods + if((this.tagBits & TagBits.AreMethodsSorted) == 0) { + int length = this.methods.length; + if(length > 1) + ReferenceBinding.sortMethods(this.methods, 0, length); + this.tagBits |= TagBits.AreMethodsSorted; + } + MethodBinding[] result; long range; - if ((range = ReferenceBinding.binarySearch(selector, this.methods)) >= 0) { + if((range = ReferenceBinding.binarySearch(selector, this.methods)) >= 0) { int start = (int) range, end = (int) (range >> 32); + for(int i = start; i <= end; i++) { + MethodBinding method = this.methods[i]; + if(resolveTypesFor(method) == null || method.returnType == null) { + methods(); + return getMethods(selector); // try again since the problem methods have been removed + } + } int length = end - start + 1; - MethodBinding[] result; System.arraycopy(this.methods, start, result = new MethodBinding[length], 0, length); - return result; } else { return Binding.NO_METHODS; } - } - - if (!methodsBuilt) - { - buildMethods(); - methodsBuilt=true; - } - - // lazily sort methods - if ((this.tagBits & TagBits.AreMethodsSorted) == 0) { - int length = this.methods.length; - if (length > 1) - ReferenceBinding.sortMethods(this.methods, 0, length); - this.tagBits |= TagBits.AreMethodsSorted; - } - MethodBinding[] result; - long range; - if ((range = ReferenceBinding.binarySearch(selector, this.methods)) >= 0) { - int start = (int) range, end = (int) (range >> 32); - for (int i = start; i <= end; i++) { - MethodBinding method = this.methods[i]; - if (resolveTypesFor(method) == null || method.returnType == null) { - methods(); - return getMethods(selector); // try again since the problem methods have been removed + boolean isSource15 = this.libraryScope.compilerOptions().sourceLevel >= ClassFileConstants.JDK1_5; + for(int i = 0, length = result.length - 1; i < length; i++) { + MethodBinding method = result[i]; + for(int j = length; j > i; j--) { + boolean paramsMatch = isSource15 + ? method.areParametersEqual(result[j]) : method.areParametersEqual(result[j]); + if(paramsMatch) { + methods(); + return getMethods(selector); // try again since the duplicate methods have been removed + } } } - int length = end - start + 1; - System.arraycopy(this.methods, start, result = new MethodBinding[length], 0, length); - } else { - return Binding.NO_METHODS; + return result; } - boolean isSource15 = this.libraryScope.compilerOptions().sourceLevel >= ClassFileConstants.JDK1_5; - for (int i = 0, length = result.length - 1; i < length; i++) { - MethodBinding method = result[i]; - for (int j = length; j > i; j--) { - boolean paramsMatch = isSource15 - ? method.areParametersEqual(result[j]) - : method.areParametersEqual(result[j]); - if (paramsMatch) { - methods(); - return getMethods(selector); // try again since the duplicate methods have been removed - } + + /** + * Returns true if a type is identical to another one, + * or for generic types, true if compared to its raw type. + */ + public boolean isEquivalentTo(TypeBinding otherType) { + if(this == otherType) { + return true; + } if(otherType == null) { + return false; } + return false; } - return result; -} - -/** - * Returns true if a type is identical to another one, - * or for generic types, true if compared to its raw type. - */ -public boolean isEquivalentTo(TypeBinding otherType) { - - if (this == otherType) return true; - if (otherType == null) return false; - return false; -} -public ReferenceBinding[] memberTypes() { - if (this.nextType==null) - return this.memberTypes; - - ReferenceBinding[] moreTypes=this.nextType.memberTypes(); - ReferenceBinding[] combinedTypes=new ReferenceBinding[this.memberTypes.length+moreTypes.length]; - System.arraycopy(this.memberTypes, 0, combinedTypes, 0, this.memberTypes.length); - System.arraycopy(moreTypes, 0, combinedTypes, this.memberTypes.length, moreTypes.length); - - return combinedTypes; - -} -public boolean hasMemberTypes() { - boolean hasMembers= this.memberTypes!=null && this.memberTypes.length > 0; - if (!hasMembers && this.nextType!=null) - hasMembers=this.nextType.hasMemberTypes(); - return hasMembers; -} -// NOTE: the return type, arg & exception types of each method of a source type are resolved when needed -public MethodBinding[] methods() { - - if ((this.tagBits & TagBits.AreMethodsComplete) == 0) { - if (!methodsBuilt) - { - buildMethods(); - methodsBuilt=true; - } - // lazily sort methods - if ((this.tagBits & TagBits.AreMethodsSorted) == 0) { - int length = this.methods.length; - if (length > 1) - ReferenceBinding.sortMethods(this.methods, 0, length); - this.tagBits |= TagBits.AreMethodsSorted; - } - int failed = 0; - MethodBinding[] resolvedMethods = this.methods; - try { - for (int i = 0, length = this.methods.length; i < length; i++) { - if (resolveTypesFor(this.methods[i]) == null) { - // do not alter original method array until resolution is over, due to reentrance (143259) - if (resolvedMethods == this.methods) { - System.arraycopy(this.methods, 0, - resolvedMethods = new MethodBinding[length], 0, - length); + + // NOTE: the return type, arg & exception types of each method of a source type are resolved when needed + public MethodBinding[] methods() { + + if((this.tagBits & TagBits.AreMethodsComplete) == 0) { + if(!methodsBuilt) { + buildMethods(); + methodsBuilt = true; + } + // lazily sort methods + if((this.tagBits & TagBits.AreMethodsSorted) == 0) { + int length = this.methods.length; + if(length > 1) + ReferenceBinding.sortMethods(this.methods, 0, length); + this.tagBits |= TagBits.AreMethodsSorted; + } + int failed = 0; + MethodBinding[] resolvedMethods = this.methods; + try { + for(int i = 0, length = this.methods.length; i < length; i++) { + if(resolveTypesFor(this.methods[i]) == null) { + // do not alter original method array until resolution is over, due to reentrance (143259) + if(resolvedMethods == this.methods) { + System.arraycopy(this.methods, 0, resolvedMethods = new MethodBinding[length], 0, length); + } + resolvedMethods[i] = null; // unable to resolve parameters + failed++; } - resolvedMethods[i] = null; // unable to resolve parameters - failed++; } - } - // find & report collision cases - - boolean complyTo15 = - (this.libraryScope!=null && this.libraryScope.compilerOptions().sourceLevel >= ClassFileConstants.JDK1_5); - for (int i = 0, length = this.methods.length; i < length; i++) { - MethodBinding method = resolvedMethods[i]; - if (method == null) - continue; - char[] selector = method.selector; -// AbstractMethodDeclaration methodDecl = null; - nextSibling: for (int j = i + 1; j < length; j++) { - MethodBinding method2 = resolvedMethods[j]; - if (method2 == null) - continue nextSibling; - if (!CharOperation.equals(selector, method2.selector)) - break nextSibling; // methods with same selector are contiguous - - if (complyTo15 && method.returnType != null - && method2.returnType != null) { - // 8.4.2, for collision to be detected between m1 and m2: - // signature(m1) == signature(m2) i.e. same arity, same type parameter count, can be substituted - // signature(m1) == erasure(signature(m2)) or erasure(signature(m1)) == signature(m2) - TypeBinding[] params1 = method.parameters; - TypeBinding[] params2 = method2.parameters; - int pLength = params1.length; - if (pLength != params2.length) + // find & report collision cases + boolean complyTo15 = (this.libraryScope != null && this.libraryScope.compilerOptions().sourceLevel >= ClassFileConstants.JDK1_5); + for(int i = 0, length = this.methods.length; i < length; i++) { + MethodBinding method = resolvedMethods[i]; + if(method == null) + continue; + char[] selector = method.selector; + + nextSibling: for(int j = i + 1; j < length; j++) { + MethodBinding method2 = resolvedMethods[j]; + if(method2 == null) continue nextSibling; + if(!CharOperation.equals(selector, method2.selector)) + break nextSibling; // methods with same selector are contiguous + + if(complyTo15 && method.returnType != null && method2.returnType != null) { + // 8.4.2, for collision to be detected between m1 and m2: + // signature(m1) == signature(m2) i.e. same arity, same type parameter count, can be substituted + // signature(m1) == erasure(signature(m2)) or erasure(signature(m1)) == signature(m2) + TypeBinding[] params1 = method.parameters; + TypeBinding[] params2 = method2.parameters; + int pLength = params1.length; + if(pLength != params2.length) + continue nextSibling; - boolean equalTypeVars = true; - MethodBinding subMethod = method2; - if (!equalTypeVars) { - MethodBinding temp = method2; - if (temp != null) { + boolean equalTypeVars = true; + MethodBinding subMethod = method2; + if(!equalTypeVars) { + MethodBinding temp = method2; equalTypeVars = true; subMethod = temp; } - } - boolean equalParams = method - .areParametersEqual(subMethod); - if (equalParams && equalTypeVars) { - // duplicates regardless of return types - } else if (method.returnType == subMethod.returnType - && (equalParams || method - .areParametersEqual(method2))) { - // name clash for sure if not duplicates, report as duplicates - } else if (pLength > 0) { - // check to see if the erasure of either method is equal to the other - int index = pLength; - for (; --index >= 0;) { - if (params1[index] != params2[index]) - break; - } - if (index >= 0 && index < pLength) { - for (index = pLength; --index >= 0;) - if (params1[index] != params2[index]) + boolean equalParams = method.areParametersEqual(subMethod); + if(equalParams && equalTypeVars) { + // duplicates regardless of return types + } else if(method.returnType == subMethod.returnType + && (equalParams || method.areParametersEqual(method2))) { + + // name clash for sure if not duplicates, report as duplicates + } else if(pLength > 0) { + // check to see if the erasure of either method is equal to the other + int index = pLength; + for(; --index >= 0;) { + if(params1[index] != params2[index]) { break; + } + } + if(index >= 0 && index < pLength) { + for(index = pLength; --index >= 0;) { + if(params1[index] != params2[index]) { + break; + } + } + } + if(index >= 0) { + continue nextSibling; + } } - if (index >= 0) - continue nextSibling; + } else if(!method.areParametersEqual(method2)) { // prior to 1.5, parameter identity meant a collision case + continue nextSibling; } - } else if (!method.areParametersEqual(method2)) { // prior to 1.5, parameter identity meant a collision case - continue nextSibling; } - // report duplicate -// if (methodDecl == null) { -// methodDecl = method.sourceMethod(); // cannot be retrieved after binding is lost & may still be null if method is special -// if (methodDecl != null && methodDecl.binding != null) { // ensure its a valid user defined method -// if (isEnumSpecialMethod) { -// this.libraryScope.problemReporter() -// .duplicateEnumSpecialMethod(this, -// methodDecl); -// } else { -// this.libraryScope -// .problemReporter() -// .duplicateMethodInType(this, methodDecl); -// } -// methodDecl.binding = null; -// // do not alter original method array until resolution is over, due to reentrance (143259) -// if (resolvedMethods == this.methods) { -// System -// .arraycopy( -// this.methods, -// 0, -// resolvedMethods = new FunctionBinding[length], -// 0, length); -// } -// resolvedMethods[i] = null; -// failed++; -// } -// } -// AbstractMethodDeclaration method2Decl = method2 -// .sourceMethod(); -// if (method2Decl != null && method2Decl.binding != null) { // ensure its a valid user defined method -// if (isEnumSpecialMethod) { -// this.libraryScope.problemReporter() -// .duplicateEnumSpecialMethod(this, -// method2Decl); -// } else { -// this.libraryScope.problemReporter().duplicateMethodInType( -// this, method2Decl); -// } -// method2Decl.binding = null; -// // do not alter original method array until resolution is over, due to reentrance (143259) -// if (resolvedMethods == this.methods) { -// System -// .arraycopy( -// this.methods, -// 0, -// resolvedMethods = new FunctionBinding[length], -// 0, length); -// } -// resolvedMethods[j] = null; -// failed++; -// } } -// if (method.returnType == null && methodDecl == null) { // forget method with invalid return type... was kept to detect possible collisions -// methodDecl = method.sourceMethod(); -// if (methodDecl != null) { -// methodDecl.binding = null; -// } -// // do not alter original method array until resolution is over, due to reentrance (143259) -// if (resolvedMethods == this.methods) { -// System.arraycopy(this.methods, 0, -// resolvedMethods = new FunctionBinding[length], 0, -// length); -// } -// resolvedMethods[i] = null; -// failed++; -// } - } - } finally { - if (failed > 0) { - int newSize = resolvedMethods.length - failed; - if (newSize == 0) { - this.methods = Binding.NO_METHODS; - } else { - MethodBinding[] newMethods = new MethodBinding[newSize]; - for (int i = 0, j = 0, length = resolvedMethods.length; i < length; i++) - if (resolvedMethods[i] != null) - newMethods[j++] = resolvedMethods[i]; - this.methods = newMethods; + } finally { + if(failed > 0) { + int newSize = resolvedMethods.length - failed; + if(newSize == 0) { + this.setMethods(Binding.NO_METHODS); + } else { + MethodBinding[] newMethods = new MethodBinding[newSize]; + for(int i = 0, j = 0, length = resolvedMethods.length; i < length; i++) + if(resolvedMethods[i] != null) + newMethods[j++] = resolvedMethods[i]; + this.setMethods(newMethods); + } } - } - // handle forward references to potential default abstract methods - // addDefaultAbstractMethods(); - this.tagBits |= TagBits.AreMethodsComplete; + this.tagBits |= TagBits.AreMethodsComplete; + } } + + return this.methods; } - if (this.nextType!=null) - { - MethodBinding[] moreMethods=this.nextType.methods(); - MethodBinding[] combinedMethods=new MethodBinding[this.methods.length+moreMethods.length]; - System.arraycopy(this.methods, 0, combinedMethods, 0, this.methods.length); - System.arraycopy(moreMethods, 0, combinedMethods, this.methods.length, moreMethods.length); - return combinedMethods; + private FieldBinding resolveTypeFor(FieldBinding field) { + if((field.modifiers & ExtraCompilerModifiers.AccUnresolved) == 0) { + return field; + } + if(isViewedAsDeprecated() && !field.isDeprecated()) { + field.modifiers |= ExtraCompilerModifiers.AccDeprecatedImplicitly; + } if(hasRestrictedAccess()) { + field.modifiers |= ExtraCompilerModifiers.AccRestrictedAccess; + } + + return field; } - else - return this.methods; -} -private FieldBinding resolveTypeFor(FieldBinding field) { - if ((field.modifiers & ExtraCompilerModifiers.AccUnresolved) == 0) - return field; + public MethodBinding resolveTypesFor(MethodBinding method) { + if((method.modifiers & ExtraCompilerModifiers.AccUnresolved) == 0) { + return method; + } - if (isViewedAsDeprecated() && !field.isDeprecated()) - field.modifiers |= ExtraCompilerModifiers.AccDeprecatedImplicitly; - if (hasRestrictedAccess()) - field.modifiers |= ExtraCompilerModifiers.AccRestrictedAccess; - return field; -} -public MethodBinding resolveTypesFor(MethodBinding method) { - if ((method.modifiers & ExtraCompilerModifiers.AccUnresolved) == 0) - return method; - - if (isViewedAsDeprecated() && !method.isDeprecated()) - method.modifiers |= ExtraCompilerModifiers.AccDeprecatedImplicitly; - if (hasRestrictedAccess()) - method.modifiers |= ExtraCompilerModifiers.AccRestrictedAccess; - - Method methodDecl = method.oaaMethod; - if (methodDecl == null) return null; // method could not be resolved in previous iteration - - - boolean foundArgProblem = false; - Parameter[] arguments = methodDecl.parameters; - if (arguments != null) { - int size = arguments.length; - method.parameters = Binding.NO_PARAMETERS; - TypeBinding[] newParameters = new TypeBinding[size]; - for (int i = 0; i < size; i++) { - Parameter arg = arguments[i]; - TypeBinding parameterType = TypeBinding.UNKNOWN; - parameterType = libraryScope.resolveType(arg.dataType) ; - - -// else - if (parameterType == TypeBinding.VOID) { -// scope.problemReporter().argumentTypeCannotBeVoid(this, methodDecl, arg); - foundArgProblem = true; - } else { - TypeBinding leafType = parameterType.leafComponentType(); - newParameters[i] = parameterType; - } + if(isViewedAsDeprecated() && !method.isDeprecated()) { + method.modifiers |= ExtraCompilerModifiers.AccDeprecatedImplicitly; + } + + if(hasRestrictedAccess()) { + method.modifiers |= ExtraCompilerModifiers.AccRestrictedAccess; } - // only assign parameters if no problems are found - if (!foundArgProblem) - method.parameters = newParameters; - } - boolean foundReturnTypeProblem = false; - if (foundArgProblem) { - method.parameters = Binding.NO_PARAMETERS; // see 107004 - // nullify type parameter bindings as well as they have a backpointer to the method binding - // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=81134) - return null; - } - if (foundReturnTypeProblem) - return method; // but its still unresolved with a null return type & is still connected to its method declaration - - method.modifiers &= ~ExtraCompilerModifiers.AccUnresolved; - return method; -} -public void setFields(FieldBinding[] fields) { -// if (this.nextType!=null) -// throw new UnimplementedException("should not get here"); //$NON-NLS-1$ - - this.fields = fields; -} -public void setMethods(MethodBinding[] methods) { -// if (this.nextType!=null) -// throw new UnimplementedException("should not get here"); //$NON-NLS-1$ - this.methods = methods; -} -public final int sourceEnd() { -return -1; -} -public final int sourceStart() { - return -1; -} -public ReferenceBinding superclass() { - return this.superclass; - -} -public String toString() { - StringBuffer buffer = new StringBuffer(30); - buffer.append("(id="); //$NON-NLS-1$ - if (this.id == TypeIds.NoId) - buffer.append("NoId"); //$NON-NLS-1$ - else - buffer.append(this.id); - buffer.append(")\n"); //$NON-NLS-1$ - if (isDeprecated()) buffer.append("deprecated "); //$NON-NLS-1$ - if (isPublic()) buffer.append("public "); //$NON-NLS-1$ - if (isPrivate()) buffer.append("private "); //$NON-NLS-1$ - if (isStatic() && isNestedType()) buffer.append("static "); //$NON-NLS-1$ - - if (isClass()) buffer.append("class "); //$NON-NLS-1$ - else buffer.append("interface "); //$NON-NLS-1$ - buffer.append((this.compoundName != null) ? CharOperation.toString(this.compoundName) : "UNNAMED TYPE"); //$NON-NLS-1$ - - buffer.append("\n\textends "); //$NON-NLS-1$ - buffer.append((this.superclass != null) ? this.superclass.debugName() : "NULL TYPE"); //$NON-NLS-1$ - - if (enclosingType() != null) { - buffer.append("\n\tenclosing type : "); //$NON-NLS-1$ - buffer.append(enclosingType().debugName()); - } + Method methodDecl = method.oaaMethod; + if(methodDecl == null) { + return null; // method could not be resolved in previous iteration + } - if (this.fields != null) { - if (this.fields != Binding.NO_FIELDS) { - buffer.append("\n/* fields */"); //$NON-NLS-1$ - for (int i = 0, length = this.fields.length; i < length; i++) - buffer.append('\n').append((this.fields[i] != null) ? this.fields[i].toString() : "NULL FIELD"); //$NON-NLS-1$ + boolean foundArgProblem = false; + Parameter[] arguments = methodDecl.parameters; + if(arguments != null) { + int size = arguments.length; + method.setParameters(Binding.NO_PARAMETERS); + TypeBinding[] newParameters = new TypeBinding[size]; + for(int i = 0; i < size; i++) { + Parameter arg = arguments[i]; + TypeBinding parameterType = TypeBinding.UNKNOWN; + parameterType = libraryScope.resolveType(arg.dataType); + + if(parameterType == TypeBinding.VOID) { + foundArgProblem = true; + } else { + parameterType.leafComponentType(); + newParameters[i] = parameterType; + } + } + // only assign parameters if no problems are found + if(!foundArgProblem) + method.setParameters(newParameters); } - } else { - buffer.append("NULL FIELDS"); //$NON-NLS-1$ - } - if (this.methods != null) { - if (this.methods != Binding.NO_METHODS) { - buffer.append("\n/* methods */"); //$NON-NLS-1$ - for (int i = 0, length = this.methods.length; i < length; i++) - buffer.append('\n').append((this.methods[i] != null) ? this.methods[i].toString() : "NULL METHOD"); //$NON-NLS-1$ + boolean foundReturnTypeProblem = false; + if(foundArgProblem) { + method.setParameters(Binding.NO_PARAMETERS); // see 107004 + // nullify type parameter bindings as well as they have a backpointer to the method binding + // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=81134) + return null; } - } else { - buffer.append("NULL METHODS"); //$NON-NLS-1$ + if(foundReturnTypeProblem) + return method; // but its still unresolved with a null return type & is still connected to its method declaration + + method.modifiers &= ~ExtraCompilerModifiers.AccUnresolved; + return method; } - if (this.memberTypes != null) { - if (this.memberTypes != Binding.NO_MEMBER_TYPES) { - buffer.append("\n/* members */"); //$NON-NLS-1$ - for (int i = 0, length = this.memberTypes.length; i < length; i++) - buffer.append('\n').append((this.memberTypes[i] != null) ? this.memberTypes[i].toString() : "NULL TYPE"); //$NON-NLS-1$ - } - } else { - buffer.append("NULL MEMBER TYPES"); //$NON-NLS-1$ + public final int sourceEnd() { + return -1; } - buffer.append("\n\n"); //$NON-NLS-1$ - return buffer.toString(); -} -void verifyMethods(MethodVerifier verifier) { - //verifier.verify(this); + public final int sourceStart() { + return -1; + } -// for (int i = this.memberTypes.length; --i >= 0;) -// ((SourceTypeBinding) this.memberTypes[i]).verifyMethods(verifier); -} + public ReferenceBinding getSuperBinding() { + return this.getSuperBinding0(); -public AbstractMethodDeclaration sourceMethod(MethodBinding binding) { - return null; -} + } -public void addMethod(MethodBinding binding) -{ - int length=this.methods.length; - System.arraycopy(this.methods, 0, this.methods=new MethodBinding[length+1], 0, length); - this.methods[length]=binding; + public String toString() { + StringBuffer buffer = new StringBuffer(30); + buffer.append("(id="); //$NON-NLS-1$ + if(this.id == TypeIds.NoId) + buffer.append("NoId"); //$NON-NLS-1$ + else + buffer.append(this.id); + buffer.append(")\n"); //$NON-NLS-1$ + if(isDeprecated()) + buffer.append("deprecated "); //$NON-NLS-1$ + if(isPublic()) + buffer.append("public "); //$NON-NLS-1$ + if(isPrivate()) + buffer.append("private "); //$NON-NLS-1$ + if(isStatic() && isNestedType()) + buffer.append("static "); //$NON-NLS-1$ + + if(isClass()) + buffer.append("class "); //$NON-NLS-1$ + else + buffer.append("interface "); //$NON-NLS-1$ + buffer.append((this.compoundName != null) ? CharOperation.toString(this.compoundName) : "UNNAMED TYPE"); //$NON-NLS-1$ + + buffer.append("\n\textends "); //$NON-NLS-1$ + buffer.append((this.getSuperBinding0() != null) ? this.getSuperBinding0().debugName() : "NULL TYPE"); //$NON-NLS-1$ + + if(enclosingType() != null) { + buffer.append("\n\tenclosing type : "); //$NON-NLS-1$ + buffer.append(enclosingType().debugName()); + } -} + if(this.fields != null) { + if(this.fields != Binding.NO_FIELDS) { + buffer.append("\n/* fields */"); //$NON-NLS-1$ + for(int i = 0, length = this.fields.length; i < length; i++) + buffer.append('\n').append((this.fields[i] != null) ? this.fields[i].toString() : "NULL FIELD"); //$NON-NLS-1$ + } + } else { + buffer.append("NULL FIELDS"); //$NON-NLS-1$ + } -public void cleanup() -{ -this.scope=null; -this.classScope=null; -super.cleanup(); -// clean up should be called for each compilation unit, so it shouldnt be necessary to chain the cleanups -//if (this.nextType!=null) -// this.nextType.cleanup(); -} + if(this.methods != null) { + if(this.methods != Binding.NO_METHODS) { + buffer.append("\n/* methods */"); //$NON-NLS-1$ + for(int i = 0, length = this.methods.length; i < length; i++) + buffer.append('\n').append((this.methods[i] != null) ? this.methods[i].toString() : "NULL METHOD"); //$NON-NLS-1$ + } + } else { + buffer.append("NULL METHODS"); //$NON-NLS-1$ + } + if(this.memberTypes != null) { + if(this.memberTypes != Binding.NO_MEMBER_TYPES) { + buffer.append("\n/* members */"); //$NON-NLS-1$ + for(int i = 0, length = this.memberTypes.length; i < length; i++) + buffer.append('\n').append( + (this.memberTypes[i] != null) ? this.memberTypes[i].toString() : "NULL TYPE"); //$NON-NLS-1$ + } + } else { + buffer.append("NULL MEMBER TYPES"); //$NON-NLS-1$ + } -public boolean contains(ReferenceBinding binding) -{ - return false; -} + buffer.append("\n\n"); //$NON-NLS-1$ + return buffer.toString(); + } -public ClassData getClassData() -{ - return this.classData; -} + void verifyMethods(MethodVerifier verifier) { + } + public AbstractMethodDeclaration sourceMethod(MethodBinding binding) { + return null; + } -public LibraryAPIsScope getLibraryAPIsScope() -{ - return this.libraryScope; -} + public void cleanup() { + this.scope = null; + this.classScope = null; + super.cleanup(); + } -} + public boolean contains(ReferenceBinding binding) { + return false; + } + + public ClassData getClassData() { + return this.classData; + } + + public LibraryAPIsScope getLibraryAPIsScope() { + return this.libraryScope; + } +} \ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MethodBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MethodBinding.java index 78a92555..8c353f4f 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MethodBinding.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MethodBinding.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -26,205 +26,163 @@ public class MethodBinding extends Binding { public FunctionTypeBinding functionTypeBinding; public ReferenceBinding allocationType; public Method oaaMethod; + + /** + *

+ * {@link MethodBinding} used to create this {@link MethodBinding}. + *

+ */ + private MethodBinding fOriginal; + protected MethodBinding() { + // for creating problem or synthetic method + } -protected MethodBinding() { - // for creating problem or synthetic method -} -public MethodBinding(int modifiers, char[] selector, TypeBinding returnType, TypeBinding[] parameters, ReferenceBinding declaringClass) { - this.modifiers = modifiers; - this.selector = selector; - this.returnType = returnType; - this.parameters = (parameters == null || parameters.length == 0) ? Binding.NO_PARAMETERS : parameters; - this.declaringClass = declaringClass; - - // propagate the strictfp & deprecated modifiers - if (this.declaringClass != null) { - if (this.declaringClass.isStrictfp()) - if (!(isAbstract())) - this.modifiers |= ClassFileConstants.AccStrictfp; - } -} -public MethodBinding(int modifiers, TypeBinding[] parameters, ReferenceBinding declaringClass) { - this(modifiers, TypeConstants.INIT, TypeBinding.UNKNOWN, parameters, declaringClass); -} -// special API used to change method declaring class for runtime visibility check -public MethodBinding(MethodBinding initialMethodBinding, ReferenceBinding declaringClass) { - this.modifiers = initialMethodBinding.modifiers; - this.selector = initialMethodBinding.selector; - this.returnType = initialMethodBinding.returnType; - this.parameters = initialMethodBinding.parameters; - this.declaringClass = declaringClass; -} -/* Answer true if the argument types & the receiver's parameters are equal -*/ -public final boolean areParametersEqual(MethodBinding method) { - TypeBinding[] args = method.parameters; - if (parameters == args) - return true; + public MethodBinding(int modifiers, char[] selector, TypeBinding returnType, TypeBinding[] parameters, ReferenceBinding declaringClass) { + this.modifiers = modifiers; + this.selector = selector; + this.returnType = returnType; + this.setParameters((parameters == null || parameters.length == 0) ? Binding.NO_PARAMETERS : parameters); + this.declaringClass = declaringClass; + + // propagate the strictfp & deprecated modifiers + if (this.declaringClass != null) { + if (this.declaringClass.isStrictfp()) { + if (!(isAbstract())) { + this.modifiers |= ClassFileConstants.AccStrictfp; + } + } + } + } - int length = parameters.length; - if (length != args.length) - return false; + public MethodBinding(int modifiers, TypeBinding[] parameters, ReferenceBinding declaringClass) { + this(modifiers, TypeConstants.INIT, TypeBinding.UNKNOWN, parameters, declaringClass); + } + + /** + * special API used to change method declaring class for runtime visibility check + * + * @param initialMethodBinding + * @param declaringClass + */ + public MethodBinding(MethodBinding initialMethodBinding, ReferenceBinding declaringClass) { + this.modifiers = initialMethodBinding.modifiers; + this.selector = initialMethodBinding.selector; + this.returnType = initialMethodBinding.returnType; + this.parameters = initialMethodBinding.parameters; + this.declaringClass = declaringClass; + this.fOriginal = initialMethodBinding; + } + + /** + * @return Answer true if the argument types & the receiver's parameters are equal + */ + public final boolean areParametersEqual(MethodBinding method) { + TypeBinding[] args = method.parameters; + if (parameters == args) + return true; - for (int i = 0; i < length; i++) - if (parameters[i] != args[i]) + int length = parameters.length; + if (length != args.length) return false; - return true; -} -/* - * Returns true if given parameters are compatible with this method parameters. - * Callers to this method should first check that the number of TypeBindings - * passed as argument matches this FunctionBinding number of parameters - */ - -public final boolean areParametersCompatibleWith(TypeBinding[] arguments) { - int paramLength = this.parameters.length; - int argLength = arguments.length; - int lastIndex = argLength; - if (isVarargs()) { - lastIndex = paramLength - 1; - if (paramLength == argLength) { // accept X[] but not X or X[][] - TypeBinding varArgType = parameters[lastIndex]; // is an ArrayBinding by definition - TypeBinding lastArgument = arguments[lastIndex]; - if (varArgType != lastArgument && !lastArgument.isCompatibleWith(varArgType)) + + for (int i = 0; i < length; i++) + if (parameters[i] != args[i]) return false; - } else if (paramLength < argLength) { // all remainig argument types must be compatible with the elementsType of varArgType - TypeBinding varArgType = ((ArrayBinding) parameters[lastIndex]).elementsType(); - for (int i = lastIndex; i < argLength; i++) - if (varArgType != arguments[i] && !arguments[i].isCompatibleWith(varArgType)) - return false; - } else if (lastIndex != argLength) { // can call foo(int i, X ... x) with foo(1) but NOT foo(); - return false; - } - // now compare standard arguments from 0 to lastIndex + return true; } - for (int i = 0; i < lastIndex; i++) - if (parameters[i] != arguments[i] && !arguments[i].isCompatibleWith(parameters[i])) - return false; - return true; -} - -/* API -* Answer the receiver's binding type from Binding.BindingID. -*/ - -public final int kind() { - return Binding.METHOD; -} -/* Answer true if the receiver is visible to the invocationPackage. -*/ - -public final boolean canBeSeenBy(PackageBinding invocationPackage) { - if (isPublic()) return true; - if (isPrivate()) return false; - - // isProtected() or isDefault() - return invocationPackage == declaringClass.getPackage(); -} -/* Answer true if the receiver is visible to the type provided by the scope. -* InvocationSite implements isSuperAccess() to provide additional information -* if the receiver is protected. -* -* NOTE: This method should ONLY be sent if the receiver is a constructor. -* -* NOTE: Cannot invoke this method with a compilation unit scope. -*/ - -public final boolean canBeSeenBy(InvocationSite invocationSite, Scope scope) { - if (isPublic()) return true; - - SourceTypeBinding invocationType = scope.enclosingSourceType(); - if (invocationType == declaringClass) return true; - - if (isProtected()) { - // answer true if the receiver is in the same package as the invocationType - if (invocationType.fPackage == declaringClass.fPackage) return true; - return invocationSite.isSuperAccess(); - } - - if (isPrivate()) { - // answer true if the invocationType and the declaringClass have a common enclosingType - // already know they are not the identical type - ReferenceBinding outerInvocationType = invocationType; - ReferenceBinding temp = outerInvocationType.enclosingType(); - while (temp != null) { - outerInvocationType = temp; - temp = temp.enclosingType(); - } - ReferenceBinding outerDeclaringClass = declaringClass; - temp = outerDeclaringClass.enclosingType(); - while (temp != null) { - outerDeclaringClass = temp; - temp = temp.enclosingType(); - } - return outerInvocationType == outerDeclaringClass; - } - - // isDefault() - return invocationType.fPackage == declaringClass.fPackage; -} -/* Answer true if the receiver is visible to the type provided by the scope. -* InvocationSite implements isSuperAccess() to provide additional information -* if the receiver is protected. -* -* NOTE: Cannot invoke this method with a compilation unit scope. -*/ -public final boolean canBeSeenBy(TypeBinding receiverType, InvocationSite invocationSite, Scope scope) { - if (isPublic()) return true; - - SourceTypeBinding invocationType = scope.enclosingSourceType(); - if (invocationType == declaringClass && invocationType == receiverType) return true; - - if (invocationType == null) // static import call - return !isPrivate() && scope.getCurrentPackage() == declaringClass.fPackage; - - if (isProtected()) { - // answer true if the invocationType is the declaringClass or they are in the same package - // OR the invocationType is a subclass of the declaringClass - // AND the receiverType is the invocationType or its subclass - // OR the method is a static method accessed directly through a type - // OR previous assertions are true for one of the enclosing type - if (invocationType == declaringClass) return true; - if (invocationType.fPackage == declaringClass.fPackage) return true; - - ReferenceBinding currentType = invocationType; - TypeBinding receiverErasure = receiverType; - ReferenceBinding declaringErasure = declaringClass; - int depth = 0; - do { - if (currentType.findSuperTypeWithSameErasure(declaringErasure) != null) { - if (invocationSite.isSuperAccess()) - return true; - // receiverType can be an array binding in one case... see if you can change it - if (receiverType instanceof ArrayBinding) + /** + * @return true if given parameters are compatible with this method + * parameters. Callers to this method should first check that the + * number of TypeBindings passed as argument matches this + * FunctionBinding number of parameters + */ + public final boolean areParametersCompatibleWith(TypeBinding[] arguments) { + int paramLength = this.parameters.length; + int argLength = arguments.length; + int lastIndex = argLength; + if (isVarargs()) { + lastIndex = paramLength - 1; + // accept X[] but not X or X[][] + if (paramLength == argLength) { + // is an ArrayBinding by definition + TypeBinding varArgType = parameters[lastIndex]; + TypeBinding lastArgument = arguments[lastIndex]; + if (varArgType != lastArgument && !lastArgument.isCompatibleWith(varArgType)) return false; - if (isStatic()) { - if (depth > 0) invocationSite.setDepth(depth); - return true; // see 1FMEPDL - return invocationSite.isTypeAccess(); - } - if (currentType == receiverErasure || receiverErasure.findSuperTypeWithSameErasure(currentType) != null) { - if (depth > 0) invocationSite.setDepth(depth); - return true; - } } - depth++; - currentType = currentType.enclosingType(); - } while (currentType != null); - return false; + // all remainig argument types must be compatible with the elementsType of varArgType + else if (paramLength < argLength) { + TypeBinding varArgType = ((ArrayBinding) parameters[lastIndex]).elementsType(); + for (int i = lastIndex; i < argLength; i++) + if (varArgType != arguments[i] && !arguments[i].isCompatibleWith(varArgType)) + return false; + } + // can call foo(int i, X ... x) with foo(1) but NOT foo(); + else if (lastIndex != argLength) { + return false; + } + // now compare standard arguments from 0 to lastIndex + } + for (int i = 0; i < lastIndex; i++) { + if (parameters[i] != arguments[i] && !arguments[i].isCompatibleWith(parameters[i])) { + return false; + } + } + + return true; } - if (isPrivate()) { - // answer true if the receiverType is the declaringClass - // AND the invocationType and the declaringClass have a common enclosingType - - if (receiverType != declaringClass) { + /** + * API Answer the receiver's binding type from Binding.BindingID. + */ + public final int kind() { + return Binding.METHOD; + } + + /** + * @return true if the receiver is visible to the invocationPackage. + */ + public final boolean canBeSeenBy(PackageBinding invocationPackage) { + if (isPublic()) + return true; + if (isPrivate()) return false; + + // isProtected() or isDefault() + return invocationPackage == declaringClass.getPackage(); + } + + /** + * NOTE: This method should ONLY be sent if the receiver is a constructor. + * + * NOTE: Cannot invoke this method with a compilation unit scope. + * + * @return true if the receiver is visible to the type provided by the + * scope. InvocationSite implements isSuperAccess() to provide + * additional information if the receiver is protected. + */ + public final boolean canBeSeenBy(InvocationSite invocationSite, Scope scope) { + if (isPublic()) + return true; + + SourceTypeBinding invocationType = scope.enclosingSourceType(); + if (invocationType == declaringClass) + return true; + + if (isProtected()) { + // answer true if the receiver is in the same package as the invocationType + if (invocationType.fPackage == declaringClass.fPackage) + return true; + return invocationSite.isSuperAccess(); } - - if (invocationType != declaringClass) { + if (isPrivate()) { + /* answer true if the invocationType and the declaringClass + * have a common enclosingType + * + * already know they are not the identical type */ ReferenceBinding outerInvocationType = invocationType; ReferenceBinding temp = outerInvocationType.enclosingType(); while (temp != null) { @@ -238,391 +196,582 @@ public final boolean canBeSeenBy(TypeBinding receiverType, InvocationSite invoca outerDeclaringClass = temp; temp = temp.enclosingType(); } - if (outerInvocationType != outerDeclaringClass) return false; + return outerInvocationType == outerDeclaringClass; } - return true; + + return invocationType.fPackage == declaringClass.fPackage; } - // isDefault() - PackageBinding declaringPackage = declaringClass.fPackage; - if (invocationType.fPackage != declaringPackage) return false; + /** + * NOTE: Cannot invoke this method with a compilation unit scope. + * + * @return true if the receiver is visible to the type provided by the + * scope. InvocationSite implements isSuperAccess() to provide + * additional information if the receiver is protected. + */ + public final boolean canBeSeenBy(TypeBinding receiverType, InvocationSite invocationSite, Scope scope) { + if (isPublic()) { + return true; + } - // receiverType can be an array binding in one case... see if you can change it - if (receiverType instanceof ArrayBinding) - return false; - ReferenceBinding currentType = (ReferenceBinding) receiverType; - do { - if (declaringClass == currentType) return true; - if(currentType == null) return true; - PackageBinding currentPackage = currentType.fPackage; - // package could be null for wildcards/intersection types, ignore and recurse in superclass - if (currentPackage != null && currentPackage != declaringPackage) return false; - } while ((currentType = currentType.superclass()) != null); - return false; -} -/* - * declaringUniqueKey dot selector genericSignature - * p.X { void bar(X t) } --> Lp/X;.bar(LX;)V - */ -public char[] computeUniqueKey(boolean isLeaf) { - // declaring class - char[] declaringKey = this.declaringClass.computeUniqueKey(false/*not a leaf*/); - int declaringLength = declaringKey.length; - - // selector - int selectorLength = - (this.selector == TypeConstants.INIT || this.selector==null) ? 0 : this.selector.length; - - // generic signature - char[] sig = signature(); - int signatureLength = sig.length; - - char[] uniqueKey = new char[declaringLength + 1 + selectorLength + signatureLength]; - int index = 0; - System.arraycopy(declaringKey, 0, uniqueKey, index, declaringLength); - index = declaringLength; - uniqueKey[index++] = '.'; - if (this.selector!=null) - System.arraycopy(this.selector, 0, uniqueKey, index, selectorLength); - index += selectorLength; - System.arraycopy(sig, 0, uniqueKey, index, signatureLength); - - return uniqueKey; -} -/* - * Answer the declaring class to use in the constant pool - * may not be a reference binding (see subtypes) - */ -public TypeBinding constantPoolDeclaringClass() { - return this.declaringClass; -} -/* Answer the receiver's constant pool name. -* -* for constructors -* for clinit methods -* or the source name of the method -*/ -public final char[] constantPoolName() { - return selector; -} -///** -// * @param index the index of the parameter of interest -// * @return the annotations on the indexth parameter -// * @throws ArrayIndexOutOfBoundsException when index is not valid -// */ -//public AnnotationBinding[] getParameterAnnotations(int index) { -// MethodBinding originalMethod = this.original(); -// AnnotationHolder holder = originalMethod.declaringClass.retrieveAnnotationHolder(originalMethod, true); -// return holder == null ? Binding.NO_ANNOTATIONS : holder.getParameterAnnotations(index); -//} -public final int getAccessFlags() { - return modifiers & ExtraCompilerModifiers.AccJustFlag; -} - -/** - * @return the default value for this annotation method or null if there is no default value - */ -public Object getDefaultValue() { - MethodBinding originalMethod = this.original(); - if ((originalMethod.tagBits & TagBits.DefaultValueResolved) == 0) { - originalMethod.tagBits |= TagBits.DefaultValueResolved; + SourceTypeBinding invocationType = scope.enclosingSourceType(); + if (invocationType == declaringClass && invocationType == receiverType) { + return true; + } + + // static import call + if (invocationType == null) { + return !isPrivate() && scope.getCurrentPackage() == declaringClass.fPackage; + } + + if (isProtected()) { + /* answer true if the invocationType is the declaringClass or they are in the same package + * OR the invocationType is a subclass of the declaringClass + * AND the receiverType is the invocationType or its subclass + * OR the method is a static method accessed directly through a type + * OR previous assertions are true for one of the enclosing type */ + if (invocationType == declaringClass) { + return true; + } + + if (invocationType.fPackage == declaringClass.fPackage) { + return true; + } + + ReferenceBinding currentType = invocationType; + TypeBinding receiverErasure = receiverType; + ReferenceBinding declaringErasure = declaringClass; + int depth = 0; + do { + if (currentType.findSuperTypeWithSameErasure(declaringErasure) != null) { + if (invocationSite.isSuperAccess()) + return true; + // receiverType can be an array binding in one case... see if you can change it + if (receiverType instanceof ArrayBinding) { + return false; + } + + if (isStatic()) { + if (depth > 0) { + invocationSite.setDepth(depth); + } + + return true; + } + if (currentType == receiverErasure || receiverErasure.findSuperTypeWithSameErasure(currentType) != null) { + if (depth > 0) { + invocationSite.setDepth(depth); + } + + return true; + } + } + depth++; + currentType = currentType.enclosingType(); + } while (currentType != null); + + return false; + } + + if (isPrivate()) { + /* answer true if the receiverType is the declaringClass + * AND the invocationType and the declaringClass have a common enclosingType */ + if (receiverType != declaringClass) { + return false; + } + + if (invocationType != declaringClass) { + ReferenceBinding outerInvocationType = invocationType; + ReferenceBinding temp = outerInvocationType.enclosingType(); + while (temp != null) { + outerInvocationType = temp; + temp = temp.enclosingType(); + } + + ReferenceBinding outerDeclaringClass = declaringClass; + temp = outerDeclaringClass.enclosingType(); + while (temp != null) { + outerDeclaringClass = temp; + temp = temp.enclosingType(); + } + + if (outerInvocationType != outerDeclaringClass) { + return false; + } + } + return true; + } + + PackageBinding declaringPackage = null; + if(declaringClass != null) { + declaringPackage = declaringClass.fPackage; + if (invocationType.fPackage != declaringPackage) { + return false; + } } - return null; -} - -/* Answer true if the receiver is an abstract method -*/ -public final boolean isAbstract() { - return (modifiers & ClassFileConstants.AccAbstract) != 0; -} - -/* Answer true if the receiver is a bridge method -*/ -public final boolean isBridge() { - return (modifiers & ClassFileConstants.AccBridge) != 0; -} - -/* Answer true if the receiver is a constructor -*/ -public final boolean isConstructor() { - return (selector == TypeConstants.INIT || (this.tagBits&TagBits.IsConstructor)!=0); -} - -/* Answer true if the receiver has default visibility -*/ -public final boolean isDefault() { - return !isPublic() && !isProtected() && !isPrivate(); -} - -/* Answer true if the receiver is a system generated default abstract method -*/ -public final boolean isDefaultAbstract() { - return (modifiers & ExtraCompilerModifiers.AccDefaultAbstract) != 0; -} - -/* Answer true if the receiver is a deprecated method -*/ -public final boolean isDeprecated() { - return (modifiers & ClassFileConstants.AccDeprecated) != 0; -} - -/* Answer true if the receiver is final and cannot be overridden -*/ -public final boolean isFinal() { - return (modifiers & ClassFileConstants.AccFinal) != 0; -} - -/* Answer true if the receiver is implementing another method - * in other words, it is overriding and concrete, and overriden method is abstract - * Only set for source methods -*/ -public final boolean isImplementing() { - return (modifiers & ExtraCompilerModifiers.AccImplementing) != 0; -} - -/* Answer true if the receiver is overriding another method - * Only set for source methods -*/ -public final boolean isOverriding() { - return (modifiers & ExtraCompilerModifiers.AccOverriding) != 0; -} -/* Answer true if the receiver has private visibility -*/ -public final boolean isPrivate() { - return (modifiers & ClassFileConstants.AccPrivate) != 0; -} - -/* Answer true if the receiver has private visibility and is used locally -*/ -public final boolean isUsed() { - return (modifiers & ExtraCompilerModifiers.AccLocallyUsed) != 0; -} - -/* Answer true if the receiver has protected visibility -*/ -public final boolean isProtected() { - return (modifiers & ClassFileConstants.AccProtected) != 0; -} - -/* Answer true if the receiver has public visibility -*/ -public final boolean isPublic() { - return (modifiers & ClassFileConstants.AccPublic) != 0; -} - -/* Answer true if the receiver is a static method -*/ -public final boolean isStatic() { - return (modifiers & ClassFileConstants.AccStatic) != 0; -} - -/* Answer true if all float operations must adher to IEEE 754 float/double rules -*/ -public final boolean isStrictfp() { - return (modifiers & ClassFileConstants.AccStrictfp) != 0; -} - -/* Answer true if the receiver method has varargs -*/ -public final boolean isVarargs() { - return (modifiers & ClassFileConstants.AccVarargs) != 0; -} - -/* Answer true if the receiver's declaring type is deprecated (or any of its enclosing types) -*/ -public final boolean isViewedAsDeprecated() { - return (modifiers & (ClassFileConstants.AccDeprecated | ExtraCompilerModifiers.AccDeprecatedImplicitly)) != 0; -} - -/** - * Returns the original method (as opposed to parameterized instances) - */ -public MethodBinding original() { - return this; -} - -public char[] readableName() /* foo(int, Thread) */ { - StringBuffer buffer = new StringBuffer(parameters.length + 1 * 20); - if (isConstructor()) - buffer.append(declaringClass.sourceName()); - else - buffer.append(selector); - buffer.append('('); - if (parameters != Binding.NO_PARAMETERS) { - for (int i = 0, length = parameters.length; i < length; i++) { - if (i > 0) - buffer.append(", "); //$NON-NLS-1$ - buffer.append(parameters[i].sourceName()); + + // receiverType can be an array binding in one case... see if you can change it + if (receiverType instanceof ArrayBinding) { + return false; } + + ReferenceBinding currentType = (ReferenceBinding) receiverType; + do { + if (declaringClass == currentType) { + return true; + } + + if (currentType == null) { + return true; + } + + PackageBinding currentPackage = currentType.fPackage; + // package could be null for wildcards/intersection types, ignore and recurse in superclass + if (currentPackage != null && currentPackage != declaringPackage) { + return false; + } + } while ((currentType = currentType.getSuperBinding()) != null); + + return false; } - buffer.append(')'); - return buffer.toString().toCharArray(); -} -public void setDefaultValue(Object defaultValue) { - MethodBinding originalMethod = this.original(); - originalMethod.tagBits |= TagBits.DefaultValueResolved; -} -/** - * @see org.eclipse.wst.jsdt.internal.compiler.lookup.Binding#shortReadableName() - */ -public char[] shortReadableName() { - StringBuffer buffer = new StringBuffer(parameters.length + 1 * 20); - if (isConstructor()) - buffer.append(declaringClass.shortReadableName()); - else - buffer.append(selector); - buffer.append('('); - if (parameters != Binding.NO_PARAMETERS) { - for (int i = 0, length = parameters.length; i < length; i++) { - if (i > 0) - buffer.append(", "); //$NON-NLS-1$ - buffer.append(parameters[i].shortReadableName()); + + /** + * declaringUniqueKey dot selector genericSignature p.X { void bar(X t) + * } --> Lp/X;.bar(LX;)V + */ + public char[] computeUniqueKey(boolean isLeaf) { + // declaring class + char[] declaringKey = this.declaringClass.computeUniqueKey(false); + int declaringLength = declaringKey.length; + + // selector + int selectorLength = (this.selector == TypeConstants.INIT || this.selector == null) ? 0 : this.selector.length; + + // generic signature + char[] sig = signature(); + int signatureLength = sig.length; + + char[] uniqueKey = new char[declaringLength + 1 + selectorLength + signatureLength]; + int index = 0; + System.arraycopy(declaringKey, 0, uniqueKey, index, declaringLength); + index = declaringLength; + uniqueKey[index++] = '.'; + if (this.selector != null) { + System.arraycopy(this.selector, 0, uniqueKey, index, selectorLength); } + + index += selectorLength; + System.arraycopy(sig, 0, uniqueKey, index, signatureLength); + + return uniqueKey; } - buffer.append(')'); - int nameLength = buffer.length(); - char[] shortReadableName = new char[nameLength]; - buffer.getChars(0, nameLength, shortReadableName, 0); - return shortReadableName; -} - -protected final void setSelector(char[] selector) { - this.selector = selector; - this.signature = null; -} - -/* Answer the receiver's signature. -* -* NOTE: This method should only be used during/after code gen. -* The signature is cached so if the signature of the return type or any parameter -* type changes, the cached state is invalid. -*/ -public final char[] signature() /* (ILjava/lang/Thread;)Ljava/lang/Object; */ { - if (signature != null) - return signature; - StringBuffer buffer = new StringBuffer(parameters.length + 1 * 20); - buffer.append('('); + /** + * @return the declaring class to use in the constant pool may not be a + * reference binding (see subtypes) + */ + public TypeBinding constantPoolDeclaringClass() { + return this.declaringClass; + } - TypeBinding[] targetParameters = this.parameters; - boolean isConstructor = isConstructor(); -// if (isConstructor && declaringClass.isEnum()) { // insert String name,int ordinal -// buffer.append(ConstantPool.JavaLangStringSignature); -// buffer.append(TypeBinding.INT.signature()); -// } - boolean needSynthetics = isConstructor && declaringClass.isNestedType(); + /** + * for constructors for clinit methods or the source name + * of the method + * + * @return the receiver's constant pool name. + */ + public final char[] constantPoolName() { + return selector; + } - if (targetParameters != Binding.NO_PARAMETERS) { - for (int i = 0; i < targetParameters.length; i++) { - buffer.append(targetParameters[i].signature()); - } + public final int getAccessFlags() { + return modifiers & ExtraCompilerModifiers.AccJustFlag; } - if (needSynthetics) { - // move the extra padding arguments of the synthetic constructor invocation to the end - for (int i = targetParameters.length, extraLength = parameters.length; i < extraLength; i++) { - buffer.append(parameters[i].signature()); + + /** + * @return the default value for this annotation method or + * null if there is no default value + */ + public Object getDefaultValue() { + MethodBinding originalMethod = this.original(); + if ((originalMethod.tagBits & TagBits.DefaultValueResolved) == 0) { + originalMethod.tagBits |= TagBits.DefaultValueResolved; } - } - buffer.append(')'); - if (this.returnType != null) - buffer.append(this.returnType.signature()); - int nameLength = buffer.length(); - signature = new char[nameLength]; - buffer.getChars(0, nameLength, signature, 0); - - return signature; -} -public final int sourceEnd() { - AbstractMethodDeclaration method = sourceMethod(); - if (method == null) { - if (this.declaringClass instanceof SourceTypeBinding) - return ((SourceTypeBinding) this.declaringClass).sourceEnd(); - return 0; - } - return method.sourceEnd; -} -public AbstractMethodDeclaration sourceMethod() { - SourceTypeBinding sourceType; - try { - sourceType = (SourceTypeBinding) declaringClass; - } catch (ClassCastException e) { return null; } - if (sourceType!=null) - return sourceType.sourceMethod(this); - return null; -} -public final int sourceStart() { - AbstractMethodDeclaration method = sourceMethod(); - if (method == null) { - if (this.declaringClass instanceof SourceTypeBinding) - return ((SourceTypeBinding) this.declaringClass).sourceStart(); - return 0; + /** + * @return true if the receiver is an abstract method + */ + public final boolean isAbstract() { + return (modifiers & ClassFileConstants.AccAbstract) != 0; } - return method.sourceStart; -} -public String toString() { - String s = (returnType != null) ? returnType.debugName() : "NULL TYPE"; //$NON-NLS-1$ - s += " "; //$NON-NLS-1$ - s += (selector != null) ? new String(selector) : "UNNAMED METHOD"; //$NON-NLS-1$ + /** + * @return true if the receiver is a bridge method + */ + public final boolean isBridge() { + return (modifiers & ClassFileConstants.AccBridge) != 0; + } - s += "("; //$NON-NLS-1$ - if (parameters != null) { + /** + * @return true if the receiver is a constructor + */ + public final boolean isConstructor() { + return (selector == TypeConstants.INIT || (this.tagBits & TagBits.IsConstructor) != 0); + } + + /** + * @return true if the receiver has default visibility + */ + public final boolean isDefault() { + return !isPublic() && !isProtected() && !isPrivate(); + } + + /** + * @return true if the receiver is a system generated default abstract method + */ + public final boolean isDefaultAbstract() { + return (modifiers & ExtraCompilerModifiers.AccDefaultAbstract) != 0; + } + + /** + * @return true if the receiver is a deprecated method + */ + public final boolean isDeprecated() { + return (modifiers & ClassFileConstants.AccDeprecated) != 0; + } + + /** + * @return true if the receiver is final and cannot be overridden + */ + public final boolean isFinal() { + return (modifiers & ClassFileConstants.AccFinal) != 0; + } + + /** + * @return true if the receiver is implementing another method in other + * words, it is overriding and concrete, and overriden method is + * abstract Only set for source methods + */ + public final boolean isImplementing() { + return (modifiers & ExtraCompilerModifiers.AccImplementing) != 0; + } + + /** + * @return true if the receiver is overriding another method Only set for + * source methods + */ + public final boolean isOverriding() { + return (modifiers & ExtraCompilerModifiers.AccOverriding) != 0; + } + + /** + * @return true if the receiver has private visibility + */ + public final boolean isPrivate() { + return (modifiers & ClassFileConstants.AccPrivate) != 0; + } + + /** + * @return true if the receiver has private visibility and is used locally + */ + public final boolean isUsed() { + return (modifiers & ExtraCompilerModifiers.AccLocallyUsed) != 0; + } + + /** + * @return true if the receiver has protected visibility + */ + public final boolean isProtected() { + return (modifiers & ClassFileConstants.AccProtected) != 0; + } + + /** + * @return true if the receiver has public visibility + */ + public final boolean isPublic() { + return (modifiers & ClassFileConstants.AccPublic) != 0; + } + + /** + * @return true if the receiver is a static method + */ + public final boolean isStatic() { + return (modifiers & ClassFileConstants.AccStatic) != 0; + } + + /** + * @return true if all float operations must adher to IEEE 754 + * float/double rules + */ + public final boolean isStrictfp() { + return (modifiers & ClassFileConstants.AccStrictfp) != 0; + } + + /** + * @return true if the receiver method has varargs + */ + public final boolean isVarargs() { + return (modifiers & ClassFileConstants.AccVarargs) != 0; + } + + /** + * @return true if the receiver's declaring type is deprecated (or any of + * its enclosing types) + */ + public final boolean isViewedAsDeprecated() { + return (modifiers & (ClassFileConstants.AccDeprecated | ExtraCompilerModifiers.AccDeprecatedImplicitly)) != 0; + } + + /** + * @return {@link MethodBinding} this {@link MethodBinding} was created + * with or this if this {@link MethodBinding} was + * created from scratch. + */ + public MethodBinding original() { + return this.fOriginal != null ? this.fOriginal : this; + } + + /** + * foo(int, Thread) + * + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.Binding#readableName() + */ + public char[] readableName() { + StringBuffer buffer = new StringBuffer(parameters.length + 1 * 20); + if (isConstructor()) + buffer.append(declaringClass.sourceName()); + else + buffer.append(selector); + buffer.append('('); + if (parameters != Binding.NO_PARAMETERS) { + for (int i = 0, length = parameters.length; i < length; i++) { + if (i > 0) + buffer.append(", "); //$NON-NLS-1$ + buffer.append(parameters[i].sourceName()); + } + } + buffer.append(')'); + return buffer.toString().toCharArray(); + } + + public void setDefaultValue(Object defaultValue) { + MethodBinding originalMethod = this.original(); + originalMethod.tagBits |= TagBits.DefaultValueResolved; + } + + /** + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.Binding#shortReadableName() + */ + public char[] shortReadableName() { + StringBuffer buffer = new StringBuffer(parameters.length + 1 * 20); + if (isConstructor()) + buffer.append(declaringClass.shortReadableName()); + else + buffer.append(selector); + buffer.append('('); if (parameters != Binding.NO_PARAMETERS) { for (int i = 0, length = parameters.length; i < length; i++) { - if (i > 0) - s += ", "; //$NON-NLS-1$ - s += (parameters[i] != null) ? parameters[i].debugName() : "NULL TYPE"; //$NON-NLS-1$ + if (i > 0) + buffer.append(", "); //$NON-NLS-1$ + buffer.append(parameters[i].shortReadableName()); } } - } else { - s += "NULL PARAMETERS"; //$NON-NLS-1$ - } - s += ") "; //$NON-NLS-1$ - - return s; -} -/** - * Returns the method to use during tiebreak (usually the method itself). - * For generic method invocations, tiebreak needs to use generic method with erasure substitutes. - */ -public MethodBinding tiebreakMethod() { - return this; -} - -public void createFunctionTypeBinding(Scope scope) -{ - functionTypeBinding=new FunctionTypeBinding(this,scope); -} - -public MethodBinding createNamedMethodBinding(char [] name) -{ - MethodBinding newBinding=new MethodBinding(this.modifiers,name, this.returnType, this.parameters, this.declaringClass); - newBinding.functionTypeBinding=this.functionTypeBinding; - newBinding.tagBits=this.tagBits; - newBinding.signature=this.signature; - return newBinding; -} -public void updateFrom(MethodBinding functionBinding) { - this.returnType=functionBinding.returnType; - this.parameters=functionBinding.parameters; -} -public void cleanup() { - if (this.functionTypeBinding!=null) - this.functionTypeBinding.cleanup(); + buffer.append(')'); + int nameLength = buffer.length(); + char[] shortReadableName = new char[nameLength]; + buffer.getChars(0, nameLength, shortReadableName, 0); + return shortReadableName; + } + + protected final void setSelector(char[] selector) { + this.selector = selector; + this.signature = null; + } + + /** + * NOTE: This method should only be used during/after code gen. The + * signature is cached so if the signature of the return type or any + * parameter type changes, the cached state is invalid. + * + * (ILjava/lang/Thread;)Ljava/lang/Object; + * + * @return the receiver's signature. + */ + public final char[] signature() { + if (signature != null) + return signature; + + StringBuffer buffer = new StringBuffer(parameters.length + 1 * 20); + buffer.append('('); + + TypeBinding[] targetParameters = this.parameters; + boolean isConstructor = isConstructor(); + + boolean needSynthetics = isConstructor && declaringClass.isNestedType(); + + if (targetParameters != Binding.NO_PARAMETERS) { + for (int i = 0; i < targetParameters.length; i++) { + buffer.append(targetParameters[i].signature()); + } + } + if (needSynthetics) { + // move the extra padding arguments of the synthetic constructor invocation to the end + for (int i = targetParameters.length, extraLength = parameters.length; i < extraLength; i++) { + buffer.append(parameters[i].signature()); + } + } + buffer.append(')'); + if (this.returnType != null) { + buffer.append(this.returnType.signature()); + } + + int nameLength = buffer.length(); + signature = new char[nameLength]; + buffer.getChars(0, nameLength, signature, 0); + + return signature; + } + + public final int sourceEnd() { + AbstractMethodDeclaration method = sourceMethod(); + if (method == null) { + if (this.declaringClass instanceof SourceTypeBinding) { + return ((SourceTypeBinding) this.declaringClass).sourceEnd(); + } + + return 0; + } + return method.sourceEnd; + } + + public AbstractMethodDeclaration sourceMethod() { + SourceTypeBinding sourceType; + try { + sourceType = (SourceTypeBinding) this.original().declaringClass; + } catch (ClassCastException e) { + return null; + } + + if (sourceType!=null) { + return sourceType.sourceMethod(this.original()); + } + + return null; + } + + public final int sourceStart() { + AbstractMethodDeclaration method = sourceMethod(); + if (method == null) { + if (this.declaringClass instanceof SourceTypeBinding) { + return ((SourceTypeBinding) this.declaringClass).sourceStart(); + } + + return 0; + } + + return method.sourceStart; + } + + public String toString() { + String s = (returnType != null) ? returnType.debugName() : "NULL TYPE"; //$NON-NLS-1$ + s += " "; //$NON-NLS-1$ + s += (selector != null) ? new String(selector) : "UNNAMED METHOD"; //$NON-NLS-1$ + + s += "("; //$NON-NLS-1$ + if (parameters != null) { + if (parameters != Binding.NO_PARAMETERS) { + for (int i = 0, length = parameters.length; i < length; i++) { + if (i > 0) { + s += ", "; //$NON-NLS-1$ + } + + s += (parameters[i] != null) ? parameters[i].debugName() : "NULL TYPE"; //$NON-NLS-1$ + } + } + } + else { + s += "NULL PARAMETERS"; //$NON-NLS-1$ + } + s += ") "; //$NON-NLS-1$ + + return s; + } + + /** + * @return the method to use during tiebreak (usually the method itself). + * For generic method invocations, tiebreak needs to use generic method + * with erasure substitutes. + */ + public MethodBinding tiebreakMethod() { + return this; + } + + public void createFunctionTypeBinding(Scope scope) { + functionTypeBinding = new FunctionTypeBinding(this, scope); + } + + public MethodBinding createNamedMethodBinding(char[] name) { + MethodBinding newBinding = new MethodBinding(this.modifiers, name, this.returnType, this.parameters, this.declaringClass); + newBinding.functionTypeBinding = this.functionTypeBinding; + newBinding.tagBits = this.tagBits; + newBinding.signature = this.signature; + return newBinding; + } + + public void updateFrom(MethodBinding functionBinding) { + this.returnType = functionBinding.returnType; + this.parameters = functionBinding.parameters; + } + + public void cleanup() { + if (this.functionTypeBinding != null) { + this.functionTypeBinding.cleanup(); + } + } + + /** + *

+ * Sets the parameters on this binding as well as the original binding if + * this binding was created from some other binding. + *

+ * + * @param params + * {@link TypeBinding}s to set as the parameters of this + * binding + */ + protected void setParameters(TypeBinding[] params) { + this.parameters = params; + + if(this.fOriginal != null) { + this.fOriginal.parameters = params; + } + } -} - -void ensureBindingsAreComplete() -{ - if (this.declaringClass instanceof SourceTypeBinding) { - SourceTypeBinding parentBinding = (SourceTypeBinding) this.declaringClass; - if ((parentBinding.tagBits & TagBits.AreMethodsComplete) == 0) { - parentBinding.methods(); //finish resolving method bindings + /** + * @return the parameters sfor this binding, or if not set and this + * binding has an original binding then the parameters from the + * original binding, else {@link Binding#NO_PARAMETERS} + */ + public TypeBinding[] getParameters() { + TypeBinding[] params = Binding.NO_PARAMETERS; + + if(this.parameters != null && this.parameters.length > 0) { + params = this.parameters; + } else if(this.fOriginal.parameters != null && this.fOriginal.parameters.length > 0) { + params = this.fOriginal.parameters; + } + + return params; + } + + void ensureBindingsAreComplete() { + if (this.declaringClass instanceof SourceTypeBinding) { + SourceTypeBinding parentBinding = (SourceTypeBinding) this.declaringClass; + if ((parentBinding.tagBits & TagBits.AreMethodsComplete) == 0) { + parentBinding.methods(); // finish resolving method bindings + } } } -} - -} +} \ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MethodScope.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MethodScope.java index 57874e80..3a5930ba 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MethodScope.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MethodScope.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -10,20 +10,24 @@ *******************************************************************************/ package org.eclipse.wst.jsdt.internal.compiler.lookup; +import org.eclipse.wst.jsdt.core.ast.IAbstractVariableDeclaration; import org.eclipse.wst.jsdt.core.compiler.CharOperation; import org.eclipse.wst.jsdt.core.infer.InferredMethod; import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode; import org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.wst.jsdt.internal.compiler.ast.Argument; import org.eclipse.wst.jsdt.internal.compiler.ast.ConstructorDeclaration; +import org.eclipse.wst.jsdt.internal.compiler.ast.ProgramElement; import org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedNameReference; import org.eclipse.wst.jsdt.internal.compiler.ast.SingleNameReference; +import org.eclipse.wst.jsdt.internal.compiler.ast.Statement; import org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants; import org.eclipse.wst.jsdt.internal.compiler.flow.FlowInfo; import org.eclipse.wst.jsdt.internal.compiler.flow.UnconditionalFlowInfo; import org.eclipse.wst.jsdt.internal.compiler.impl.ReferenceContext; import org.eclipse.wst.jsdt.internal.compiler.problem.ProblemReporter; +import org.eclipse.wst.jsdt.internal.compiler.util.HashtableOfObject; /** * Particular block scope used for methods, constructors or clinits, representing @@ -43,7 +47,6 @@ public class MethodScope extends BlockScope { // flow analysis public int analysisIndex; // for setting flow-analysis id - public boolean isPropagatingInnerClassEmulation; // for local variables table attributes public int lastIndex = 0; @@ -53,8 +56,23 @@ public class MethodScope extends BlockScope { public static final char [] ARGUMENTS_NAME={'a','r','g','u','m','e','n','t','s'}; - public LocalVariableBinding argumentsBinding ; + public LocalVariableBinding argumentsBinding; + /** + *

+ * Map of variable names to statements that have not been resolved that + * define those variables. + *

+ */ + private HashtableOfObject fUnresolvedLocalVars; + + /** + *

+ * Map of function names to statements that have not been resolved that + * define those variables. + *

+ */ + private HashtableOfObject fUnresolvedLocalFuncs; public MethodScope(Scope parent, ReferenceContext context, boolean isStatic) { @@ -174,17 +192,25 @@ public class MethodScope extends BlockScope { MethodBinding methodBinding=null; // is necessary to ensure error reporting this.referenceContext = method; - method.scope = this; + method.setScope(this); int modifiers = method.modifiers | ExtraCompilerModifiers.AccUnresolved; if ((method.modifiers &(ClassFileConstants.AccPrivate | ClassFileConstants.AccProtected))==0) modifiers|=ClassFileConstants.AccPublic; if (method.inferredMethod!=null && method.inferredMethod.isStatic) modifiers|= ClassFileConstants.AccStatic; - if (method.isConstructor() || isConstructor) { + if (isConstructor) { if (method.isDefaultConstructor() || isConstructor) { modifiers |= ExtraCompilerModifiers.AccIsDefaultConstructor; } - methodBinding = new MethodBinding(modifiers, name, TypeBinding.UNKNOWN, null, declaringClass); + TypeBinding constructorType = null; + if (method.inferredMethod!=null && method.inferredMethod.inType != null) { + constructorType=method.inferredMethod.inType.resolveType(this,method); + } + //return type still null, return type is unknown + if (constructorType==null) { + constructorType=TypeBinding.UNKNOWN; + } + methodBinding = new MethodBinding(modifiers, name, constructorType, null, constructorType instanceof ReferenceBinding ? (ReferenceBinding) constructorType : declaringClass); methodBinding.tagBits|=TagBits.IsConstructor; checkAndSetModifiersForConstructor(methodBinding); } else { @@ -200,7 +226,7 @@ public class MethodScope extends BlockScope { returnType=TypeBinding.UNKNOWN; } - if (isLocal && method.selector!=null) { + if (isLocal && method.getName()!=null) { methodBinding = new LocalFunctionBinding(modifiers, name,returnType, null, declaringClass); } else{// not local method @@ -215,12 +241,13 @@ public class MethodScope extends BlockScope { } } - methodBinding.createFunctionTypeBinding(this); - if (method.inferredMethod!=null && method.inferredMethod.isConstructor) { - methodBinding.tagBits|=TagBits.IsConstructor; - } + //methodBinding.createFunctionTypeBinding(this); +// if (method.inferredMethod!=null && method.inferredMethod.isConstructor) { +// methodBinding.tagBits|=TagBits.IsConstructor; +// } checkAndSetModifiersForMethod(methodBinding); } + methodBinding.createFunctionTypeBinding(this); this.isStatic =methodBinding.isStatic(); //set arguments @@ -399,12 +426,161 @@ public class MethodScope extends BlockScope { return s; } + /** + *

+ * This implementation first calls super, if that returns no binding or a + * problem binding then the list of unresolved local variables is checked, + * and if there is a statement that defines a variable with the correct + * name it is resolved, and then the super implementation is called again. + *

+ * + *

+ * This allows {@link #addUnresolvedLocalVar(char[], Statement)} to be used in + * conjunction with this method to prevent having to resolve the entire + * {@link AbstractMethodDeclaration} associated with this scope. + *

+ * + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope#findVariable(char[]) + */ public LocalVariableBinding findVariable(char[] variableName) { LocalVariableBinding binding = super.findVariable(variableName); - if (binding==null && CharOperation.equals(variableName,ARGUMENTS_NAME)) - binding=this.argumentsBinding; + if (binding == null && CharOperation.equals(variableName,ARGUMENTS_NAME)) { + binding = this.argumentsBinding; + } + + // if super could not find a good binding then check list of unresolved local variables + if(binding == null && this.fUnresolvedLocalVars != null) { + IAbstractVariableDeclaration statement = (IAbstractVariableDeclaration)this.fUnresolvedLocalVars.removeKey(variableName); + if(statement != null && statement instanceof ProgramElement) { + //resolve and then call super again + ((ProgramElement)statement).resolve(this); + binding = super.findVariable(variableName); + } + } + return binding; } - - -} + + /** + *

+ * This implementation first calls super, if that returns no binding or a + * problem binding then the list of unresolved local functions is checked, + * and if there is a statement that defines a function with the correct + * name it is resolved, and then its binding is returned. + *

+ * + *

+ * This allows {@link #addUnresolvedLocalFunc(char[], AbstractMethodDeclaration)} to be used in + * conjunction with this method to prevent having to resolve the entire + * {@link AbstractMethodDeclaration} associated with this scope. + *

+ * + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.Scope#findMethod(org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding, char[], org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding[], org.eclipse.wst.jsdt.internal.compiler.lookup.InvocationSite) + */ + public MethodBinding findMethod(ReferenceBinding receiverType, char[] selector, TypeBinding[] argumentTypes, InvocationSite invocationSite) { + MethodBinding binding = super.findMethod(receiverType, selector, argumentTypes, invocationSite); + + // if super could not find a good binding then check list of unresolved local functions + if((binding == null || !binding.isValidBinding()) && this.fUnresolvedLocalFuncs != null) { + AbstractMethodDeclaration statement = (AbstractMethodDeclaration)this.fUnresolvedLocalFuncs.removeKey(selector); + if(statement != null) { + //resolve and then return the statements binding + statement.resolve(this); + binding = statement.getBinding(); + } + } + + return binding; + } + + /** + *

+ * This implementation first calls super, if that returns no binding or a + * problem binding then the list of unresolved local functions is checked, + * and if there is a statement that defines a function with the correct + * name it is resolved, and then its binding is returned. + *

+ * + *

+ * This allows {@link #addUnresolvedLocalFunc(char[], AbstractMethodDeclaration)} to be used in + * conjunction with this method to prevent having to resolve the entire + * {@link AbstractMethodDeclaration} associated with this scope. + *

+ * + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.Scope#findMethod(org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding, char[], org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding[], org.eclipse.wst.jsdt.internal.compiler.lookup.InvocationSite) + */ + public MethodBinding findMethod(char[] methodName, TypeBinding[]argumentTypes, boolean checkVars) { + MethodBinding binding = super.findMethod(methodName, argumentTypes, checkVars); + + // if super could not find a good binding then check list of unresolved local functions + if((binding == null || !binding.isValidBinding()) && this.fUnresolvedLocalFuncs != null) { + AbstractMethodDeclaration methDecl = (AbstractMethodDeclaration)this.fUnresolvedLocalFuncs.removeKey(methodName); + if(methDecl != null) { + //resolve and then return the statements binding + binding = methDecl.getBinding(); + if(binding == null || !binding.isValidBinding()) { + + /* if it is anonymous, but has a name (has to to be here) then this is a + * function assignment to a variable not declared in this scope so + * build with compilation unit scope. + * + * else build with this scope */ + Scope scope = null; + if(methDecl.isAnonymous()) { + scope = this.compilationUnitScope(); + } else { + scope = this; + } + methDecl.resolve(scope); + } + binding = methDecl.getBinding(); + } + } + + return binding; + } + + /** + *

+ * Adds an unresolved local variable defined in this scope to be resolved + * on an as needed basses. + *

+ * + * @param name + * the name of the unresolved local variable + * @param expr + * {@link IAbstractVariableDeclaration} that defines the unresolved local variable + * that will be used to resolve it if needed + */ + public void addUnresolvedLocalVar(char[] name, IAbstractVariableDeclaration expr) { + if(name != null && name.length > 0 && expr != null) { + if(this.fUnresolvedLocalVars == null) { + this.fUnresolvedLocalVars = new HashtableOfObject(); + } + + this.fUnresolvedLocalVars.put(name, expr); + } + } + + /** + *

+ * Adds an unresolved local function defined in this scope to be resolved + * on an as needed basses. + *

+ * + * @param name + * the name of the unresolved local function + * @param expr + * {@link AbstractMethodDeclaration} that defines the unresolved local function + * that will be used to resolve it if needed + */ + public void addUnresolvedLocalFunc(char[] name, AbstractMethodDeclaration func) { + if(name != null && name.length > 0 && func != null) { + if(this.fUnresolvedLocalFuncs == null) { + this.fUnresolvedLocalFuncs = new HashtableOfObject(); + } + + this.fUnresolvedLocalFuncs.put(name, func); + } + } +} \ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MethodVerifier.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MethodVerifier.java index 7590611c..6725700a 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MethodVerifier.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MethodVerifier.java @@ -274,15 +274,15 @@ void checkPackagePrivateAbstractMethod(MethodBinding abstractMethod) { PackageBinding necessaryPackage = abstractMethod.declaringClass.fPackage; if (necessaryPackage == this.type.fPackage) return; // not a problem - ReferenceBinding superType = this.type.superclass(); + ReferenceBinding superType = this.type.getSuperBinding(); do { if (!superType.isValidBinding()) return; return; // closer non abstract super type will be flagged instead - } while ((superType = superType.superclass()) != abstractMethod.declaringClass); + } while ((superType = superType.getSuperBinding()) != abstractMethod.declaringClass); } void computeInheritedMethods() { - ReferenceBinding superclass = this.type.superclass(); // class or enum + ReferenceBinding superclass = this.type.getSuperBinding(); // class or enum computeInheritedMethods(superclass, null); } /* @@ -365,7 +365,7 @@ void computeInheritedMethods(ReferenceBinding superclass, ReferenceBinding[] sup } } } - superType = superType.superclass(); + superType = superType.getSuperBinding(); } if (nextPosition == 0) return; @@ -455,7 +455,7 @@ boolean isAsVisible(MethodBinding newMethod, MethodBinding inheritedMethod) { boolean isSameClassOrSubclassOf(ReferenceBinding testClass, ReferenceBinding superclass) { do { if (testClass == superclass) return true; - } while ((testClass = testClass.superclass()) != null); + } while ((testClass = testClass.getSuperBinding()) != null); return false; } ProblemReporter problemReporter() { diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MissingBinaryTypeBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MissingBinaryTypeBinding.java index 7d9c7c94..115aa429 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MissingBinaryTypeBinding.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MissingBinaryTypeBinding.java @@ -32,7 +32,7 @@ public MissingBinaryTypeBinding(PackageBinding packageBinding, char[][] compound this.fileName = CharOperation.concatWith(compoundName, '/'); this.sourceName = compoundName[compoundName.length - 1]; // [java][util][Map$Entry] this.modifiers = ClassFileConstants.AccPublic; - this.superclass = null; // will be fixed up using #setMissingSuperclass(...) + this.setSuperBinding(null); // will be fixed up using #setMissingSuperclass(...) this.memberTypes = Binding.NO_MEMBER_TYPES; this.fields = Binding.NO_FIELDS; this.methods = Binding.NO_METHODS; @@ -52,6 +52,6 @@ public int problemId() { * @see LookupEnvironment#cacheMissingBinaryType(char[][], org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration) */ void setMissingSuperclass(ReferenceBinding missingSuperclass) { - this.superclass = missingSuperclass; + this.setSuperBinding(missingSuperclass); } } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MultipleTypeBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MultipleTypeBinding.java index 2aab63e1..3782260d 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MultipleTypeBinding.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/MultipleTypeBinding.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2008 IBM Corporation and others. + * Copyright (c) 2005, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/PackageBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/PackageBinding.java index 26dc8392..fc9fbc55 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/PackageBinding.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/PackageBinding.java @@ -197,15 +197,15 @@ Binding getBinding0(char[] name, int mask) { if (binding!=null) return binding; } - if ( (mask&(Binding.TYPE))!=0) + if ( (mask&(Binding.METHOD))!=0) { - binding=getBinding1(name,Binding.TYPE); + binding=getBinding1(name,Binding.METHOD); if (binding!=null) return binding; } - if ( (mask&(Binding.METHOD))!=0) + if ( (mask&(Binding.TYPE))!=0) { - binding=getBinding1(name,Binding.METHOD); + binding=getBinding1(name,Binding.TYPE); if (binding!=null) return binding; } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ProblemReasons.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ProblemReasons.java index eeca0a92..921b72a3 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ProblemReasons.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ProblemReasons.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ReferenceBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ReferenceBinding.java index a8954b41..8837a9fd 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ReferenceBinding.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/ReferenceBinding.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -43,8 +43,6 @@ abstract public class ReferenceBinding extends TypeBinding implements IDependent private SimpleLookupTable compatibleCache; - public static ReferenceBinding LUB_GENERIC = new ReferenceBinding() { /* used for lub computation */}; - private static final Comparator FIELD_COMPARATOR = new Comparator() { public int compare(Object o1, Object o2) { char[] n1 = ((FieldBinding) o1).name; @@ -58,7 +56,7 @@ abstract public class ReferenceBinding extends TypeBinding implements IDependent MethodBinding m2 = (MethodBinding) o2; char[] s1 = m1.selector; char[] s2 = m2.selector; - int c = ReferenceBinding.compare(s1, s2, s1.length, s2.length); + int c = ReferenceBinding.compare(s1, s2, s1 == null ? 0 : s1.length, s2 == null ? 0 : s2.length); return c == 0 ? m1.parameters.length - m2.parameters.length : c; } }; @@ -96,7 +94,7 @@ public static FieldBinding binarySearch(char[] name, FieldBinding[] sortedFields * @return (start + (end<<32)) or -1 if no method found */ public static long binarySearch(char[] selector, MethodBinding[] sortedMethods) { - if (sortedMethods == null) + if (sortedMethods == null || selector == null || selector.length == 0) return -1; int max = sortedMethods.length; if (max == 0) @@ -227,7 +225,7 @@ public final boolean canBeSeenBy(ReferenceBinding receiverType, ReferenceBinding PackageBinding currentPackage = currentType.fPackage; // package could be null for wildcards/intersection types, ignore and recurse in superclass if (currentPackage != null && currentPackage != this.fPackage) return false; - } while ((currentType = currentType.superclass()) != null); + } while ((currentType = currentType.getSuperBinding()) != null); return false; } /* @@ -515,7 +513,7 @@ public boolean hasIncompatibleSuperType(ReferenceBinding otherType) { match = otherType.findSuperTypeWithSameErasure(currentType); if (match != null && !match.isIntersectingWith(currentType)) return true; - } while ((currentType = currentType.superclass()) != null); + } while ((currentType = currentType.getSuperBinding()) != null); // for (int i = 0; i < nextPosition; i++) { // currentType = interfacesToVisit[i]; @@ -547,7 +545,7 @@ boolean implementsMethod(MethodBinding method) { return true; } } - type = type.superclass(); + type = type.getSuperBinding(); } return false; } @@ -581,9 +579,17 @@ public boolean isCompatibleWith(TypeBinding otherType) { return result == Boolean.TRUE; } } - this.compatibleCache.put(otherType, Boolean.FALSE); // protect from recursive call + boolean cacheThisBinding = true; + if(this instanceof ProblemReferenceBinding) { + cacheThisBinding = false; + } + if(cacheThisBinding) { + this.compatibleCache.put(otherType, Boolean.FALSE); // protect from recursive call + } if (isCompatibleWith0(otherType)) { - this.compatibleCache.put(otherType, Boolean.TRUE); + if(cacheThisBinding) { + this.compatibleCache.put(otherType, Boolean.TRUE); + } return true; } return false; @@ -672,7 +678,7 @@ public final boolean isStrictfp() { * NOTE: Object.isSuperclassOf(Object) -> false */ public boolean isSuperclassOf(ReferenceBinding otherType) { - while ((otherType = otherType.superclass()) != null) { + while ((otherType = otherType.getSuperBinding()) != null) { if (otherType.isEquivalentTo(this)) return true; } return false; @@ -690,7 +696,7 @@ public boolean isThrowable() { case TypeIds.T_JavaLangException : return true; } - } while ((current = current.superclass()) != null); + } while ((current = current.getSuperBinding()) != null); return false; } /** @@ -713,7 +719,7 @@ public boolean isUncheckedException(boolean includeSupertype) { return includeSupertype; } ReferenceBinding current = this; - while ((current = current.superclass()) != null) { + while ((current = current.getSuperBinding()) != null) { switch (current.id) { case TypeIds.T_JavaLangError : case TypeIds.T_JavaLangRuntimeException : @@ -761,8 +767,8 @@ public final ReferenceBinding outermostEnclosingType() { */ public char[] qualifiedSourceName() { - if (isMemberType()) - return CharOperation.concat(enclosingType().qualifiedSourceName(), sourceName(), '.'); +// if (isMemberType()) +// return CharOperation.concat(enclosingType().qualifiedSourceName(), sourceName(), '.'); return sourceName(); } @@ -800,7 +806,7 @@ public char[] sourceName() { return this.sourceName; } -public ReferenceBinding superclass() { +public ReferenceBinding getSuperBinding() { return null; } public InferredType getInferredType() { diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/Scope.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/Scope.java index d9879f5a..f58926b1 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/Scope.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/Scope.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2011 IBM Corporation and others. + * Copyright (c) 2007, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -11,12 +11,15 @@ package org.eclipse.wst.jsdt.internal.compiler.lookup; import java.util.ArrayList; +import java.util.HashSet; import java.util.Iterator; import java.util.Map; +import java.util.Set; import org.eclipse.wst.jsdt.core.JavaScriptCore; import org.eclipse.wst.jsdt.core.compiler.CharOperation; import org.eclipse.wst.jsdt.core.infer.InferredType; +import org.eclipse.wst.jsdt.internal.compiler.Compiler; import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode; import org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.wst.jsdt.internal.compiler.ast.CaseStatement; @@ -29,7 +32,6 @@ import org.eclipse.wst.jsdt.internal.compiler.problem.AbortCompilation; import org.eclipse.wst.jsdt.internal.compiler.problem.ProblemReporter; import org.eclipse.wst.jsdt.internal.compiler.util.HashtableOfObject; import org.eclipse.wst.jsdt.internal.compiler.util.ObjectVector; -import org.eclipse.wst.jsdt.internal.compiler.util.SimpleSet; import org.eclipse.wst.jsdt.internal.core.Logger; public abstract class Scope implements TypeConstants, TypeIds { @@ -327,10 +329,7 @@ public abstract class Scope implements TypeConstants, TypeIds { MethodBinding concreteMatch) { int startFoundSize = found.size; - ReferenceBinding currentType = classHierarchyStart; - while (currentType != null) { - currentType = currentType.superclass(); - } + MethodBinding[] candidates = null; int candidatesCount = 0; MethodBinding problemMethod = null; @@ -359,7 +358,7 @@ public abstract class Scope implements TypeConstants, TypeIds { if (concreteMatch == null) { if (candidatesCount == 0) return problemMethod; // can be null - concreteMatch = candidates[0]; + concreteMatch = candidates != null ? candidates[0] : null; } return concreteMatch; } @@ -449,18 +448,32 @@ public abstract class Scope implements TypeConstants, TypeIds { return new ProblemFieldBinding(field /* closest match*/, field.declaringClass, fieldName, ProblemReasons.NotVisible); } // collect all superinterfaces of receiverType until the field is found in a supertype - int nextPosition = 0; FieldBinding visibleField = null; boolean keepLooking = true; FieldBinding notVisibleField = null; // we could hold onto the not visible field for extra error reporting + + Set checkedParents = new HashSet(); while (keepLooking) { if (JavaScriptCore.IS_ECMASCRIPT4) { ((SourceTypeBinding) currentType).classScope.connectTypeHierarchy(); } - if ((currentType = currentType.superclass()) == null) + if ((currentType = currentType.getSuperBinding()) == null) { + break; + } + + /* if current type is already a parent that was check break to prevent + * infinite loop. This can happen if something gets messed up with + * the parentage of a type and there ends up being a parentage loop. + * + * else add the current type to the checked parents and continue on + */ + if(checkedParents.contains(currentType)) { break; + } else { + checkedParents.add(currentType); + } unitScope.recordTypeReference(currentType); if ((field = currentType.getField(fieldName, needResolve)) != null) { @@ -512,6 +525,7 @@ public abstract class Scope implements TypeConstants, TypeIds { boolean keepLooking = true; ReferenceBinding notVisible = null; // we could hold onto the not visible field for extra error reporting + Set checkedParents = new HashSet(); while (keepLooking) { ReferenceBinding sourceType = currentType; @@ -519,8 +533,21 @@ public abstract class Scope implements TypeConstants, TypeIds { return null; // looking for an undefined member type in its own superclass ref ((SourceTypeBinding) sourceType).classScope.connectTypeHierarchy(); - if ((currentType = currentType.superclass()) == null) + if ((currentType = currentType.getSuperBinding()) == null) { break; + } + + /* if current type is already a parent that was check break to prevent + * infinite loop. This can happen if something gets messed up with + * the parentage of a type and there ends up being a parentage loop. + * + * else add the current type to the checked parents and continue on + */ + if(checkedParents.contains(currentType)) { + break; + } else { + checkedParents.add(currentType); + } unitScope.recordReference(currentType, typeName); if ((memberType = currentType.getMemberType(typeName)) != null) { @@ -564,7 +591,15 @@ public abstract class Scope implements TypeConstants, TypeIds { return null; } - // Internal use only - use findMethod() + /** + * NOTE: Internal use only - use findMethod() + * + * @param receiverType + * @param selector + * @param argumentTypes null means match on any arguments + * @param invocationSite + * @return + */ public MethodBinding findMethod(ReferenceBinding receiverType, char[] selector, TypeBinding[] argumentTypes, InvocationSite invocationSite) { ReferenceBinding currentType = receiverType; ObjectVector found = new ObjectVector(3); @@ -584,7 +619,20 @@ public abstract class Scope implements TypeConstants, TypeIds { boolean isCompliant14 = complianceLevel >= ClassFileConstants.JDK1_4; boolean isCompliant15 = complianceLevel >= ClassFileConstants.JDK1_5; ReferenceBinding classHierarchyStart = currentType; + Set checkedParents = new HashSet(); while (currentType != null) { + /* if current type is already a parent that was check break to prevent + * infinite loop. This can happen if something gets messed up with + * the parentage of a type and there ends up being a parentage loop. + * + * else add the current type to the checked parents and continue on + */ + if(checkedParents.contains(currentType)) { + break; + } else { + checkedParents.add(currentType); + } + unitScope.recordTypeReference(currentType); MethodBinding[] currentMethods = currentType.getMethods(selector); int currentLength = currentMethods.length; @@ -627,7 +675,7 @@ public abstract class Scope implements TypeConstants, TypeIds { } } } - currentType = currentType.superclass(); + currentType = currentType.getSuperBinding(); } if (found.size==0 && (receiverType==null || receiverType instanceof CompilationUnitBinding)) @@ -1355,15 +1403,15 @@ public abstract class Scope implements TypeConstants, TypeIds { } //get the methods - MethodBinding[] methods = receiverType.getMethods(receiverType.sourceName); + MethodBinding[] methods = receiverType.sourceName != null ? receiverType.getMethods(receiverType.sourceName) : null; MethodBinding constructor = null; if (methods == null || methods == Binding.NO_METHODS || methods.length == 0){ constructor = new MethodBinding(0, receiverType.sourceName, receiverType, null,receiverType); } else { - - if(methods.length > 1) { - Logger.log(Logger.WARNING, "There should only ever be one match for a constructor search" + - " but found " + methods.length + " when looking for " + + //log warning about to many constructors + if(methods.length > 1 && Compiler.DEBUG) { + Logger.log(Logger.WARNING_DEBUG, "Scope#getConstructor: There should only ever be one match for a" + + " constructor search but found " + methods.length + " when looking for " + new String(receiverType.sourceName) + ". Using the first match."); } @@ -1407,7 +1455,7 @@ public abstract class Scope implements TypeConstants, TypeIds { MethodScope methodScope = methodScope(); if (!methodScope.isInsideInitializer()){ // check method modifiers to see if deprecated - MethodBinding context = ((AbstractMethodDeclaration)methodScope.referenceContext).binding; + MethodBinding context = ((AbstractMethodDeclaration)methodScope.referenceContext).getBinding(); if (context != null) return context.modifiers; } else { @@ -1454,11 +1502,14 @@ public abstract class Scope implements TypeConstants, TypeIds { env.missingClassFileLocation = invocationSite; //first look for field FieldBinding field = findField(receiverType, fieldName, invocationSite, true /*resolve*/); - if (field != null) return field; - + if (field != null) { + return field; + } - /* not sure if this fix is correct, but reciever type is [sometimes] coming in as "BaseTypeBinding" and causing a classcastexception */ - MethodBinding method = findMethod( receiverType instanceof ReferenceBinding?(ReferenceBinding)receiverType:null, fieldName, new TypeBinding[0], invocationSite ); + /* not sure if this fix is correct, but receiver type is [sometimes] coming in as "BaseTypeBinding" and causing a classcastexception */ + MethodBinding method = findMethod( + receiverType instanceof ReferenceBinding?(ReferenceBinding)receiverType:null, + fieldName, null, invocationSite ); if( method != null ) { if (!method.isValidBinding()) @@ -2352,7 +2403,7 @@ public abstract class Scope implements TypeConstants, TypeIds { if (scope instanceof MethodScope) { ReferenceContext refContext = ((MethodScope) scope).referenceContext; if (refContext instanceof AbstractMethodDeclaration) - if (((AbstractMethodDeclaration) refContext).binding == method) + if (((AbstractMethodDeclaration) refContext).getBinding() == method) return true; } scope = scope.parent; @@ -2419,7 +2470,7 @@ public abstract class Scope implements TypeConstants, TypeIds { MethodScope methodScope = methodScope(); if (!methodScope.isInsideInitializer()){ // check method modifiers to see if deprecated - MethodBinding context = ((AbstractMethodDeclaration)methodScope.referenceContext).binding; + MethodBinding context = ((AbstractMethodDeclaration)methodScope.referenceContext).getBinding(); if (context != null && context.isViewedAsDeprecated()) return true; } else { @@ -2538,7 +2589,7 @@ public abstract class Scope implements TypeConstants, TypeIds { } currentType = (ReferenceBinding) typeToVisit; - TypeBinding itsSuperclass = currentType.superclass(); + TypeBinding itsSuperclass = currentType.getSuperBinding(); if (itsSuperclass != null) { TypeBinding superType = dim == 0 ? itsSuperclass : (TypeBinding)environment().createArrayType(itsSuperclass, dim); // recreate array if needed if (!typesToVisit.contains(superType)) { @@ -2696,7 +2747,16 @@ public abstract class Scope implements TypeConstants, TypeIds { return new ProblemMethodBinding(visible[0], visible[0].selector, visible[0].parameters, ProblemReasons.Ambiguous); } - // caveat: this is not a direct implementation of JLS + /** + * caveat: this is not a direct implementation of JLS + * + * @param visible + * @param visibleSize + * @param argumentTypes null means match on any arguments + * @param invocationSite + * @param receiverType + * @return + */ protected final MethodBinding mostSpecificMethodBinding(MethodBinding[] visible, int visibleSize, TypeBinding[] argumentTypes, InvocationSite invocationSite, ReferenceBinding receiverType) { int[] compatibilityLevels = new int[visibleSize]; for (int i = 0; i < visibleSize; i++) @@ -2758,8 +2818,6 @@ public abstract class Scope implements TypeConstants, TypeIds { nextSpecific : for (int i = 0; i < visibleSize; i++) { MethodBinding current = moreSpecific[i]; if (current != null) { - ReferenceBinding[] mostSpecificExceptions = null; - SimpleSet possibleMethods = null; MethodBinding original = current.original(); for (int j = 0; j < visibleSize; j++) { MethodBinding next = moreSpecific[j]; @@ -2810,38 +2868,13 @@ public abstract class Scope implements TypeConstants, TypeIds { } } } - if (mostSpecificExceptions != null) { - Object[] values = possibleMethods.values; - int exceptionLength = mostSpecificExceptions.length; - nextMethod : for (int p = 0, vLength = values.length; p < vLength; p++) { - MethodBinding possible = (MethodBinding) values[p]; - if (possible == null) continue nextMethod; - if (0 == exceptionLength) { - nextException : for (int e = 0; e < exceptionLength; e++) { - ReferenceBinding exception = null; - for (int f = 0; f < exceptionLength; f++) - if (exception == mostSpecificExceptions[f]) continue nextException; - continue nextMethod; - } - return possible; - } - } -// do not return a new methodBinding until we know that it does not cause problems -// return new FunctionBinding( -// current.modifiers, -// current.selector, -// current.returnType, -// current.parameters, -// mostSpecificExceptions, -// current.declaringClass -// ); - } + return current; } } - // if all moreSpecific methods are equal then see if duplicates exist because of substitution - return new ProblemMethodBinding(visible[0], visible[0].selector, visible[0].parameters, ProblemReasons.Ambiguous); + //if can not figure which one is best, just pick first one + return moreSpecific[0]; } public final ClassScope outerMostClassScope() { @@ -2866,7 +2899,19 @@ public abstract class Scope implements TypeConstants, TypeIds { return lastMethodScope; // may answer null if no method around } + /** + * + * @param method + * @param arguments null means match on any arguments + * + * @return + */ public int parameterCompatibilityLevel(MethodBinding method, TypeBinding[] arguments) { + //if not arguments to compare against, assume arguments do not matter, so compatible + if(arguments == null) { + return COMPATIBLE; + } + TypeBinding[] parameters = method.parameters; int paramLength = parameters.length; int argLength = arguments.length; diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/SourceTypeBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/SourceTypeBinding.java index 03ed1dd3..f3f663d9 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/SourceTypeBinding.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/SourceTypeBinding.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -11,24 +11,56 @@ package org.eclipse.wst.jsdt.internal.compiler.lookup; import java.util.HashMap; +import java.util.HashSet; import java.util.Hashtable; +import java.util.Iterator; +import java.util.LinkedList; import java.util.Map; +import java.util.Set; import java.util.zip.CRC32; +import org.eclipse.wst.jsdt.core.ast.IAssignment; +import org.eclipse.wst.jsdt.core.ast.IExpression; +import org.eclipse.wst.jsdt.core.ast.IFieldReference; +import org.eclipse.wst.jsdt.core.ast.IFunctionDeclaration; import org.eclipse.wst.jsdt.core.compiler.CharOperation; import org.eclipse.wst.jsdt.core.infer.InferredAttribute; import org.eclipse.wst.jsdt.core.infer.InferredMethod; import org.eclipse.wst.jsdt.core.infer.InferredType; import org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.wst.jsdt.internal.compiler.ast.Argument; +import org.eclipse.wst.jsdt.internal.compiler.ast.Assignment; +import org.eclipse.wst.jsdt.internal.compiler.ast.Expression; import org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration; +import org.eclipse.wst.jsdt.internal.compiler.ast.SingleNameReference; import org.eclipse.wst.jsdt.internal.compiler.ast.TypeReference; import org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants; import org.eclipse.wst.jsdt.internal.compiler.util.HashtableOfObject; import org.eclipse.wst.jsdt.internal.compiler.util.Util; public class SourceTypeBinding extends ReferenceBinding { - public ReferenceBinding superclass; + /** + *

+ * Enable for enhanced debugging + *

+ */ + private static final boolean DEBUG = false; + + /** + *

+ * Super type binding for this binding. + *

+ * + *

+ * WARNING: a linked binding may have a different supper binding. + *

+ * + * @see #getSuperBinding0() + * @see #getSuperBinding() + * @see #setSuperBinding(ReferenceBinding) + */ + private ReferenceBinding fSuperBinding; + protected FieldBinding[] fields; protected MethodBinding[] methods; public ReferenceBinding[] memberTypes = Binding.NO_MEMBER_TYPES; @@ -36,14 +68,85 @@ public class SourceTypeBinding extends ReferenceBinding { public Scope scope; public ClassScope classScope; - char[] genericReferenceTypeSignature; - - public SourceTypeBinding nextType; + /** + *

+ * The next type in the circular linked list of linked types. If this type is not linked to any other + * types then the value of {@link #fNextType} will be this type forming a circle of 1. + *

+ * + *

+ * Due to the circular nature of this linked list always use {@link #performActionOnLinkedBindings(LinkedBindingAction)} + * when needing to perform any action on all of the linked types. + *

+ * + * @see #performActionOnLinkedBindings(LinkedBindingAction) + * @see LinkedBindingAction + */ + private SourceTypeBinding fNextType; private static final CRC32 checksumCalculator = new CRC32(); + + /** + * true if all fields and functions have already been built, + * false otherwise + */ + private boolean fHasBuiltFieldsAndMethods; + + /** + * true if currently building fields and functions, + * false otherwise + */ + private boolean fBuildingAllFieldsAndFunctions; + + /** + *

+ * When building specific selectors using + * {@link #buildFieldsAndMethods(char[])} then this list contains all of + * the selectors currently being built. + *

+ * + *

+ * If all fields and functions are being built at once then this list is + * not used. use {@link #fBuildingAllFieldsAndFunctions} to detect this situation. + *

+ * + * @see #buildFieldsAndMethods(char[]) + * @see #fBuildingAllFieldsAndFunctions + */ + private char[][] fBuildingSelectors; + + /** + *

+ * If have built specific selectors using + * {@link #buildFieldsAndMethods(char[])} then this list contains all of + * the selectors that have already been built. + *

+ * + *

+ * If all fields and functions have been built then this list is not accurate. + * Use {@link #fHasBuiltFieldsAndMethods} to detect this situation. + *

+ * + * @see #buildFieldsAndMethods(char[]) + * @see #fHasBuiltFieldsAndMethods + */ + private char[][] fBuiltSelectors; + + /** + *

+ * Used to synchronize access to fields that keep track of field and function building. + *

+ * + * @see #fBuildingAllFieldsAndFunctions + * @see #fBuildingSelectors + * @see #fBuiltSelectors + */ + private final Object fBuildFieldsAndFunctionsLock = new Object(); public SourceTypeBinding(char[][] compoundName, PackageBinding fPackage, Scope scope) { + + this(); this.compoundName = compoundName; this.fPackage = fPackage; this.fileName = scope.referenceCompilationUnit().getFileName(); @@ -65,17 +168,133 @@ public class SourceTypeBinding extends ReferenceBinding { this.methods = Binding.NO_METHODS; computeId(); - } protected SourceTypeBinding() { - + //next type is a circular linked list + this.fNextType = this; + + this.fHasBuiltFieldsAndMethods = false; + this.fBuildingAllFieldsAndFunctions = false; + this.fBuildingSelectors = null; + this.fBuiltSelectors = null; } - + + /** + *

+ * Builds all fields and functions for this type. + *

+ * + *

+ * No operation if all fields and functions are already built. Also if an + * individual field or function has already been built then it will not be + * built again. + *

+ */ void buildFieldsAndMethods() { - buildFields(); - buildMethods(); + this.buildFieldsAndMethods(null); + } + /** + *

+ * If no restriction is given then the same as + * {@link #buildFieldsAndMethods()}, else if a restriction is given only + * fields and functions with the given selector are built. + *

+ * + *

+ * No operation if all fields and functions are already built. Also if an + * individual field or function has already been built then it will not be + * built again. + *

+ * + * @param restrictToSelector + * restrict building to only fields and functions with this + * selector, or if null build all fields and + * functions + */ + private void buildFieldsAndMethods(char[] restrictToSelector) { + synchronized (this.fBuildFieldsAndFunctionsLock) { + //if already building or have already built then do nothing + if(this.fBuildingAllFieldsAndFunctions || this.fHasBuiltFieldsAndMethods ) { + return; + } + + //if already building restrict to selector then do nothing + if(restrictToSelector != null && this.fBuildingSelectors != null && this.fBuildingSelectors.length > 0) { + if(CharOperation.contains(restrictToSelector, this.fBuildingSelectors)) { + return; + } + } + + //if already built selector then do nothing + if(restrictToSelector != null && this.fBuiltSelectors != null && this.fBuiltSelectors.length > 0) { + if(CharOperation.contains(restrictToSelector, this.fBuiltSelectors)) { + return; + } + } + + /* if restrict building to specific selector add it to list of currently building specific selectors + * else set building all fields and functions */ + if(restrictToSelector != null) { + if(this.fBuildingSelectors == null) { + this.fBuildingSelectors = new char[1][]; + this.fBuildingSelectors[0] = restrictToSelector; + } else { + char[][] newBuildingSelectors = new char[this.fBuildingSelectors.length+1][]; + System.arraycopy(this.fBuildingSelectors, 0, newBuildingSelectors, 0, this.fBuildingSelectors.length); + this.fBuildingSelectors = newBuildingSelectors; + this.fBuildingSelectors[this.fBuildingSelectors.length-1] = restrictToSelector; + } + } else { + this.fBuildingAllFieldsAndFunctions = true; + } + } + + try { + /* build functions first because building fields depends on built functions + * + * This is because building fields can add functions if their assignment is a function + * but only if a function with the fields name has not already been created */ + buildFunctions(restrictToSelector); + buildFields(restrictToSelector); + + if(restrictToSelector == null) { + this.fHasBuiltFieldsAndMethods = true; + } + } finally { + synchronized (this.fBuildFieldsAndFunctionsLock) { + if(restrictToSelector != null) { + //remove selector from list of building selectors + if(this.fBuildingSelectors.length == 1) { + this.fBuildingSelectors = null; + } else { + char[][] newBuildingSelectors = new char[this.fBuildingSelectors.length-1][]; + int j = 0; + for(int i = 0; i < this.fBuildingSelectors.length; ++i) { + if(!CharOperation.equals(restrictToSelector, this.fBuildingSelectors[i])) { + newBuildingSelectors[j++] = this.fBuildingSelectors[i]; + } + } + + this.fBuildingSelectors = newBuildingSelectors; + } + + //add selector to list of built selectors + if(this.fBuiltSelectors == null) { + this.fBuiltSelectors = new char[1][]; + this.fBuiltSelectors[0] = restrictToSelector; + } else { + char[][] newBuiltSelectors = new char[this.fBuiltSelectors.length+1][]; + System.arraycopy(this.fBuiltSelectors, 0, newBuiltSelectors, 0, this.fBuiltSelectors.length); + this.fBuiltSelectors = newBuiltSelectors; + this.fBuiltSelectors[this.fBuiltSelectors.length-1] = restrictToSelector; + } + } else { + this.fBuildingAllFieldsAndFunctions = false; + } + } + } } /** @@ -90,73 +309,201 @@ public class SourceTypeBinding extends ReferenceBinding { return classScope.inferredType; } - private void buildFields() { - FieldBinding prototype = new FieldBinding(TypeConstants.PROTOTYPE, - TypeBinding.UNKNOWN, modifiers - | ExtraCompilerModifiers.AccUnresolved, this); + /** + *

+ * Build all or a specific field. + *

+ * + * @param restrictToSelector + * build only fields with this selector, or if + * null build all fields + */ + private void buildFields(char[] restrictToSelector) { + if(this.classScope == null) + return; InferredType inferredType = this.classScope.inferredType; int size = inferredType.numberAttributes; - if (size == 0) { - setFields(new FieldBinding[] { prototype }); - return; - } - - // iterate the field declarations to create the bindings, lose all - // duplicates + + // iterate the field declarations to create the bindings, lose all duplicates FieldBinding[] fieldBindings = new FieldBinding[size + 1]; HashtableOfObject knownFieldNames = new HashtableOfObject(size); boolean duplicate = false; int count = 0; for (int i = 0; i < size; i++) { InferredAttribute field = inferredType.attributes[i]; - int modifiers = 0; - if (field.isStatic) - modifiers |= ClassFileConstants.AccStatic; - InferredType fieldType = field.type; - TypeBinding fieldTypeBinding = null; - if (fieldType != null) { - // fieldTypeBinding = BaseTypeBinding.UNKNOWN; - // fieldTypeBinding = scope.getType(fieldType.getName()); - fieldTypeBinding = fieldType.resolveType(scope, field.node); - } - if (fieldTypeBinding == null) - fieldTypeBinding = TypeBinding.UNKNOWN; - - FieldBinding fieldBinding = new FieldBinding(field, - fieldTypeBinding, modifiers - | ExtraCompilerModifiers.AccUnresolved, this); - fieldBinding.id = count; - // field's type will be resolved when needed for top level types - // checkAndSetModifiersForField(fieldBinding, field); - - if (knownFieldNames.containsKey(field.name)) { - duplicate = true; - FieldBinding previousBinding = (FieldBinding) knownFieldNames - .get(field.name); - if (previousBinding != null) { - for (int f = 0; f < i; f++) { - InferredAttribute previousField = inferredType.attributes[f]; - if (previousField.binding == previousBinding) { - scope.problemReporter().duplicateFieldInType(this, - previousField); - previousField.binding = null; - break; + + /* only build field if either the restricted selector is not set or + * the field name matches the restricted selector. + * + * Also skip any field that is already building or has already been built */ + if((restrictToSelector == null || CharOperation.equals(field.name, restrictToSelector)) && + (restrictToSelector != null || !CharOperation.contains(field.name, this.fBuildingSelectors)) && + !CharOperation.contains(field.name, this.fBuiltSelectors)) { + + int modifiers = 0; + if (field.isStatic) { + modifiers |= ClassFileConstants.AccStatic; + } + + InferredType fieldType = field.type; + TypeBinding fieldTypeBinding = null; + + Scope searchScope = null; + + /* if field type set then use that for binding + * else if field node is an assignment use that + * + * TODO: this is not the correct logic because it does not deal + * with cases where the RHS is a function and the field type + * has already been resolved to function because then the function + * itself has not actually been resolved yet, so we can not create + * a function binding on this type for it. Initial attempts to fix + * this flaw have caused performance issues, so it will have to be + * addressed latter. To fix this turn this into two ifs, but again + * that then tanks performance for SOME scenarios.*/ + if (fieldType != null) { + fieldTypeBinding = fieldType.resolveType(scope, field.node); + } else if(field.node instanceof IAssignment) { + IExpression rhs = ((IAssignment)field.node).getExpression(); + + if(rhs instanceof Expression) { + fieldTypeBinding = ((Expression) rhs).resolvedType; + + /* if field binding for RHS not set or is any look for a better one, + * if function then local scope needs to be built so function can be resolved */ + if(fieldTypeBinding == null || fieldTypeBinding.isAnyType()) { + + /* if node is an assignment and that assignment is contained + * in a function resolve the function first */ + IFunctionDeclaration containingFunction = null; + if(field.node instanceof Assignment) { + containingFunction = ((Assignment)field.node).getContainingFunction(); + if(containingFunction != null && containingFunction instanceof AbstractMethodDeclaration) { + ((AbstractMethodDeclaration)containingFunction).buildLocals(this.scope.compilationUnitScope()); + searchScope = ((AbstractMethodDeclaration)containingFunction).getScope(); + } + } + + //if no search scope found yet find first parent scope that is a BlockScope + if(searchScope == null) { + searchScope = this.scope; + while(searchScope != null && !(searchScope instanceof BlockScope)) { + searchScope = searchScope.parent; + } + } + + //use search scope to find binding + TypeBinding resolvedBinding = ((Expression) rhs).resolveType((BlockScope)searchScope); + if(resolvedBinding != null) { + fieldTypeBinding = resolvedBinding; + } + } + } + + //if RHS binding is a function so create a new function binding on this source binding + if(fieldTypeBinding != null && isFunctionType(fieldTypeBinding)) { + + /* if RHS is a field reference search its receiver for the function binding for the assigned function + * else if single name reference just use its method bindingn */ + MethodBinding assignedFuncBinding = null; + + /* this is to deal with cases like: + * foo = (bar = function() {}); */ + while(rhs instanceof IAssignment) { + rhs = ((IAssignment)rhs).getExpression(); + } + + if(rhs instanceof IFieldReference) { + char[] selector = ((IFieldReference) rhs).getToken(); + IExpression receiver = ((IFieldReference) rhs).getReceiver(); + if(receiver instanceof Expression) { + TypeBinding receiverType = ((Expression) receiver).resolvedType; + if(receiverType instanceof SourceTypeBinding) { + //if found bindings use first one + MethodBinding[] funcBindings = ((SourceTypeBinding) receiverType).getMethods(selector); + if(funcBindings != null && funcBindings.length > 0) { + assignedFuncBinding = funcBindings[0]; + } + } + } + } else if(rhs instanceof SingleNameReference) { + Binding binding = ((SingleNameReference) rhs).binding; + + /* if binding is method binding just use that + * else if binding is local variable, find func binding in scope with same name as variable + * var foo; + * foo = function() {} */ + if(binding instanceof MethodBinding) { + assignedFuncBinding = (MethodBinding)binding; + } else if(binding instanceof LocalVariableBinding && searchScope != null) { + if(searchScope instanceof BlockScope) { + assignedFuncBinding = ((BlockScope)searchScope).findMethod(field.name, null, true); + } else { + assignedFuncBinding = searchScope.findMethod(null, field.name, null, null); + } + } + } + + //if RHS was a function binding create a new function binding on this type binding + if(assignedFuncBinding != null) { + InferredMethod dupMeth = inferredType.findMethod(field.name, null); + if(dupMeth == null) { + MethodBinding[] funcBindings = this.getMethods(field.name); + if(funcBindings == null || funcBindings.length == 0) { + MethodBinding funcBinding = new MethodBinding(assignedFuncBinding, this); + funcBinding.setSelector(field.name); + this.addMethod(funcBinding); + } + } } } } - knownFieldNames.put(field.name, null); // ensure that the - // duplicate field is - // found & removed - scope.problemReporter().duplicateFieldInType(this, field); - field.binding = null; - } else { - knownFieldNames.put(field.name, fieldBinding); - // remember that we have seen a field with this name - if (fieldBinding != null) + + if (fieldTypeBinding == null) { + fieldTypeBinding = TypeBinding.UNKNOWN; + } + + FieldBinding fieldBinding = new FieldBinding(field, + fieldTypeBinding, modifiers + | ExtraCompilerModifiers.AccUnresolved, this); + fieldBinding.id = count; + + if (knownFieldNames.containsKey(field.name)) { + duplicate = true; + FieldBinding previousBinding = (FieldBinding) knownFieldNames + .get(field.name); + if (previousBinding != null) { + for (int f = 0; f < i; f++) { + InferredAttribute previousField = inferredType.attributes[f]; + if (previousField.binding == previousBinding) { + scope.problemReporter().duplicateFieldInType(this, + previousField); + previousField.binding = null; + break; + } + } + } + // ensure that the duplicate field is found & removed + knownFieldNames.put(field.name, null); + scope.problemReporter().duplicateFieldInType(this, field); + field.binding = null; + } else { + knownFieldNames.put(field.name, fieldBinding); + // remember that we have seen a field with this name fieldBindings[count++] = fieldBinding; + } } } - fieldBindings[count++] = prototype; + + //only add prototype if not building specific selector + if(restrictToSelector == null) { + FieldBinding prototype = new FieldBinding(TypeConstants.PROTOTYPE, + TypeBinding.UNKNOWN, modifiers + | ExtraCompilerModifiers.AccUnresolved, this); + + fieldBindings[count++] = prototype; + } + // remove duplicate fields if (duplicate) { FieldBinding[] newFieldBindings = new FieldBinding[fieldBindings.length]; @@ -172,19 +519,34 @@ public class SourceTypeBinding extends ReferenceBinding { } fieldBindings = newFieldBindings; } - if (count != fieldBindings.length) + + //make sure array length is correct + if (count != fieldBindings.length) { System.arraycopy(fieldBindings, 0, fieldBindings = new FieldBinding[count], 0, count); - setFields(fieldBindings); + } + + this.addFields(fieldBindings); } - private void buildMethods() { + /** + *

+ * Build all or a specific function. + *

+ * + * @param restrictToSelector + * build only functions with this selector, or if + * null build all functions + */ + private void buildFunctions(char[] restrictToSelector) { + if(this.classScope == null) { + return; + } InferredType inferredType = this.classScope.inferredType; int size = (inferredType.methods != null) ? inferredType.methods.size() : 0; if (size == 0) { - setMethods(Binding.NO_METHODS); return; } @@ -192,40 +554,80 @@ public class SourceTypeBinding extends ReferenceBinding { MethodBinding[] methodBindings = new MethodBinding[size]; // create bindings for source methods for (int i = 0; i < size; i++) { - InferredMethod method = (InferredMethod) inferredType.methods.get(i); - - //determine if the method already has a resolved scope or not - boolean doesNotHaveResolvedScope = method.getFunctionDeclaration() instanceof AbstractMethodDeclaration && - ((AbstractMethodDeclaration)method.getFunctionDeclaration()).scope == null; - - //build method scope - MethodDeclaration methDec = (MethodDeclaration) method.getFunctionDeclaration(); - MethodScope scope = new MethodScope(this.scope, methDec, false); - MethodBinding methodBinding = scope.createMethod(method, this); - - //bind arguments - method.methodBinding = methodBinding; - methDec.binding = methodBinding; - methDec.bindArguments(); + InferredMethod inferredMethod = (InferredMethod) inferredType.methods.get(i); - if (methodBinding != null) // is null if binding could not be - // created - methodBindings[count++] = methodBinding; - - // if method did not already have a resolved scope, then add it to the environment - if(doesNotHaveResolvedScope) { - this.scope.environment().defaultPackage.addBinding( - methodBinding, methodBinding.selector, - Binding.METHOD); + /* only build function if either the restricted selector is not set or + * the function name matches the restricted selector. + * + * Also skip any function that is already building or has already been built */ + if((restrictToSelector == null || CharOperation.equals(inferredMethod.name, restrictToSelector)) && + (restrictToSelector != null || !CharOperation.contains(inferredMethod.name, this.fBuildingSelectors)) && + !CharOperation.contains(inferredMethod.name, this.fBuiltSelectors)) { + + //determine if the method already has a resolved scope or not + boolean doesNotHaveResolvedScope = inferredMethod.getFunctionDeclaration() instanceof AbstractMethodDeclaration && + ((AbstractMethodDeclaration)inferredMethod.getFunctionDeclaration()).getScope() == null; + + //build method scope + MethodDeclaration methDec = (MethodDeclaration) inferredMethod.getFunctionDeclaration(); + MethodBinding methodBinding; + + /* if does not already have a binding or existing binding has a different name then + * current inferred function create a new method binding + * else use existing method binding */ + if(!methDec.hasBinding() || !CharOperation.equals(methDec.getBinding().selector, inferredMethod.name)) { + MethodScope scope = new MethodScope(this.scope, methDec, false); + + /* if the inferred method specifies that it is in a type use that one. + * + * This is for the case where a method has been mixed in from another type + * but we still want that method to be reported as defined on the other + * type and not this type */ + SourceTypeBinding declaringTypeBinding = null; + if(inferredMethod.inType != null && inferredMethod.inType.binding != null && !inferredMethod.isConstructor) { + declaringTypeBinding = inferredMethod.inType.binding; + } else { + declaringTypeBinding = this; + } + + /* if not existing binding or is a constructor then use scope to create new binding + * else create new binding based on existing binding */ + if(!methDec.hasBinding() || inferredMethod.isConstructor) { + methodBinding = scope.createMethod(inferredMethod, declaringTypeBinding); + } else { + methodBinding = new MethodBinding(methDec.getBinding(), declaringTypeBinding); + methodBinding.setSelector(inferredMethod.name); + } + } else { + methodBinding = methDec.getBinding(); + } + + //set bindings + inferredMethod.methodBinding = methodBinding; + methDec.setBinding(methodBinding); + + //is null if binding could not be created + if (methodBinding != null) { + methodBindings[count++] = methodBinding; + + // if method did not already have a resolved scope, then add it to the environment + if(doesNotHaveResolvedScope) { + this.scope.environment().defaultPackage.addBinding( + methodBinding, methodBinding.selector, + Binding.METHOD); + } + } } } - if (count != methodBindings.length) + if (count != methodBindings.length) { System.arraycopy(methodBindings, 0, methodBindings = new MethodBinding[count], 0, count); - tagBits &= ~TagBits.AreMethodsSorted; // in case some static imports - // reached already into this - // type - setMethods(methodBindings); + } + + // in case some static imports reached already into this type + tagBits &= ~TagBits.AreMethodsSorted; + + this.addMethods(methodBindings); } public int kind() { @@ -252,9 +654,7 @@ public class SourceTypeBinding extends ReferenceBinding { start = CharOperation.lastIndexOf('/', uniqueKey) + 1; if (start == 0) start = 1; // start after L - end = CharOperation.indexOf('$', uniqueKey, start); - if (end == -1) - end = CharOperation.indexOf('<', uniqueKey, start); + end = CharOperation.indexOf('<', uniqueKey, start); if (end == -1) end = CharOperation.indexOf(';', uniqueKey, start); char[] topLevelType = CharOperation.subarray(uniqueKey, start, end); @@ -283,162 +683,162 @@ public class SourceTypeBinding extends ReferenceBinding { this.modifiers |= ExtraCompilerModifiers.AccDeprecatedImplicitly; fields(); methods(); - - // for (int i = 0, length = this.memberTypes.length; i < length; i++) - // ((SourceTypeBinding) - // this.memberTypes[i]).faultInTypesForFieldsAndMethods(); } - // NOTE: the type of each field of a source type is resolved when needed + /** + *

+ * NOTE: the type of each field of a source type is resolved when needed + *

+ * + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding#fields() + */ public FieldBinding[] fields() { - Map fieldCache = new HashMap(); - if ((this.tagBits & TagBits.AreFieldsComplete) == 0) { - - int failed = 0; - FieldBinding[] resolvedFields = this.fields; - try { - // lazily sort fields - if ((this.tagBits & TagBits.AreFieldsSorted) == 0) { - int length = this.fields.length; - if (length > 1) - ReferenceBinding.sortFields(this.fields, 0, length); - this.tagBits |= TagBits.AreFieldsSorted; - } - for (int i = 0, length = this.fields.length; i < length; i++) { - if (resolveTypeFor(this.fields[i]) == null) { - // do not alter original field array until resolution is - // over, due to reentrance (143259) - if (resolvedFields == this.fields) { - System.arraycopy(this.fields, 0, - resolvedFields = new FieldBinding[length], - 0, length); + final Map fieldCache = new HashMap(); + + //get fields across all linked types + this.performActionOnLinkedBindings(new LinkedBindingAction() { + /** + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding.LinkedBindingAction#performAction(org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding) + */ + public boolean performAction(SourceTypeBinding linkedBinding) { + //be sure fields and methods are built + linkedBinding.buildFieldsAndMethods(); + + // complete fields if not yet complete + if ((linkedBinding.tagBits & TagBits.AreFieldsComplete) == 0) { + int failed = 0; + FieldBinding[] resolvedFields = linkedBinding.fields; + try { + // lazily sort fields + if ((linkedBinding.tagBits & TagBits.AreFieldsSorted) == 0) { + int length = linkedBinding.fields.length; + if (length > 1) { + ReferenceBinding.sortFields(linkedBinding.fields, 0, length); + } + linkedBinding.tagBits |= TagBits.AreFieldsSorted; + } + for (int i = 0, length = linkedBinding.fields.length; i < length; i++) { + if (linkedBinding.resolveTypeFor(linkedBinding.fields[i]) == null) { + /* do not alter original field array until resolution is + * over, due to reentrance (143259) */ + if (resolvedFields == linkedBinding.fields) { + System.arraycopy(linkedBinding.fields, 0, + resolvedFields = new FieldBinding[length], + 0, length); + } + resolvedFields[i] = null; + failed++; + } + } + } finally { + if (failed > 0) { + // ensure fields are consistent regardless of the error + int newSize = resolvedFields.length - failed; + if (newSize == 0) { + linkedBinding.setFields(Binding.NO_FIELDS); + } else { + FieldBinding[] newFields = new FieldBinding[newSize]; + for (int i = 0, j = 0, length = resolvedFields.length; i < length; i++) { + if (resolvedFields[i] != null) { + newFields[j++] = resolvedFields[i]; + } + } + linkedBinding.setFields(newFields); + } } - resolvedFields[i] = null; - failed++; } - fieldCache.put(this.fields[i].name, this.fields[i]); + + //mark fields as complete + linkedBinding.tagBits |= TagBits.AreFieldsComplete; } - } finally { - if (failed > 0) { - // ensure fields are consistent reqardless of the error - int newSize = resolvedFields.length - failed; - if (newSize == 0) - return this.fields = Binding.NO_FIELDS; - - FieldBinding[] newFields = new FieldBinding[newSize]; - for (int i = 0, j = 0, length = resolvedFields.length; i < length; i++) { - if (resolvedFields[i] != null) - newFields[j++] = resolvedFields[i]; + + //add fields to combined cache + for(int i = 0; i < linkedBinding.fields.length; i++) { + if(linkedBinding.fields[i] != null) { + fieldCache.put(linkedBinding.fields[i].name, linkedBinding.fields[i]); } - this.fields = newFields; - } - } - this.tagBits |= TagBits.AreFieldsComplete; - } else { - for(int i = 0; i < this.fields.length; i++) { - if(this.fields[i] != null) - fieldCache.put(this.fields[i].name, this.fields[i]); - } - } - if (this.nextType != null) { - FieldBinding[] moreFields = this.nextType.fields(); - for(int i = 0; i < moreFields.length; i++) { - if(fieldCache.get(moreFields[i].name) == null) { - fieldCache.put(moreFields[i].name, moreFields[i]); } + + // always search every linked type + return true; } -// FieldBinding[] combinedFields = new FieldBinding[this.fields.length -// + moreFields.length]; -// System.arraycopy(this.fields, 0, combinedFields, 0, -// this.fields.length); -// System.arraycopy(moreFields, 0, combinedFields, this.fields.length, -// moreFields.length); - - return (FieldBinding[]) fieldCache.values().toArray(new FieldBinding[0]); - //return combinedFields; - - } else - return this.fields; - } - - public MethodBinding[] getDefaultAbstractMethods() { - int count = 0; - for (int i = this.methods.length; --i >= 0;) - if (this.methods[i].isDefaultAbstract()) - count++; - if (count == 0) - return Binding.NO_METHODS; - - MethodBinding[] result = new MethodBinding[count]; - count = 0; - for (int i = this.methods.length; --i >= 0;) - if (this.methods[i].isDefaultAbstract()) - result[count++] = this.methods[i]; - return result; + }); + + return (FieldBinding[]) fieldCache.values().toArray(new FieldBinding[0]); } - public MethodBinding getExactConstructor(TypeBinding[] argumentTypes) { - MethodBinding exactConstructor = getExactConstructor0(argumentTypes); - if (exactConstructor == null && this.nextType != null) - exactConstructor = this.nextType.getExactConstructor(argumentTypes); + /** + *

+ * Finds an exact constructor match searching across all linked type bindings. + *

+ * @see org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding#getExactConstructor(org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding[]) + */ + public MethodBinding getExactConstructor(final TypeBinding[] argumentTypes) { + MethodBinding exactConstructor = (MethodBinding)this.performActionOnLinkedBindings(new LinkedBindingAction() { + /** + *

+ * The exact constructor match found on any of the linked types. + *

+ */ + private MethodBinding fExactConstructorMatch = null; + + /** + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding.LinkedBindingAction#performAction(org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding) + */ + public boolean performAction(SourceTypeBinding linkedBinding) { + //be sure fields and methods are built + linkedBinding.buildFieldsAndMethods(); + + this.fExactConstructorMatch = linkedBinding.getExactConstructor0(argumentTypes); + + //keep processing if have not yet found exact match + return this.fExactConstructorMatch == null; + } + + /** + * @return {@link MethodBinding} + * + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding.LinkedBindingAction#getFinalResult() + */ + public Object getFinalResult() { + return this.fExactConstructorMatch; + } + }); + return exactConstructor; } // NOTE: the return type, arg & exception types of each method of a source // type are resolved when needed private MethodBinding getExactConstructor0(TypeBinding[] argumentTypes) { - int argCount = argumentTypes.length; - if ((this.tagBits & TagBits.AreMethodsComplete) != 0) { // have resolved - // all arg types - // & return type - // of the - // methods + // have resolved all arg types & return type of the methods + if ((this.tagBits & TagBits.AreMethodsComplete) != 0) { long range; - if ((range = ReferenceBinding.binarySearch(TypeConstants.INIT, - this.methods)) >= 0) { - // nextMethod: - for (int imethod = (int) range, end = (int) (range >> 32); imethod <= end; imethod++) { - MethodBinding method = this.methods[imethod]; - // if (method.parameters.length == argCount) { - // TypeBinding[] toMatch = method.parameters; - // for (int iarg = 0; iarg < argCount; iarg++) - // if (toMatch[iarg] != argumentTypes[iarg]) - // continue nextMethod; + if ((range = ReferenceBinding.binarySearch(TypeConstants.INIT, this.methods)) >= 0) { + if((int) range <= (int) (range >> 32)) { + MethodBinding method = this.methods[(int) range]; return method; - // } } } } else { // lazily sort methods if ((this.tagBits & TagBits.AreMethodsSorted) == 0) { int length = this.methods.length; - if (length > 1) + if (length > 1) { ReferenceBinding.sortMethods(this.methods, 0, length); + } this.tagBits |= TagBits.AreMethodsSorted; } long range; - if ((range = ReferenceBinding.binarySearch(TypeConstants.INIT, - this.methods)) >= 0) { - // nextMethod: - for (int imethod = (int) range, end = (int) (range >> 32); imethod <= end; imethod++) { - MethodBinding method = this.methods[imethod]; + if ((range = ReferenceBinding.binarySearch(TypeConstants.INIT, this.methods)) >= 0) { + if((int) range <= (int) (range >> 32)) { + MethodBinding method = this.methods[(int) range]; if (resolveTypesFor(method) == null || method.returnType == null) { methods(); - return getExactConstructor(argumentTypes); // try again - // since the - // problem - // methods - // have been - // removed + // try again since the problem methods have been removed + return getExactConstructor(argumentTypes); } - // if (method.parameters.length == argCount) { - // TypeBinding[] toMatch = method.parameters; - // for (int iarg = 0; iarg < argCount; iarg++) - // if (toMatch[iarg] != argumentTypes[iarg]) - // continue nextMethod; - // return method; - // } return method; } } @@ -446,49 +846,168 @@ public class SourceTypeBinding extends ReferenceBinding { return null; } - public MethodBinding getExactMethod(char[] selector, - TypeBinding[] argumentTypes, CompilationUnitScope refScope) { - MethodBinding exactMethod = getExactMethod0(selector, argumentTypes, - refScope); - if (exactMethod == null && this.nextType != null) - exactMethod = this.nextType.getExactMethod(selector, argumentTypes, - refScope); + /** + *

+ * Finds an exact function match searching across all linked type bindings + * and their super types. + *

+ * + *

+ * NOTE: this uses a breadth first search to find an exact function + * binding, first it searches all linked bindings, then their parents, so + * forth and so on. + *

+ * + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding#getExactMethod(char[], + * org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding[], + * org.eclipse.wst.jsdt.internal.compiler.lookup.CompilationUnitScope) + */ + public MethodBinding getExactMethod(final char[] selector, + final TypeBinding[] argumentTypes, final CompilationUnitScope refScope) { + + MethodBinding exactMethod = null; + + //search all linked types for exact method match + if(selector != null) { + final LinkedList typesToCheck = new LinkedList(); + + /* this set will contain every type that has already been checked + * this includes all linked types, therefore a simple contains check + * can be done to see if a given type has already been checked + * rather then having to iterate and do an expensive #isEquivalentTo check */ + final Set checkedTypes = new HashSet(); + typesToCheck.add(this); + + while(!typesToCheck.isEmpty() && exactMethod == null) { + ReferenceBinding typeToCheck = (ReferenceBinding)typesToCheck.removeFirst(); + + + /* if type to check is SourceTypeBinding then have to check all linked bindings + * else just check the ReferenceBinding directly */ + if(typeToCheck instanceof SourceTypeBinding) { + exactMethod = (MethodBinding)((SourceTypeBinding)typeToCheck).performActionOnLinkedBindings(new LinkedBindingAction() { + /** + *

+ * The located exact function match. + *

+ */ + private MethodBinding fExactFunctionMatch; + + /** + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding.LinkedBindingAction#performAction(org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding) + */ + public boolean performAction(SourceTypeBinding typeToCheckLinkedBinding) { + checkedTypes.add(typeToCheckLinkedBinding); + + /* only build fields and functions if inferred type has a function with correct name, + * and only bother checking inferred type if the fields and functions have not already been built + * + * this saves time avoiding building fields and functions when it is not needed */ + if(!SourceTypeBinding.this.fHasBuiltFieldsAndMethods && typeToCheckLinkedBinding.inferredTypeHasFunction(selector)) { + //be sure fields and methods are built + typeToCheckLinkedBinding.buildFieldsAndMethods(selector); + } + + //check self for exact function + this.fExactFunctionMatch = typeToCheckLinkedBinding.getExactMethod0(selector, argumentTypes, refScope); + + /* add super type of current linked binding to types to check if + * not already there and not already checked */ + if(this.fExactFunctionMatch == null) { + boolean alreadyGoingToCheck = false; + ReferenceBinding superBinding = typeToCheckLinkedBinding.getSuperBinding0(); + if(superBinding != null) { + Iterator typesToCheckIter = typesToCheck.iterator(); + while(typesToCheckIter.hasNext()) { + alreadyGoingToCheck = ((ReferenceBinding)typesToCheckIter.next()).isEquivalentTo(superBinding); + } + + boolean alreadyChecked = false; + if(!alreadyGoingToCheck) { + alreadyChecked = checkedTypes.contains(superBinding); + } + + if(!alreadyGoingToCheck && !alreadyChecked) { + typesToCheck.add(superBinding); + } + } + } + + //keep processing if have not yet found exact match + return this.fExactFunctionMatch == null; + } + + /** + * @return {@link MethodBinding} + * + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding.LinkedBindingAction#getFinalResult() + */ + public Object getFinalResult() { + return this.fExactFunctionMatch; + } + }); + } else { + checkedTypes.add(typeToCheck); + + exactMethod = typeToCheck.getExactMethod(selector, argumentTypes, refScope); + + /* add super type of current binding to types to check if + * not already there and not already checked */ + if(exactMethod == null) { + boolean alreadyGoingToCheck = false; + ReferenceBinding superBinding = typeToCheck.getSuperBinding(); + if(superBinding != null) { + Iterator typesToCheckIter = typesToCheck.iterator(); + while(typesToCheckIter.hasNext()) { + alreadyGoingToCheck = ((ReferenceBinding)typesToCheckIter.next()).isEquivalentTo(superBinding); + } + + boolean alreadyChecked = false; + if(!alreadyGoingToCheck) { + alreadyChecked = checkedTypes.contains(superBinding); + } + + if(!alreadyGoingToCheck && !alreadyChecked) { + typesToCheck.add(superBinding); + } + } + } + } + } + } + return exactMethod; } - // NOTE: the return type, arg & exception types of each method of a source - // type are resolved when needed - // searches up the hierarchy as long as no potential (but not exact) match - // was found. + /** + *

+ * NOTES: + *

    + *
  • the return type, arg & exception types of each method of a source + * type are resolved when needed.
  • + *
  • this method only searches this specific binding, it does not search + * any linked bindings or any super bindings
  • + *
+ *

+ * + * @param selector + * @param argumentTypes + * @param refScope + * @return + */ private MethodBinding getExactMethod0(char[] selector, TypeBinding[] argumentTypes, CompilationUnitScope refScope) { - // sender from refScope calls recordTypeReference(this) - // int argCount = argumentTypes.length; - boolean foundNothing = true; - - if ((this.tagBits & TagBits.AreMethodsComplete) != 0) { // have resolved - // all arg types - // & return type - // of the - // methods + + if(selector == null || this.methods == null || this.methods.length == 0) + return null; + + // have resolved all arg types & return type of the methods + if ((this.tagBits & TagBits.AreMethodsComplete) != 0) { long range; if ((range = ReferenceBinding.binarySearch(selector, this.methods)) >= 0) { - // nextMethod: - for (int imethod = (int) range, end = (int) (range >> 32); imethod <= end; imethod++) { - MethodBinding method = this.methods[imethod]; - foundNothing = false; // inner type lookups must know that a - // method with this name exists - // if (method.parameters.length == argCount) { - // TypeBinding[] toMatch = method.parameters; - // for (int iarg = 0; iarg < argCount; iarg++) - // if (toMatch[iarg] != argumentTypes[iarg]) - // { - // if (toMatch[iarg].id!=TypeIds.T_any && - // argumentTypes[iarg].id!=TypeIds.T_any) - // continue nextMethod; - // } - // return method; - // } + if((int) range <= (int) (range >> 32)) { + MethodBinding method = this.methods[(int) range]; + // inner type lookups must know that a method with this name exists return method; } } @@ -510,15 +1029,8 @@ public class SourceTypeBinding extends ReferenceBinding { if (resolveTypesFor(method) == null || method.returnType == null) { methods(); - return getExactMethod(selector, argumentTypes, refScope); // try - // again - // since - // the - // problem - // methods - // have - // been - // removed + // try again since the problem methods have been removed + return getExactMethod0(selector, argumentTypes, refScope); } } // check dup collisions @@ -533,56 +1045,84 @@ public class SourceTypeBinding extends ReferenceBinding { .areParametersEqual(method2); if (paramsMatch) { methods(); - return getExactMethod(selector, argumentTypes, - refScope); // try again since the problem - // methods have been removed + // try again since the problem methods have been removed + return getExactMethod0(selector, argumentTypes, refScope); } } } return this.methods[start]; - // nextMethod: for (int imethod = start; imethod <= end; - // imethod++) { - // FunctionBinding method = this.methods[imethod]; - // TypeBinding[] toMatch = method.parameters; - // if (toMatch.length == argCount) { - // for (int iarg = 0; iarg < argCount; iarg++) - // if (toMatch[iarg] != argumentTypes[iarg]) - // continue nextMethod; - // return method; - // } - // } } } - if (foundNothing) { - if (this.superclass != null && this.superclass != this) { - if (refScope != null) - refScope.recordTypeReference(this.superclass); - MethodBinding exactMethod = this.superclass.getExactMethod( - selector, argumentTypes, refScope); - if (exactMethod != null && exactMethod.isValidBinding()) - return exactMethod; - } - - } return null; } - public FieldBinding getField(char[] fieldName, boolean needResolve) { - FieldBinding field = getField0(fieldName, needResolve); - if (field == null && this.nextType != null) - field = this.nextType.getField(fieldName, needResolve); + /** + *

+ * Searches all linked types for a field with the given name. + *

+ * + *

+ * NOTE:

this does not check super types. + *

+ * + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding#getField(char[], boolean) + */ + public FieldBinding getField(final char[] fieldName, final boolean needResolve) { + FieldBinding field = null; + + //search all linked types for exact method match + if(fieldName != null) { + field = (FieldBinding)this.performActionOnLinkedBindings(new LinkedBindingAction() { + /** + *

+ * The located exact function match. + *

+ */ + private FieldBinding fFieldMatch; + + /** + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding.LinkedBindingAction#performAction(org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding) + */ + public boolean performAction(SourceTypeBinding linkedBinding) { + /* only build fields and functions if inferred type has field with correct name, + * and only bother checking inferred type if the fields and functions have not already been built + * + * this saves time avoiding building fields and functions when it is not needed */ + if(!SourceTypeBinding.this.fHasBuiltFieldsAndMethods && linkedBinding.inferredTypeHasField(fieldName)) { + //be sure fields and methods are built + linkedBinding.buildFieldsAndMethods(fieldName); + } + + //check self for exact field + this.fFieldMatch = linkedBinding.getField0(fieldName, needResolve); + + //keep processing if have not yet found exact match + return this.fFieldMatch == null; + } + + /** + * @return {@link FieldBinding} + * + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding.LinkedBindingAction#getFinalResult() + */ + public Object getFinalResult() { + return this.fFieldMatch; + } + }); + } + return field; } - public FieldBinding getFieldInHierarchy(char[] fieldName, - boolean needResolve) { + public FieldBinding getFieldInHierarchy(char[] fieldName, boolean needResolve) { SourceTypeBinding currentType = this; while (currentType != null) { FieldBinding field = currentType.getField(fieldName, needResolve); - if (field != null) + if (field != null) { return field; - currentType = (SourceTypeBinding) currentType.superclass(); + } + currentType = (SourceTypeBinding) currentType.getSuperBinding(); } return null; } @@ -590,8 +1130,9 @@ public class SourceTypeBinding extends ReferenceBinding { // NOTE: the type of a field of a source type is resolved when needed private FieldBinding getField0(char[] fieldName, boolean needResolve) { - if ((this.tagBits & TagBits.AreFieldsComplete) != 0) + if ((this.tagBits & TagBits.AreFieldsComplete) != 0) { return ReferenceBinding.binarySearch(fieldName, this.fields); + } // lazily sort fields if ((this.tagBits & TagBits.AreFieldsSorted) == 0) { @@ -601,8 +1142,7 @@ public class SourceTypeBinding extends ReferenceBinding { this.tagBits |= TagBits.AreFieldsSorted; } // always resolve anyway on source types - FieldBinding field = ReferenceBinding.binarySearch(fieldName, - this.fields); + FieldBinding field = ReferenceBinding.binarySearch(fieldName, this.fields); if (field != null) { FieldBinding result = null; try { @@ -613,17 +1153,18 @@ public class SourceTypeBinding extends ReferenceBinding { // ensure fields are consistent reqardless of the error int newSize = this.fields.length - 1; if (newSize == 0) { - this.fields = Binding.NO_FIELDS; + this.setFields(Binding.NO_FIELDS); } else { FieldBinding[] newFields = new FieldBinding[newSize]; int index = 0; for (int i = 0, length = this.fields.length; i < length; i++) { FieldBinding f = this.fields[i]; - if (f == field) + if (f == field) { continue; + } newFields[index++] = f; } - this.fields = newFields; + this.setFields(newFields); } } } @@ -631,23 +1172,96 @@ public class SourceTypeBinding extends ReferenceBinding { return null; } - public MethodBinding[] getMethods(char[] selector) { - MethodBinding[] meths = getMethods0(selector); - if (this.nextType == null) - return meths; - MethodBinding[] moreMethods = this.nextType.getMethods(selector); - MethodBinding[] combinedMethods = new MethodBinding[meths.length - + moreMethods.length]; - System.arraycopy(meths, 0, combinedMethods, 0, meths.length); - System.arraycopy(moreMethods, 0, combinedMethods, meths.length, - moreMethods.length); - - return combinedMethods; + /** + *

+ * Get all methods across all linked type bindings. + *

+ * + *

+ * NOTE:

this does not check super types. + *

+ * + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding#getMethods(char[]) + */ + public MethodBinding[] getMethods(final char[] selector) { + MethodBinding[] allFunctionMatches = Binding.NO_METHODS; + + //search all linked types for functions matching the given selector + if(selector != null) { + allFunctionMatches = (MethodBinding[])this.performActionOnLinkedBindings(new LinkedBindingAction() { + /** + *

+ * All of the functions matching a given selector found across all of the linked types. + *

+ */ + private MethodBinding[] fAllFunctionMatches = Binding.NO_METHODS; + + /** + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding.LinkedBindingAction#performAction(org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding) + */ + public boolean performAction(SourceTypeBinding linkedBinding) { + /* only build fields and functions if inferred type has field with correct name, + * and only bother checking inferred type if the fields and functions have not already been built + * + * this saves time avoiding building fields and functions when it is not needed */ + if(!SourceTypeBinding.this.fHasBuiltFieldsAndMethods && linkedBinding.inferredTypeHasFunction(selector)) { + linkedBinding.buildFieldsAndMethods(selector); + } + + //get current types functions + MethodBinding[] functionMatches = linkedBinding.getMethods0(selector); + + //combine all function matches into one array + if(this.fAllFunctionMatches == null) { + this.fAllFunctionMatches = functionMatches; + } else { + MethodBinding[] combinedFunctionMatches = new MethodBinding[this.fAllFunctionMatches.length + functionMatches.length]; + System.arraycopy(this.fAllFunctionMatches, 0, combinedFunctionMatches, 0, this.fAllFunctionMatches.length); + System.arraycopy(functionMatches, 0, combinedFunctionMatches, this.fAllFunctionMatches.length, functionMatches.length); + this.fAllFunctionMatches = combinedFunctionMatches; + } + + // always search every linked type for methods + return true; + } + + /** + * @return {@link MethodBinding}[] + * + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding.LinkedBindingAction#getFinalResult() + */ + public Object getFinalResult() { + return this.fAllFunctionMatches; + } + }); + } + + return allFunctionMatches; } - // NOTE: the return type, arg & exception types of each method of a source - // type are resolved when needed + /** + *

+ * NOTES: + *

    + *
  • the return type, arg & exception types of each method of a source + * type are resolved when needed
  • + *
  • this does not check super types
  • + *
+ *

+ * + * @param selector + * @return + */ private MethodBinding[] getMethods0(char[] selector) { + // lazily sort methods + if ((this.tagBits & TagBits.AreMethodsSorted) == 0) { + int length = this.methods.length; + if (length > 1) { + ReferenceBinding.sortMethods(this.methods, 0, length); + } + this.tagBits |= TagBits.AreMethodsSorted; + } + if ((this.tagBits & TagBits.AreMethodsComplete) != 0) { long range; if ((range = ReferenceBinding.binarySearch(selector, this.methods)) >= 0) { @@ -661,24 +1275,17 @@ public class SourceTypeBinding extends ReferenceBinding { return Binding.NO_METHODS; } } - // lazily sort methods - if ((this.tagBits & TagBits.AreMethodsSorted) == 0) { - int length = this.methods.length; - if (length > 1) - ReferenceBinding.sortMethods(this.methods, 0, length); - this.tagBits |= TagBits.AreMethodsSorted; - } + MethodBinding[] result; long range; if ((range = ReferenceBinding.binarySearch(selector, this.methods)) >= 0) { int start = (int) range, end = (int) (range >> 32); for (int i = start; i <= end; i++) { MethodBinding method = this.methods[i]; - if (resolveTypesFor(method) == null - || method.returnType == null) { + if (resolveTypesFor(method) == null || method.returnType == null) { + // try again since the problem methods have been removed methods(); - return getMethods(selector); // try again since the problem - // methods have been removed + return getMethods(selector); } } int length = end - start + 1; @@ -697,9 +1304,8 @@ public class SourceTypeBinding extends ReferenceBinding { .areParametersEqual(result[j]); if (paramsMatch) { methods(); - return getMethods(selector); // try again since the - // duplicate methods have - // been removed + // try again since the duplicate methods have been removed + return getMethods(selector); } } } @@ -707,32 +1313,87 @@ public class SourceTypeBinding extends ReferenceBinding { } /** - * Returns true if a type is identical to another one, or for generic types, - * true if compared to its raw type. + * Returns true if a type is identical to another one. */ - public boolean isEquivalentTo(TypeBinding otherType) { - - if (this == otherType) - return true; - if (otherType == null) - return false; - return false; + public boolean isEquivalentTo(final TypeBinding otherType) { + //short cut for simple case + boolean isEquivalent = this == otherType; + + if(!isEquivalent && otherType != null) { + final boolean isOtherTypeSourceType = otherType instanceof SourceTypeBinding; + + isEquivalent = ((Boolean)this.performActionOnLinkedBindings(new LinkedBindingAction() { + + private boolean fIsEquivalent = false; + + public boolean performAction(final SourceTypeBinding selfLinkedBinding) { + + /* if other type is also a source type binding have to loop + * through all its types as well + * + * else just compare current linked binding with other type */ + + this.fIsEquivalent = selfLinkedBinding == otherType; + + return !this.fIsEquivalent; + } + + public Object getFinalResult() { + return new Boolean(this.fIsEquivalent); + } + })).booleanValue(); + } + + return isEquivalent; } + /** + *

+ * Get all member types across all of the linked type bindings. + *

+ * + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding#memberTypes() + */ public ReferenceBinding[] memberTypes() { - if (this.nextType == null) - return this.memberTypes; - - ReferenceBinding[] moreTypes = this.nextType.memberTypes(); - ReferenceBinding[] combinedTypes = new ReferenceBinding[this.memberTypes.length - + moreTypes.length]; - System.arraycopy(this.memberTypes, 0, combinedTypes, 0, - this.memberTypes.length); - System.arraycopy(moreTypes, 0, combinedTypes, this.memberTypes.length, - moreTypes.length); - - return combinedTypes; - + //search all linked types for member types + ReferenceBinding[] allMemberTypes = (ReferenceBinding[])this.performActionOnLinkedBindings(new LinkedBindingAction() { + /** + *

+ * All of the member types found across all of the linked types. + *

+ */ + private ReferenceBinding[] fAllMemberTypes; + + /** + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding.LinkedBindingAction#performAction(org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding) + */ + public boolean performAction(SourceTypeBinding linkedBinding) { + //combine all methods into one array + + if(this.fAllMemberTypes == null) { + this.fAllMemberTypes = linkedBinding.memberTypes; + } else { + ReferenceBinding[] combinedMemberTypes = new ReferenceBinding[this.fAllMemberTypes.length + linkedBinding.memberTypes.length]; + System.arraycopy(this.fAllMemberTypes, 0, combinedMemberTypes, 0, this.fAllMemberTypes.length); + System.arraycopy(linkedBinding.memberTypes, 0, combinedMemberTypes, this.fAllMemberTypes.length, linkedBinding.memberTypes.length); + this.fAllMemberTypes = combinedMemberTypes; + } + + // always search every linked type for member types + return true; + } + + /** + * @return {@link ReferenceBinding}[] + * + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding.LinkedBindingAction#getFinalResult() + */ + public Object getFinalResult() { + return this.fAllMemberTypes; + } + }); + + return allMemberTypes; } public FieldBinding getUpdatedFieldBinding(FieldBinding targetField, @@ -752,302 +1413,290 @@ public class SourceTypeBinding extends ReferenceBinding { return updatedMethod; } + /** + *

+ * true if any of the linked types has have member types, false otherwise. + *

+ * + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding#hasMemberTypes() + */ public boolean hasMemberTypes() { - boolean hasMembers = this.memberTypes != null - && this.memberTypes.length > 0; - if (!hasMembers && this.nextType != null) - hasMembers = this.nextType.hasMemberTypes(); - return hasMembers; + //search all linked types for member types + Boolean hasMemberTypes = (Boolean)this.performActionOnLinkedBindings(new LinkedBindingAction() { + /** + *

+ * true if any linked type has member types, false otherwise + *

+ */ + private boolean fHasMemberTypes = false; + + /** + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding.LinkedBindingAction#performAction(org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding) + */ + public boolean performAction(SourceTypeBinding linkedBinding) { + //check if this type has member types + this.fHasMemberTypes = (linkedBinding.memberTypes != null + && linkedBinding.memberTypes.length > 0); + + //keep checking linked types if have not yet found member types + return !this.fHasMemberTypes; + } + + /** + * @return {@link Boolean} + * + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding.LinkedBindingAction#getFinalResult() + */ + public Object getFinalResult() { + return new Boolean(this.fHasMemberTypes); + } + }); + + return hasMemberTypes.booleanValue(); } - // NOTE: the return type, arg & exception types of each method of a source - // type are resolved when needed + /** + *

+ * NOTE: the return type, arg & exception types of each method of a source + * type are resolved when needed + *

+ * + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding#methods() + */ public MethodBinding[] methods() { - - if ((this.tagBits & TagBits.AreMethodsComplete) == 0) { - // lazily sort methods - if ((this.tagBits & TagBits.AreMethodsSorted) == 0) { - int length = this.methods.length; - if (length > 1) - ReferenceBinding.sortMethods(this.methods, 0, length); - this.tagBits |= TagBits.AreMethodsSorted; - } - int failed = 0; - MethodBinding[] resolvedMethods = this.methods; - try { - for (int i = 0, length = this.methods.length; i < length; i++) { - if (resolveTypesFor(this.methods[i]) == null) { - // do not alter original method array until resolution - // is over, due to reentrance (143259) - if (resolvedMethods == this.methods) { - System - .arraycopy( - this.methods, - 0, - resolvedMethods = new MethodBinding[length], - 0, length); + //gather all the functions across all the linked types + MethodBinding[] allFunctions = (MethodBinding[])this.performActionOnLinkedBindings(new LinkedBindingAction() { + /** + *

+ * All of the functions defined across all the linked types. + *

+ */ + private MethodBinding[] fAllFunctions; + + /** + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding.LinkedBindingAction#performAction(org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding) + */ + public boolean performAction(SourceTypeBinding linkedBinding) { + //be sure fields and methods are built + linkedBinding.buildFieldsAndMethods(); + + if ((linkedBinding.tagBits & TagBits.AreMethodsComplete) == 0) { + // lazily sort methods + if ((linkedBinding.tagBits & TagBits.AreMethodsSorted) == 0) { + int length = linkedBinding.methods.length; + if (length > 1) { + ReferenceBinding.sortMethods(linkedBinding.methods, 0, length); } - resolvedMethods[i] = null; // unable to resolve - // parameters - failed++; + linkedBinding.tagBits |= TagBits.AreMethodsSorted; } - } + int failed = 0; + MethodBinding[] resolvedMethods = linkedBinding.methods; + try { + for (int i = 0, length = linkedBinding.methods.length; i < length; i++) { + if (resolveTypesFor(linkedBinding.methods[i]) == null) { + /* do not alter original method array until resolution + * is over, due to reentrance (143259) */ + if (resolvedMethods == linkedBinding.methods) { + System.arraycopy(linkedBinding.methods, 0, + resolvedMethods = new MethodBinding[length], 0, length); + } + + // unable to resolve parameters + resolvedMethods[i] = null; + failed++; + } + } - // find & report collision cases - - boolean complyTo15 = (this.scope != null && this.scope - .compilerOptions().sourceLevel >= ClassFileConstants.JDK1_5); - for (int i = 0, length = this.methods.length; i < length; i++) { - MethodBinding method = resolvedMethods[i]; - if (method == null) - continue; - char[] selector = method.selector; - AbstractMethodDeclaration methodDecl = null; - nextSibling: for (int j = i + 1; j < length; j++) { - MethodBinding method2 = resolvedMethods[j]; - if (method2 == null) - continue nextSibling; - if (!CharOperation.equals(selector, method2.selector)) - break nextSibling; // methods with same selector are - // contiguous - - if (complyTo15 && method.returnType != null - && method2.returnType != null) { - // 8.4.2, for collision to be detected between m1 - // and m2: - // signature(m1) == signature(m2) i.e. same arity, - // same type parameter count, can be substituted - // signature(m1) == erasure(signature(m2)) or - // erasure(signature(m1)) == signature(m2) - TypeBinding[] params1 = method.parameters; - TypeBinding[] params2 = method2.parameters; - int pLength = params1.length; - if (pLength != params2.length) - continue nextSibling; - - MethodBinding subMethod = method2; - boolean equalParams = method - .areParametersEqual(subMethod); - if (equalParams) { - // duplicates regardless of return types - } else if (method.returnType == subMethod.returnType - && (equalParams || method - .areParametersEqual(method2))) { - // name clash for sure if not duplicates, report - // as duplicates - } else if (pLength > 0) { - // check to see if the erasure of either method - // is equal to the other - int index = pLength; - for (; --index >= 0;) { - if (params1[index] != params2[index]) - break; + // find & report collision cases + boolean complyTo15 = (linkedBinding.scope != null && + linkedBinding.scope.compilerOptions().sourceLevel >= ClassFileConstants.JDK1_5); + for (int i = 0, length = linkedBinding.methods.length; i < length; i++) { + MethodBinding method = resolvedMethods[i]; + if (method == null) { + continue; + } + char[] selector = method.selector; + AbstractMethodDeclaration methodDecl = null; + nextSibling: for (int j = i + 1; j < length; j++) { + MethodBinding method2 = resolvedMethods[j]; + if (method2 == null) { + continue nextSibling; + } + + //if its the same method skip ahead + if(method == method2) { + break nextSibling; + } + + // methods with same selector are contiguous + if (!CharOperation.equals(selector, method2.selector)) { + break nextSibling; } - if (index >= 0 && index < pLength) { - for (index = pLength; --index >= 0;) - if (params1[index] != params2[index]) - break; + + if (complyTo15 && method.returnType != null + && method2.returnType != null) { + /* 8.4.2, for collision to be detected between m1 + * and m2: + * signature(m1) == signature(m2) i.e. same arity, + * same type parameter count, can be substituted + * signature(m1) == erasure(signature(m2)) or + * erasure(signature(m1)) == signature(m2) */ + TypeBinding[] params1 = method.parameters; + TypeBinding[] params2 = method2.parameters; + int pLength = params1.length; + if (pLength != params2.length) { + continue nextSibling; + } + + MethodBinding subMethod = method2; + boolean equalParams = method .areParametersEqual(subMethod); + if (equalParams) { + // duplicates regardless of return types + } else if (method.returnType == subMethod.returnType + && (equalParams || method.areParametersEqual(method2))) { + + // name clash for sure if not duplicates, report as duplicates + } else if (pLength > 0) { + // check to see if the erasure of either method is equal to the other + int index = pLength; + for (; --index >= 0;) { + if (params1[index] != params2[index]) { + break; + } + } + if (index >= 0 && index < pLength) { + for (index = pLength; --index >= 0;) { + if (params1[index] != params2[index]) { + break; + } + } + } + if (index >= 0) { + continue nextSibling; + } + } } - if (index >= 0) + // prior to 1.5, parameter identity meant a collision case + else if (!method.areParametersEqual(method2)) { continue nextSibling; + } + + // report duplicate + if (methodDecl == null) { + // cannot be retrieved after binding is lost & may still be null if method is special + methodDecl = method.sourceMethod(); + + //ensure its a valid user defined method + if (methodDecl != null && methodDecl.hasBinding()) { + linkedBinding.scope.problemReporter().duplicateMethodInType(linkedBinding, methodDecl); + + methodDecl.setBinding(null); + /* do not alter original method array until + * resolution is over, due to reentrance (143259) */ + if (resolvedMethods == linkedBinding.methods) { + System.arraycopy(linkedBinding.methods, 0, + resolvedMethods = new MethodBinding[length], 0, length); + } + resolvedMethods[i] = null; + failed++; + } + } + AbstractMethodDeclaration method2Decl = method2.sourceMethod(); + + //ensure its a valid user defined method + if (method2Decl != null && method2Decl.hasBinding()) { + linkedBinding.scope.problemReporter().duplicateMethodInType(linkedBinding, method2Decl); + + method2Decl.setBinding(null); + /* do not alter original method array until + * resolution is over, due to reentrance (143259) */ + if (resolvedMethods == linkedBinding.methods) { + System.arraycopy(linkedBinding.methods, 0, + resolvedMethods = new MethodBinding[length], 0, length); + } + resolvedMethods[j] = null; + failed++; + } } - } else if (!method.areParametersEqual(method2)) { // prior - // to - // 1.5, - // parameter - // identity - // meant - // a - // collision - // case - continue nextSibling; - } - // report duplicate - if (methodDecl == null) { - methodDecl = method.sourceMethod(); // cannot be - // retrieved - // after binding - // is lost & may - // still be null - // if method is - // special - if (methodDecl != null - && methodDecl.binding != null) { // ensure - // its a - // valid - // user - // defined - // method - this.scope - .problemReporter() - .duplicateMethodInType(this, methodDecl); - - methodDecl.binding = null; - // do not alter original method array until - // resolution is over, due to reentrance - // (143259) - if (resolvedMethods == this.methods) { - System - .arraycopy( - this.methods, - 0, - resolvedMethods = new MethodBinding[length], - 0, length); + + //forget method with invalid return type... was kept to detect possible collisions + if (method != null && method.returnType == null && methodDecl == null) { + methodDecl = method.sourceMethod(); + if (methodDecl != null) { + methodDecl.setBinding(null); + } + /* do not alter original method array until resolution + * is over, due to reentrance (143259) */ + if (resolvedMethods == linkedBinding.methods) { + System.arraycopy(linkedBinding.methods, 0, + resolvedMethods = new MethodBinding[length], 0, length); } resolvedMethods[i] = null; failed++; } } - AbstractMethodDeclaration method2Decl = method2 - .sourceMethod(); - if (method2Decl != null && method2Decl.binding != null) { // ensure - // its - // a - // valid - // user - // defined - // method - this.scope.problemReporter().duplicateMethodInType( - this, method2Decl); - - method2Decl.binding = null; - // do not alter original method array until - // resolution is over, due to reentrance (143259) - if (resolvedMethods == this.methods) { - System - .arraycopy( - this.methods, - 0, - resolvedMethods = new MethodBinding[length], - 0, length); + } finally { + if (failed > 0) { + int newSize = resolvedMethods.length - failed; + if (newSize == 0) { + linkedBinding.setMethods(Binding.NO_METHODS); + } else { + MethodBinding[] newMethods = new MethodBinding[newSize]; + for (int i = 0, j = 0, length = resolvedMethods.length; i < length; i++) { + if (resolvedMethods[i] != null) { + newMethods[j++] = resolvedMethods[i]; + } + } + linkedBinding.setMethods(newMethods); } - resolvedMethods[j] = null; - failed++; - } - } - if (method.returnType == null && methodDecl == null) { // forget - // method - // with - // invalid - // return - // type... - // was - // kept - // to - // detect - // possible - // collisions - methodDecl = method.sourceMethod(); - if (methodDecl != null) { - methodDecl.binding = null; - } - // do not alter original method array until resolution - // is over, due to reentrance (143259) - if (resolvedMethods == this.methods) { - System - .arraycopy( - this.methods, - 0, - resolvedMethods = new MethodBinding[length], - 0, length); } - resolvedMethods[i] = null; - failed++; + + // mark functions as complete + linkedBinding.tagBits |= TagBits.AreMethodsComplete; } } - } finally { - if (failed > 0) { - int newSize = resolvedMethods.length - failed; - if (newSize == 0) { - this.methods = Binding.NO_METHODS; - } else { - MethodBinding[] newMethods = new MethodBinding[newSize]; - for (int i = 0, j = 0, length = resolvedMethods.length; i < length; i++) - if (resolvedMethods[i] != null) - newMethods[j++] = resolvedMethods[i]; - this.methods = newMethods; - } + + //combine newly found functions with already found ones + if(this.fAllFunctions == null) { + this.fAllFunctions = linkedBinding.methods; + } else { + MethodBinding[] combinedFunctions = new MethodBinding[this.fAllFunctions.length + linkedBinding.methods.length]; + System.arraycopy(this.fAllFunctions, 0, combinedFunctions, 0, this.fAllFunctions.length); + System.arraycopy(linkedBinding.methods, 0, combinedFunctions, this.fAllFunctions.length, linkedBinding.methods.length); + this.fAllFunctions = combinedFunctions; } - - // handle forward references to potential default abstract - // methods - // addDefaultAbstractMethods(); - this.tagBits |= TagBits.AreMethodsComplete; + + // always search every linked type + return true; } - } - if (this.nextType != null) { - MethodBinding[] moreMethods = this.nextType.methods(); - MethodBinding[] combinedMethods = new MethodBinding[this.methods.length - + moreMethods.length]; - System.arraycopy(this.methods, 0, combinedMethods, 0, - this.methods.length); - System.arraycopy(moreMethods, 0, combinedMethods, - this.methods.length, moreMethods.length); - - return combinedMethods; - - } else - return this.methods; - + + /** + * @return {@link MethodBinding}[] + * + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding.LinkedBindingAction#getFinalResult() + */ + public Object getFinalResult() { + return this.fAllFunctions; + } + }); + + return allFunctions; } private FieldBinding resolveTypeFor(FieldBinding field) { - if ((field.modifiers & ExtraCompilerModifiers.AccUnresolved) == 0) + if ((field.modifiers & ExtraCompilerModifiers.AccUnresolved) == 0) { return field; + } - if (isViewedAsDeprecated() && !field.isDeprecated()) + if (isViewedAsDeprecated() && !field.isDeprecated()) { field.modifiers |= ExtraCompilerModifiers.AccDeprecatedImplicitly; - if (hasRestrictedAccess()) + } + + if (hasRestrictedAccess()) { field.modifiers |= ExtraCompilerModifiers.AccRestrictedAccess; + } + return field; - // FieldDeclaration[] fieldDecls = - // this.classScope.referenceContext.fields; - // for (int f = 0, length = fieldDecls.length; f < length; f++) { - // if (fieldDecls[f].binding != field) - // continue; - // - // MethodScope initializationScope = field.isStatic() - // ? this.classScope.referenceContext.staticInitializerScope - // : this.classScope.referenceContext.initializerScope; - // FieldBinding previousField = initializationScope.initializedField; - // try { - // initializationScope.initializedField = field; - // FieldDeclaration fieldDecl = fieldDecls[f]; - // TypeBinding fieldType = - // fieldDecl.getKind() == AbstractVariableDeclaration.ENUM_CONSTANT - // ? initializationScope.environment().convertToRawType(this) // enum - // constant is implicitly of declaring enum type - // : fieldDecl.type.resolveType(initializationScope, true /* check - // bounds*/); - // field.type = fieldType; - // field.modifiers &= ~ExtraCompilerModifiers.AccUnresolved; - // if (fieldType == null) { - // fieldDecl.binding = null; - // return null; - // } - // if (fieldType == TypeBinding.VOID) { - // this.scope.problemReporter().variableTypeCannotBeVoid(fieldDecl); - // fieldDecl.binding = null; - // return null; - // } - // if (fieldType.isArrayType() && ((ArrayBinding) - // fieldType).leafComponentType == TypeBinding.VOID) { - // this.scope.problemReporter().variableTypeCannotBeVoidArray(fieldDecl); - // fieldDecl.binding = null; - // return null; - // } - // TypeBinding leafType = fieldType.leafComponentType(); - // if (leafType instanceof ReferenceBinding && - // (((ReferenceBinding)leafType).modifiers & - // ExtraCompilerModifiers.AccGenericSignature) != 0) { - // field.modifiers |= ExtraCompilerModifiers.AccGenericSignature; - // } - // } finally { - // initializationScope.initializedField = previousField; - // } - // return field; - // } - // return null; // should never reach this point } public MethodBinding resolveTypesFor(MethodBinding method) { @@ -1068,37 +1717,48 @@ public class SourceTypeBinding extends ReferenceBinding { methodDecl = method.sourceMethod(); if (methodDecl == null) return null; // method could not be resolved in previous iteration - + boolean foundArgProblem = false; Argument[] arguments = methodDecl.arguments; if (arguments != null) { int size = arguments.length; - method.parameters = Binding.NO_PARAMETERS; + method.setParameters(Binding.NO_PARAMETERS); TypeBinding[] newParameters = new TypeBinding[size]; for (int i = 0; i < size; i++) { Argument arg = arguments[i]; TypeBinding parameterType = TypeBinding.UNKNOWN; - if (arg.type != null) + if (arg.type != null) { parameterType = arg.type - .resolveType(methodDecl.scope, true /* check bounds */); - else if (arg.inferredType != null) + .resolveType(methodDecl.getScope(), true /* check bounds */); + } else if (arg.inferredType != null) { + /* if argument has an anonymous inferred type then it has not been built + * at this point, so build it before attempt to resolve it. */ + if(arg.inferredType.isAnonymous && arg.inferredType.binding == null) { + ReferenceBinding argTypeBinding = methodDecl.getScope().findType( + arg.inferredType.getName(), this.getPackage(), this.getPackage()); + if(argTypeBinding instanceof SourceTypeBinding) { + arg.inferredType.binding = (SourceTypeBinding) argTypeBinding; + } + } + parameterType = arg.inferredType.resolveType( - methodDecl.scope, arg); + methodDecl.getScope(), arg); + } if (parameterType == null) { - // foundArgProblem = true; parameterType = TypeBinding.ANY; } newParameters[i] = parameterType; - if(arg.binding == null) + if(arg.binding == null) { arg.binding = new LocalVariableBinding(arg, parameterType, arg.modifiers, true); - + } } // only assign parameters if no problems are found - if (!foundArgProblem) - method.parameters = newParameters; + if (!foundArgProblem) { + method.setParameters(newParameters); + } } boolean foundReturnTypeProblem = false; @@ -1107,29 +1767,28 @@ public class SourceTypeBinding extends ReferenceBinding { : null; if (returnType == null && !(methodDecl instanceof MethodDeclaration)) { - methodDecl.scope.problemReporter() + methodDecl.getScope().problemReporter() .missingReturnType(methodDecl); method.returnType = null; foundReturnTypeProblem = true; } else { TypeBinding methodType = (returnType != null) ? returnType - .resolveType(methodDecl.scope, true /* check bounds */) + .resolveType(methodDecl.getScope(), true /* check bounds */) : null; if (methodType == null) methodType = (methodDecl.inferredType != null) ? methodDecl.inferredType - .resolveType(methodDecl.scope, methodDecl) + .resolveType(methodDecl.getScope(), methodDecl) : TypeBinding.UNKNOWN; if (methodType == null) { foundReturnTypeProblem = true; } else { method.returnType = methodType; - TypeBinding leafType = methodType.leafComponentType(); } } } if (foundArgProblem) { - methodDecl.binding = null; - method.parameters = Binding.NO_PARAMETERS; // see 107004 + methodDecl.setBinding(null); + method.setParameters(Binding.NO_PARAMETERS); // see 107004 // nullify type parameter bindings as well as they have a // backpointer to the method binding // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=81134) @@ -1144,52 +1803,124 @@ public class SourceTypeBinding extends ReferenceBinding { } public void setFields(FieldBinding[] fields) { - // if (this.nextType!=null) - // throw new UnimplementedException("should not get here"); //$NON-NLS-1$ - + this.tagBits &= ~TagBits.AreFieldsSorted; this.fields = fields; } public void setMethods(MethodBinding[] methods) { - // if (this.nextType!=null) - // throw new UnimplementedException("should not get here"); //$NON-NLS-1$ + this.tagBits &= ~TagBits.AreMethodsSorted; this.methods = methods; } public int sourceEnd() { - if (this.classScope.referenceContext != null) + if (this.classScope.referenceContext != null) { return this.classScope.referenceContext.sourceEnd; - else + } else { return this.classScope.inferredType.sourceEnd; } + } public int sourceStart() { - if (this.classScope.referenceContext != null) + if (this.classScope.referenceContext != null) { return this.classScope.referenceContext.sourceStart; - else + } else { return this.classScope.inferredType.sourceStart; } + } - public ReferenceBinding superclass() { - if (this.nextType == null) { - //fix for https://bugs.eclipse.org/bugs/show_bug.cgi?id=282372 - if(this == this.superclass) - return null; - return this.superclass; - } - if (this.superclass != null - && this.superclass.id != TypeIds.T_JavaLangObject) { - //fix for https://bugs.eclipse.org/bugs/show_bug.cgi?id=282372 - if(this == this.superclass) - return null; - return this.superclass; - } - return this.nextType.superclass(); - + /** + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding#superclass() + */ + /** + *

+ * Will return the super binding set on this binding or if this bindings + * super biding is null or Object will return the super + * binding set on the first linked binding who's super binding is not null + * and not Object + *

+ * + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding#getSuperBinding() + * + * @see #getSuperBinding0() + */ + public ReferenceBinding getSuperBinding() { + //search all linked type bindings for the first one with a super type that is not Object + ReferenceBinding superBinding = (ReferenceBinding)this.performActionOnLinkedBindings(new LinkedBindingAction() { + /** + *

+ * First super type found when searching all linked type bindings. + *

+ */ + private ReferenceBinding fFoundSuperBinding = null; + + /** + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding.LinkedBindingAction#performAction(org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding) + */ + public boolean performAction(SourceTypeBinding linkedBinding) { + ReferenceBinding linkedSuperBinding = linkedBinding.getSuperBinding0(); + + /* Be sure that the super type of a linked binding is not the same as this type + * This can legitimately happen when using a pattern like: + * + * define("foo.BarImpl", "foo.Bar", {}): + * foo.Bar = foo.BarImpl; + * + * A best effort is made to avoid this at the infer level by setting it only as the + * super type and not as a synonym, but still best to have this check here */ + if(linkedSuperBinding != null && linkedSuperBinding != SourceTypeBinding.this && + (this.fFoundSuperBinding == null || (linkedSuperBinding.id != TypeIds.T_JavaLangObject))) { + + this.fFoundSuperBinding = linkedSuperBinding; + } + + //keep searching if super type is null or Object + return this.fFoundSuperBinding == null || this.fFoundSuperBinding.id == TypeIds.T_JavaLangObject; + } + + /** + * @return {@link ReferenceBinding} + * + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding.LinkedBindingAction#getFinalResult() + */ + public Object getFinalResult() { + return this.fFoundSuperBinding; + } + }); + + return superBinding; + } + + /** + * @return {@link SourceTypeBinding} set as the super binding for this + * binding only. Unlike {@link #getSuperBinding()} this function + * will not search the linked bindings. + * + * @see #getSuperBinding() + */ + public ReferenceBinding getSuperBinding0() { + return this.fSuperBinding; + } + + /** + *

+ * Sets the super binding for this specific binding. This will overwrite + * any currently set super binding for this binding. + *

+ * + *

+ * WARNING: A linked binding may have a different super binding. + *

+ * + * @param newSuperBinding + * {@link SourceTypeBinding} to set as the super binding for + * this binding, will overwrite any currently set super binding + */ + public void setSuperBinding(ReferenceBinding newSuperBinding) { + this.fSuperBinding = newSuperBinding; } public String toString() { - StringBuffer buffer = new StringBuffer(30); + final StringBuffer buffer = new StringBuffer(30); buffer.append("(id="); //$NON-NLS-1$ if (this.id == TypeIds.NoId) buffer.append("NoId"); //$NON-NLS-1$ @@ -1213,7 +1944,7 @@ public class SourceTypeBinding extends ReferenceBinding { .toString(this.compoundName) : "UNNAMED TYPE"); //$NON-NLS-1$ buffer.append("\n\textends "); //$NON-NLS-1$ - buffer.append((this.superclass != null) ? this.superclass.debugName() + buffer.append((this.fSuperBinding != null) ? this.fSuperBinding.debugName() : "NULL TYPE"); //$NON-NLS-1$ if (enclosingType() != null) { @@ -1256,33 +1987,92 @@ public class SourceTypeBinding extends ReferenceBinding { } else { buffer.append("NULL MEMBER TYPES"); //$NON-NLS-1$ } + + //if debugging enabled then print out all the linked type names and their hashes + if(DEBUG) { + buffer.append("\n\nLINKED TYPE NAMES:\n"); //$NON-NLS-1$ + this.performActionOnLinkedBindings(new LinkedBindingAction() { + public boolean performAction(SourceTypeBinding linkedBinding) { + buffer.append(linkedBinding.qualifiedSourceName0()); + buffer.append(" -> "); //$NON-NLS-1$ + buffer.append(Integer.toHexString(System.identityHashCode(linkedBinding))); + buffer.append("\n"); //$NON-NLS-1$ + return true; + } + }); + } buffer.append("\n\n"); //$NON-NLS-1$ return buffer.toString(); } - void verifyMethods(MethodVerifier verifier) { - //verifier.verify(this); - } - public AbstractMethodDeclaration sourceMethod(MethodBinding binding) { - if (this.classScope == null) + if (this.classScope == null) { return null; + } + InferredType inferredType = this.classScope.inferredType; InferredMethod inferredMethod = inferredType.findMethod( binding.selector, null); - if (inferredMethod != null) - return (AbstractMethodDeclaration) inferredMethod - .getFunctionDeclaration(); + if (inferredMethod != null) { + return (AbstractMethodDeclaration) inferredMethod.getFunctionDeclaration(); + } return null; } public void addMethod(MethodBinding binding) { + this.tagBits &= ~TagBits.AreMethodsSorted; + int length = this.methods.length; System.arraycopy(this.methods, 0, this.methods = new MethodBinding[length + 1], 0, length); this.methods[length] = binding; - + } + + /** + * @param binding {@link FieldBinding} to add to this type binding + */ + public void addField(FieldBinding binding) { + this.tagBits &= ~TagBits.AreFieldsSorted; + + int length = this.fields.length; + System.arraycopy(this.fields, 0, + this.fields = new FieldBinding[length + 1], 0, length); + this.fields[length] = binding; + } + + /** + *

+ * Adds new function bindings to this type binding. + *

+ * + * @param newFunctionBindings + * {@link MethodBinding}s to add to this type binding + */ + private void addMethods(MethodBinding[] newFunctionBindings) { + this.tagBits &= ~TagBits.AreMethodsSorted; + + int length = this.methods.length; + System.arraycopy(this.methods, 0, + this.methods = new MethodBinding[length + newFunctionBindings.length], 0, length); + System.arraycopy(newFunctionBindings, 0, this.methods, length, newFunctionBindings.length); + } + + /** + *

+ * Adds new field bindings to this type binding. + *

+ * + * @param newFieldBindings + * {@link FieldBinding}s to add to this type binding + */ + private void addFields(FieldBinding[] newFieldBindings) { + this.tagBits &= ~TagBits.AreFieldsSorted; + + int length = this.fields.length; + System.arraycopy(this.fields, 0, + this.fields = new FieldBinding[length + newFieldBindings.length], 0, length); + System.arraycopy(newFieldBindings, 0, this.fields, length, newFieldBindings.length); } public void cleanup() { @@ -1290,38 +2080,113 @@ public class SourceTypeBinding extends ReferenceBinding { this.classScope = null; } - public boolean contains(ReferenceBinding binding) { - if (binding == this) - return true; - if (this.nextType != null) - return this.nextType.contains(binding); - return false; + /** + *

+ * Determines if a given binding is linked to this binding. + *

+ * + * @param searchBinding + * check if this {@link ReferenceBinding} is linked to this binding + * + * @return true if any linked types are the given binding, + * false otherwise + */ + boolean isLinkedType(final ReferenceBinding searchBinding) { + // searches all linked bindings to see if any of them are the given search binding + Boolean isBindingLinked = (Boolean)this.performActionOnLinkedBindings(new LinkedBindingAction() { + + /** + *

+ * true if any linked types are the given binding, false otherwise + *

+ */ + private boolean fIsBindingLinked = false; + + /** + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding.LinkedBindingAction#performAction(org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding) + */ + public boolean performAction(SourceTypeBinding linkedBinding) { + this.fIsBindingLinked = searchBinding == linkedBinding; + + // keep searching if not found linked the given binding to be linked + return !this.fIsBindingLinked; + } + + /** + * @return {@link Boolean} + * + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding.LinkedBindingAction#getFinalResult() + */ + public Object getFinalResult() { + return new Boolean(this.fIsBindingLinked); + } + }); + + return isBindingLinked.booleanValue(); } - public void addNextType(SourceTypeBinding type) { - SourceTypeBinding binding = this; + /** + *

+ * Adds the given new linked type and all of its linked types to this + * types circle of linked types. If the given new linked type is already + * linked to this type then no operation is taken. + *

+ * + *

+ * EX:
+ * this type: A0 -> A1 -> A2 -> A3 -> A0
+ * new linked type: B0 -> B1 -> B0
+ *
+ * combined after this operation:
+ * A0 -> B0 -> B1 -> A1 -> A2 -> A3 -> A0 + *

+ * + * @param newLinkedBinding + * {@link SourceTypeBinding} to link to this one + */ + public void addLinkedBinding(final SourceTypeBinding newLinkedBinding) { + // determine if the new linked type is a duplicate of a current linked type + boolean isDuplicate = this.isLinkedType(newLinkedBinding); - // attempt to remove duplicates - boolean isDuplicate = checkIfDuplicateType(binding, type); - - while (!isDuplicate && binding.nextType != null) { - binding = binding.nextType; - if(binding != null && checkIfDuplicateType(binding, type)) - isDuplicate = true; + /* if linked type is not a duplicate then combine this types linked types + * circle with the new types circle into one giant circle + * + * EX: + * + * this type: A0 -> A1 -> A2 -> A3 -> A0 + * new linked type: B0 -> B1 -> B0 + * + * combined after this operation: + * A0 -> B0 -> B1 -> A1 -> A2 -> A3 -> A0 + */ + if(!isDuplicate) { + SourceTypeBinding currNextType = this.fNextType; + this.fNextType = newLinkedBinding; + + //search for the end of the linked type circle, aka the type that links back to the new linked type + SourceTypeBinding newTypesLastNextType = newLinkedBinding; + while(newTypesLastNextType.fNextType != newLinkedBinding) { + newTypesLastNextType = newTypesLastNextType.fNextType; + } + + /* assign what was this types next type as the next type for + * the last next type in the new linked type's next type circle + * + * clear as mud, see comment up a few lines for example of what is going on + */ + newTypesLastNextType.fNextType = currNextType; } - if(!isDuplicate) - binding.nextType = type; } - public boolean checkIfDuplicateType(SourceTypeBinding binding1, SourceTypeBinding binding2) { + public static boolean checkIfDuplicateType(SourceTypeBinding binding1, SourceTypeBinding binding2) { InferredType type2 = binding2.classScope.inferredType; if(binding1.classScope == null) { - if(binding1.superclass == null && type2.superClass != null) + if(binding1.fSuperBinding == null && type2.getSuperType() != null) return false; - if(binding1.superclass != null && type2.superClass == null) + if(binding1.fSuperBinding != null && type2.getSuperType() == null) return false; - if(binding1.superclass != null && type2.superClass != null && - !CharOperation.equals(binding1.superclass.sourceName, type2.superClass.getName())) + if(binding1.fSuperBinding != null && type2.getSuperType() != null && + !CharOperation.equals(binding1.fSuperBinding.sourceName, type2.getSuperType().getName())) return false; if(binding1.fields.length != type2.attributes.length) return false; @@ -1334,12 +2199,12 @@ public class SourceTypeBinding extends ReferenceBinding { } else { InferredType type1 = binding1.classScope.inferredType; - if(type1.superClass == null && type2.superClass != null) + if(type1.getSuperType() == null && type2.getSuperType() != null) return false; - if(type1.superClass != null && type2.superClass == null) + if(type1.getSuperType() != null && type2.getSuperType() == null) return false; - if(type1.superClass != null && type2.superClass != null && - !CharOperation.equals(type1.superClass.getName(), type2.superClass.getName())) + if(type1.getSuperType() != null && type2.getSuperType() != null && + !CharOperation.equals(type1.getSuperType().getName(), type2.getSuperType().getName())) return false; if(type1.attributes.length != type2.attributes.length) return false; @@ -1350,12 +2215,12 @@ public class SourceTypeBinding extends ReferenceBinding { if(type1.methods != null && type2.methods != null && type1.methods.size() != type2.methods.size()) return false; - StringBuffer checkSumString1 = new StringBuffer(); //$NON-NLS-1$ - StringBuffer checkSumString2 = new StringBuffer(); //$NON-NLS-1$ + StringBuffer checkSumString1 = new StringBuffer(); + StringBuffer checkSumString2 = new StringBuffer(); for(int i = 0; i < type1.attributes.length; i++) { - checkSumString1.append((type1.attributes[i] == null ? "" : new String(type1.attributes[i].name))); - checkSumString2.append((type2.attributes[i] == null ? "" : new String(type2.attributes[i].name))); + checkSumString1.append((type1.attributes[i] == null ? "" : new String(type1.attributes[i].name))); //$NON-NLS-1$ + checkSumString2.append((type2.attributes[i] == null ? "" : new String(type2.attributes[i].name))); //$NON-NLS-1$ } checksumCalculator.reset(); checksumCalculator.update(checkSumString1.toString().getBytes()); @@ -1388,31 +2253,310 @@ public class SourceTypeBinding extends ReferenceBinding { } public TypeBinding reconcileAnonymous(TypeBinding other) { - if (!(other instanceof SourceTypeBinding)) + if (!(other instanceof SourceTypeBinding)) { return null; + } SourceTypeBinding otherBinding = (SourceTypeBinding) other; - if (!otherBinding.isAnonymousType()) + if (!otherBinding.isAnonymousType()) { return null; + } + if (otherBinding.methods != null) { for (int i = 0; i < otherBinding.methods.length; i++) { MethodBinding methodBinding = otherBinding.methods[i]; MethodBinding exactMethod = this.getExactMethod( methodBinding.selector, methodBinding.parameters, null); - if (exactMethod == null) + if (exactMethod == null) { return null; } } + } if (otherBinding.fields != null) { for (int i = 0; i < otherBinding.fields.length; i++) { FieldBinding fieldBinding = otherBinding.fields[i]; FieldBinding myField = this.getFieldInHierarchy( fieldBinding.name, true); - if (myField == null) + if (myField == null) { return null; } } + } return this; } -} + + /** + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding#readableName() + */ + public char[] readableName() { + return this.qualifiedSourceName(); + } + + /** + *

+ * Will return the qualified source name from the first linked binding + * that is not anonymous, or if no linked bindings are not anonymous then + * returns the qualified source name for this binding. + *

+ * + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding#qualifiedSourceName() + */ + public char[] qualifiedSourceName() { + char[] qualifiedSourceName = (char[])performActionOnLinkedBindings(new LinkedBindingAction() { + + private char[] fQualifiedSourceName = null; + + public boolean performAction(SourceTypeBinding linkedBinding) { + if(!linkedBinding.isAnonymousType()) { + this.fQualifiedSourceName = linkedBinding.qualifiedSourceName0(); + } + + return this.fQualifiedSourceName == null; + } + + /** + * @return char[] + * + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding.LinkedBindingAction#getFinalResult() + */ + public Object getFinalResult() { + return this.fQualifiedSourceName; + } + }); + + if(qualifiedSourceName == null) { + qualifiedSourceName = this.qualifiedSourceName0(); + } + + return qualifiedSourceName; + } + + /** + * @return qualified source name for this binding + */ + private char[] qualifiedSourceName0() { + return super.qualifiedSourceName(); + } + + /** + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding#isSuperclassOf(org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding) + */ + public boolean isSuperclassOf(ReferenceBinding otherType) { + boolean isSuperTypeOf = false; + + if(otherType instanceof SourceTypeBinding) { + //NOTE: this is a breadth first search of the super types + + /* compare this type against the super types of the types in this list + * + * use the list for quickly iterating over and the set for preventing + * duplicates. */ + final LinkedList compareAgainstSupersOfList = new LinkedList(); + compareAgainstSupersOfList.add(otherType); + final Set compareAgainstSupersOfSet = new HashSet(); + compareAgainstSupersOfSet.add(otherType); + + //prevent searching the super of the same types more then once + final Set alreadyComparedAgainstSupersOf = new HashSet(); + + //while there are types to compare this type against their super types with keep going + while(!compareAgainstSupersOfList.isEmpty() && !isSuperTypeOf) { + SourceTypeBinding checkSupersOf = (SourceTypeBinding)compareAgainstSupersOfList.removeFirst(); + compareAgainstSupersOfSet.remove(checkSupersOf); + alreadyComparedAgainstSupersOf.add(checkSupersOf); + + isSuperTypeOf = ((Boolean)checkSupersOf.performActionOnLinkedBindings(new LinkedBindingAction() { + + private boolean fIsSuperTypeOf = false; + + /** + * + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding.LinkedBindingAction#performAction(org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding) + */ + public boolean performAction(SourceTypeBinding otherLinkedBinding) { + ReferenceBinding otherLinkedSuperBinding = otherLinkedBinding.getSuperBinding0(); + + if(otherLinkedSuperBinding != null && + !alreadyComparedAgainstSupersOf.contains(otherLinkedSuperBinding)) { + + fIsSuperTypeOf = otherLinkedSuperBinding.isEquivalentTo(SourceTypeBinding.this); + + //prevent searching the super of the same types more then once + if(!compareAgainstSupersOfSet.contains(otherLinkedSuperBinding)) { + compareAgainstSupersOfList.add(otherLinkedSuperBinding); + compareAgainstSupersOfSet.add(otherLinkedSuperBinding); + } + } + + return !fIsSuperTypeOf; + } + + /** + * @return {@link ReferenceBinding} + * + * @see org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding.LinkedBindingAction#getFinalResult() + */ + public Object getFinalResult() { + return new Boolean(this.fIsSuperTypeOf); + } + })).booleanValue(); + } + + + } else { + isSuperTypeOf = super.isSuperclassOf(otherType); + } + + return isSuperTypeOf; + } + + /** + *

+ * Determine if this binding's inferred type has a function with the given + * name + *

+ * + * @param functionName + * determine if this binding's inferred type has a function + * with this name + * + * @return trueif this binding's inferred type has a function + * with the given name, false otherwise + */ + private boolean inferredTypeHasFunction(char[] functionName) { + InferredType currentType = this.classScope != null ? this.classScope.inferredType : null; + if(currentType != null) { + if(currentType.methods != null && currentType.methods.size() > 0) { + for(int i = 0; i < currentType.methods.size(); i++) { + InferredMethod method = (InferredMethod) currentType.methods.get(i); + if(method != null && CharOperation.equals(method.name, functionName)) { + return true; + } + } + } + } + return false; + } + + /** + *

+ * Determine if this binding's inferred type has a field with the given + * name + *

+ * + * @param fieldName + * determine if this binding's inferred type has a field with + * this name + * + * @return trueif this binding's inferred type has a field + * with the given name, false otherwise + */ + private boolean inferredTypeHasField(char[] fieldName) { + InferredType currentType = this.classScope != null ? this.classScope.inferredType : null; + if(currentType != null) { + InferredAttribute[] attributes = currentType.attributes; + if(attributes != null && currentType.numberAttributes > 0) { + for(int i = 0; i < currentType.numberAttributes; i++) { + if(attributes[i] != null && CharOperation.equals(attributes[i].name, fieldName)) { + return true; + } + } + } + } + return false; + } + + /** + * @param binding + * determine if this binding is a function binding + * + * @return true if the given {@link TypeBinding} is a + * function binding, false otherwise + */ + private static boolean isFunctionType(TypeBinding binding) { + return binding.isFunctionType() || + binding instanceof FunctionTypeBinding || + CharOperation.equals(binding.sourceName(), InferredType.FUNCTION_NAME); + } + + /** + *

+ * Performs the given action on all of the {@link SourceTypeBinding}s + * linked to this one, including this one, unless the loop is cut short by + * a false result from + * {@link LinkedBindingAction#performAction(SourceTypeBinding)}. + *

+ * + *

+ * Whenever an action needs to be performed on all of the linked bindings + * this is the method that should be used. + *

+ * + * @param action + * {@link LinkedBindingAction} to perform on this binding and + * all of its linked bindings or until + * {@link LinkedBindingAction#performAction(SourceTypeBinding)} + * returns false + * + * @return the result of a call to + * {@link LinkedBindingAction#getFinalResult()} on the given action + * after running + * {@link LinkedBindingAction#performAction(SourceTypeBinding)} on + * each of the linked bindings or until + * {@link LinkedBindingAction#performAction(SourceTypeBinding)} + * returned false + * + * @see LinkedBindingAction + */ + Object performActionOnLinkedBindings(LinkedBindingAction action) { + SourceTypeBinding currBinding = this; + + /* perform the given action each linked type stopping either + * when looped back to the beginning or #performAction returns false */ + boolean keepProcessing = true; + do { + keepProcessing = action.performAction(currBinding); + currBinding = currBinding.fNextType; + } while(currBinding != this && keepProcessing); + + return action.getFinalResult(); + } + + /** + *

+ * An action to perform on a set of linked {@link SourceTypeBinding}s + *

+ * + * @see #performAction(SourceTypeBinding) + */ + static abstract class LinkedBindingAction { + /** + *

+ * Performs an action on the given {@link SourceTypeBinding}. + *

+ * + * @param linkedBinding + * {@link SourceTypeBinding} to perform the action on + * + * @return true if the next linked binding should be + * passed to this function, false if the loop + * should stop prematurely + */ + public abstract boolean performAction(SourceTypeBinding linkedBinding); + + /** + *

+ * Default implementation is to return null assuming no + * accumulative result was gathered. + *

+ * + * @return final result gathered after calling + * {@link #performAction(SourceTypeBinding)} on the linked + * bindings, default result is null + */ + public Object getFinalResult() { + return null; + } + } +} \ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/TagBits.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/TagBits.java index 12362207..0ddeb7a9 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/TagBits.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/TagBits.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/TypeBinding.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/TypeBinding.java index 43cb7136..0a121285 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/TypeBinding.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/lookup/TypeBinding.java @@ -164,7 +164,7 @@ abstract public class TypeBinding extends Binding { // iterate superclass to avoid recording interfaces if searched // supertype is class if (erasureIsClass) { - while ((currentType = currentType.superclass()) != null) { + while ((currentType = currentType.getSuperBinding()) != null) { if (currentType.id == wellKnownErasureID || (currentType.id == wellKnownErasureID)) return currentType; @@ -223,10 +223,12 @@ abstract public class TypeBinding extends Binding { return this; ReferenceBinding currentType = (ReferenceBinding) this; + ReferenceBinding firstSuper = null; - while ((currentType = currentType.superclass()) != null) { + while ( ((currentType = currentType.getSuperBinding()) != null) && (currentType != firstSuper)) { if (currentType == otherType || (currentType == otherType)) return currentType; + if ( firstSuper == null ) firstSuper = currentType; } return null; } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/messages.properties b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/messages.properties index b399c71f..24771f41 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/messages.properties +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/messages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2008 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,9 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR + ### Eclipse JavaScript Core Compiler messages. ### compilation diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/AbstractCommentParser.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/AbstractCommentParser.java index 32ff909d..ab4db6b1 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/AbstractCommentParser.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/AbstractCommentParser.java @@ -945,8 +945,13 @@ public abstract class AbstractCommentParser implements JavadocTagConstants { primitiveToken = token; consumeToken(); break nextToken; - - default: + case TerminalTokens.TokenNameLESS: + //if '<' token is found after dot (example: identifier.) + if ((iToken & 1) == 0 && parserKind == COMPLETION_PARSER) { + break nextToken; + } + //$FALL-THROUGH$ + default: if (iToken == 0) { if (this.identifierPtr >= 0) { this.lastIdentifierEndPosition = (int) this.identifierPositionStack[this.identifierPtr]; diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/JavadocParser.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/JavadocParser.java index 77383623..b328b4d1 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/JavadocParser.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/JavadocParser.java @@ -742,8 +742,6 @@ public class JavadocParser extends AbstractCommentParser { private boolean parseExtends() throws InvalidInputException { this.extendsType=(TypeReference)parseQualifiedName(true); - if (extendsType != null) - this.isConstructor = true; return this.extendsType!=null; } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/Parser.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/Parser.java index 4f401466..a615d7fc 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/Parser.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/parser/Parser.java @@ -1,7102 +1,7125 @@ -/******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Etienne Pfister bug 224333 - *******************************************************************************/ -package org.eclipse.wst.jsdt.internal.compiler.parser; - -import java.io.BufferedInputStream; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.MissingResourceException; -import java.util.ResourceBundle; -import java.util.Set; - -import org.eclipse.wst.jsdt.core.ast.IDoStatement; -import org.eclipse.wst.jsdt.core.compiler.CharOperation; -import org.eclipse.wst.jsdt.core.compiler.InvalidInputException; -import org.eclipse.wst.jsdt.core.infer.IInferEngine; -import org.eclipse.wst.jsdt.core.infer.InferOptions; -import org.eclipse.wst.jsdt.core.infer.InferrenceManager; -import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor; -import org.eclipse.wst.jsdt.internal.compiler.CompilationResult; -import org.eclipse.wst.jsdt.internal.compiler.ast.AND_AND_Expression; -import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode; -import org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration; -import org.eclipse.wst.jsdt.internal.compiler.ast.AbstractVariableDeclaration; -import org.eclipse.wst.jsdt.internal.compiler.ast.AllocationExpression; -import org.eclipse.wst.jsdt.internal.compiler.ast.Argument; -import org.eclipse.wst.jsdt.internal.compiler.ast.ArrayInitializer; -import org.eclipse.wst.jsdt.internal.compiler.ast.ArrayQualifiedTypeReference; -import org.eclipse.wst.jsdt.internal.compiler.ast.ArrayReference; -import org.eclipse.wst.jsdt.internal.compiler.ast.ArrayTypeReference; -import org.eclipse.wst.jsdt.internal.compiler.ast.Assignment; -import org.eclipse.wst.jsdt.internal.compiler.ast.BinaryExpression; -import org.eclipse.wst.jsdt.internal.compiler.ast.Block; -import org.eclipse.wst.jsdt.internal.compiler.ast.BreakStatement; -import org.eclipse.wst.jsdt.internal.compiler.ast.CaseStatement; -import org.eclipse.wst.jsdt.internal.compiler.ast.CombinedBinaryExpression; -import org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration; -import org.eclipse.wst.jsdt.internal.compiler.ast.CompoundAssignment; -import org.eclipse.wst.jsdt.internal.compiler.ast.ConditionalExpression; -import org.eclipse.wst.jsdt.internal.compiler.ast.ConstructorDeclaration; -import org.eclipse.wst.jsdt.internal.compiler.ast.ContinueStatement; -import org.eclipse.wst.jsdt.internal.compiler.ast.DebuggerStatement; -import org.eclipse.wst.jsdt.internal.compiler.ast.DoStatement; -import org.eclipse.wst.jsdt.internal.compiler.ast.DoubleLiteral; -import org.eclipse.wst.jsdt.internal.compiler.ast.EmptyExpression; -import org.eclipse.wst.jsdt.internal.compiler.ast.EmptyStatement; -import org.eclipse.wst.jsdt.internal.compiler.ast.EqualExpression; -import org.eclipse.wst.jsdt.internal.compiler.ast.ExplicitConstructorCall; -import org.eclipse.wst.jsdt.internal.compiler.ast.Expression; -import org.eclipse.wst.jsdt.internal.compiler.ast.FalseLiteral; -import org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration; -import org.eclipse.wst.jsdt.internal.compiler.ast.FieldReference; -import org.eclipse.wst.jsdt.internal.compiler.ast.ForInStatement; -import org.eclipse.wst.jsdt.internal.compiler.ast.ForStatement; -import org.eclipse.wst.jsdt.internal.compiler.ast.FunctionExpression; -import org.eclipse.wst.jsdt.internal.compiler.ast.IfStatement; -import org.eclipse.wst.jsdt.internal.compiler.ast.ImportReference; -import org.eclipse.wst.jsdt.internal.compiler.ast.Initializer; -import org.eclipse.wst.jsdt.internal.compiler.ast.IntLiteral; -import org.eclipse.wst.jsdt.internal.compiler.ast.IntLiteralMinValue; -import org.eclipse.wst.jsdt.internal.compiler.ast.Javadoc; -import org.eclipse.wst.jsdt.internal.compiler.ast.LabeledStatement; -import org.eclipse.wst.jsdt.internal.compiler.ast.ListExpression; -import org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration; -import org.eclipse.wst.jsdt.internal.compiler.ast.MessageSend; -import org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration; -import org.eclipse.wst.jsdt.internal.compiler.ast.NameReference; -import org.eclipse.wst.jsdt.internal.compiler.ast.NullLiteral; -import org.eclipse.wst.jsdt.internal.compiler.ast.OR_OR_Expression; -import org.eclipse.wst.jsdt.internal.compiler.ast.ObjectGetterSetterField; -import org.eclipse.wst.jsdt.internal.compiler.ast.ObjectLiteral; -import org.eclipse.wst.jsdt.internal.compiler.ast.ObjectLiteralField; -import org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds; -import org.eclipse.wst.jsdt.internal.compiler.ast.PostfixExpression; -import org.eclipse.wst.jsdt.internal.compiler.ast.PrefixExpression; -import org.eclipse.wst.jsdt.internal.compiler.ast.ProgramElement; -import org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedNameReference; -import org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedTypeReference; -import org.eclipse.wst.jsdt.internal.compiler.ast.Reference; -import org.eclipse.wst.jsdt.internal.compiler.ast.RegExLiteral; -import org.eclipse.wst.jsdt.internal.compiler.ast.ReturnStatement; -import org.eclipse.wst.jsdt.internal.compiler.ast.SingleNameReference; -import org.eclipse.wst.jsdt.internal.compiler.ast.SingleTypeReference; -import org.eclipse.wst.jsdt.internal.compiler.ast.Statement; -import org.eclipse.wst.jsdt.internal.compiler.ast.StringLiteral; -import org.eclipse.wst.jsdt.internal.compiler.ast.SuperReference; -import org.eclipse.wst.jsdt.internal.compiler.ast.SwitchStatement; -import org.eclipse.wst.jsdt.internal.compiler.ast.ThisReference; -import org.eclipse.wst.jsdt.internal.compiler.ast.ThrowStatement; -import org.eclipse.wst.jsdt.internal.compiler.ast.TrueLiteral; -import org.eclipse.wst.jsdt.internal.compiler.ast.TryStatement; -import org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration; -import org.eclipse.wst.jsdt.internal.compiler.ast.TypeReference; -import org.eclipse.wst.jsdt.internal.compiler.ast.UnaryExpression; -import org.eclipse.wst.jsdt.internal.compiler.ast.UndefinedLiteral; -import org.eclipse.wst.jsdt.internal.compiler.ast.WhileStatement; -import org.eclipse.wst.jsdt.internal.compiler.ast.WithStatement; -import org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants; -import org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit; -import org.eclipse.wst.jsdt.internal.compiler.impl.CompilerOptions; -import org.eclipse.wst.jsdt.internal.compiler.impl.ReferenceContext; -import org.eclipse.wst.jsdt.internal.compiler.lookup.Binding; -import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope; -import org.eclipse.wst.jsdt.internal.compiler.lookup.ClassScope; -import org.eclipse.wst.jsdt.internal.compiler.lookup.ExtraCompilerModifiers; -import org.eclipse.wst.jsdt.internal.compiler.lookup.MethodScope; -import org.eclipse.wst.jsdt.internal.compiler.lookup.Scope; -import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeConstants; -import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeIds; -import org.eclipse.wst.jsdt.internal.compiler.parser.diagnose.DiagnoseParser; -import org.eclipse.wst.jsdt.internal.compiler.problem.AbortCompilation; -import org.eclipse.wst.jsdt.internal.compiler.problem.AbortCompilationUnit; -import org.eclipse.wst.jsdt.internal.compiler.problem.ProblemReporter; -import org.eclipse.wst.jsdt.internal.compiler.problem.ProblemSeverities; -import org.eclipse.wst.jsdt.internal.compiler.util.Messages; -import org.eclipse.wst.jsdt.internal.compiler.util.Util; - -public class Parser implements ParserBasicInformation, TerminalTokens, OperatorIds, TypeIds { - - public static final boolean DO_DIET_PARSE=false; - - protected static final int THIS_CALL = ExplicitConstructorCall.This; - - public static char asb[] = null; - public static char asr[] = null; - //ast stack - protected final static int AstStackIncrement = 100; - public static char base_action[] = null; - public static final int BracketKinds = 3; - - public static short check_table[] = null; - public static final int CurlyBracket = 2; - private static final boolean DEBUG = false; - private static final boolean DEBUG_AUTOMATON = false; - private static final String EOF_TOKEN = "$eof" ; //$NON-NLS-1$ - private static final String ERROR_TOKEN = "$error" ; //$NON-NLS-1$ - //expression stack - protected final static int ExpressionStackIncrement = 100; - - protected final static int GenericsStackIncrement = 10; - - private final static String FILEPREFIX = "parser"; //$NON-NLS-1$ - public static char in_symb[] = null; - private static final String INVALID_CHARACTER = "Invalid Character" ; //$NON-NLS-1$ - public static char lhs[] = null; - - public static String name[] = null; - public static char nasb[] = null; - public static char nasr[] = null; - public static char non_terminal_index[] = null; - private final static String READABLE_NAMES_FILE = "readableNames"; //$NON-NLS-1$ - private final static String READABLE_NAMES_FILE_NAME = - "org.eclipse.wst.jsdt.internal.compiler.parser." + READABLE_NAMES_FILE; //$NON-NLS-1$ - public static String readableName[] = null; - - public static byte rhs[] = null; - - public static int[] reverse_index = null; - public static char[] recovery_templates_index = null; - public static char[] recovery_templates = null; - public static char[] statements_recovery_filter = null; - public static byte[] state_flags = null; - - public static long rules_compliance[] = null; - - public static final int RoundBracket = 0; - - public static byte scope_la[] = null; - public static char scope_lhs[] = null; - - public static char scope_prefix[] = null; - public static char scope_rhs[] = null; - public static char scope_state[] = null; - - public static char scope_state_set[] = null; - public static char scope_suffix[] = null; - public static final int SquareBracket = 1; - - //internal data for the automat - protected final static int StackIncrement = 255; - - public static char term_action[] = null; - public static byte term_check[] = null; - - public static char terminal_index[] = null; - - private static final String UNEXPECTED_EOF = "Unexpected End Of File" ; //$NON-NLS-1$ - public static boolean VERBOSE_RECOVERY = false; - - - static boolean optionalSemicolonState[] =null; - - - protected int astLengthPtr; - protected int[] astLengthStack; - protected int astPtr; - protected ASTNode[] astStack = new ASTNode[AstStackIncrement]; - public CompilationUnitDeclaration compilationUnit; /*the result from parse()*/ - protected RecoveredElement currentElement; - public int currentToken; - protected boolean diet = false; //tells the scanner to jump over some parts of the code/expressions like method bodies - protected int dietInt = 0; // if > 0 force the none-diet-parsing mode (even if diet if requested) [field parsing with anonymous inner classes...] - protected int endPosition; //accurate only when used ! (the start position is pushed into intStack while the end the current one) - protected int endStatementPosition; - protected int expressionLengthPtr; - protected int[] expressionLengthStack; - protected int expressionPtr; - protected Expression[] expressionStack = new Expression[ExpressionStackIncrement]; - public int firstToken ; // handle for multiple parsing goals - - // generics management - protected int genericsIdentifiersLengthPtr; - protected int[] genericsIdentifiersLengthStack = new int[GenericsStackIncrement]; - protected int genericsLengthPtr; - protected int[] genericsLengthStack = new int[GenericsStackIncrement]; - protected int genericsPtr; - protected ASTNode[] genericsStack = new ASTNode[GenericsStackIncrement]; - - protected boolean hasError; - protected boolean hasReportedError; - - //identifiers stacks - protected int identifierLengthPtr; - protected int[] identifierLengthStack; - protected long[] identifierPositionStack; - protected int identifierPtr; - protected char[][] identifierStack; - - protected boolean ignoreNextOpeningBrace; - //positions , dimensions , .... (int stacks) - protected int intPtr; - protected int[] intStack; - public int lastAct ; //handle for multiple parsing goals - - //error recovery management - protected int lastCheckPoint; - protected int lastErrorEndPosition; - protected int lastErrorEndPositionBeforeRecovery = -1; - protected int lastIgnoredToken, nextIgnoredToken; - protected int listLength; // for recovering some incomplete list (interfaces, throws or parameters) - protected int listTypeParameterLength; // for recovering some incomplete list (type parameters) - protected int lParenPos,rParenPos; //accurate only when used ! - protected int modifiers; - protected int modifiersSourceStart; - protected int[] nestedMethod; //the ptr is nestedType - protected int nestedType, dimensions; - ASTNode [] noAstNodes = new ASTNode[AstStackIncrement]; - Expression [] noExpressions = new Expression[ExpressionStackIncrement]; - //modifiers dimensions nestedType etc....... - protected boolean optimizeStringLiterals =true; - protected CompilerOptions options; - protected ProblemReporter problemReporter; - protected int rBraceStart, rBraceEnd, rBraceSuccessorStart; //accurate only when used ! - protected int realBlockPtr; - protected int[] realBlockStack; - protected int recoveredStaticInitializerStart; - public ReferenceContext referenceContext; - public boolean reportOnlyOneSyntaxError = false; - public boolean reportSyntaxErrorIsRequired = true; - protected boolean restartRecovery; - - // statement recovery -// public boolean statementRecoveryEnabled = true; - public boolean methodRecoveryActivated = false; - protected boolean statementRecoveryActivated = false; - protected TypeDeclaration[] recoveredTypes; - protected int recoveredTypePtr; - protected int nextTypeStart; - protected TypeDeclaration pendingRecoveredType; - - public RecoveryScanner recoveryScanner; - - //scanner token - public Scanner scanner; - protected int[] stack = new int[StackIncrement]; - protected int stateStackTop; -// protected int synchronizedBlockSourceStart; - protected int[] variablesCounter; - - protected boolean checkExternalizeStrings; - protected boolean recordStringLiterals; - - // javadoc - public Javadoc javadoc; - public JavadocParser javadocParser; - // used for recovery - protected int lastJavadocEnd; - - private boolean enteredRecoverStatements; - - private int insertedSemicolonPosition=-1; - - private Set errorAction = new HashSet(); - - private static final int UNCONSUMED_LIT_ELEMENT=0x4; - private static final int UNCONSUMED_ELISION=0x2; - private static final int WAS_ARRAY_LIT_ELEMENT=0x1; - - public static final byte FLAG_EMPTY_STATEMENT = 1; - - public IInferEngine[] inferenceEngines; - - static { - try{ - initTables(); - } catch(java.io.IOException ex){ - throw new ExceptionInInitializerError(ex.getMessage()); - } - } -public static int asi(int state) { - - return asb[original_state(state)]; -} -public final static short base_check(int i) { - return check_table[i - (NUM_RULES + 1)]; -} -private final static void buildFile(String filename, List listToDump) { - BufferedWriter writer = null; - try { - writer = new BufferedWriter(new FileWriter(filename)); - for (Iterator iterator = listToDump.iterator(); iterator.hasNext(); ) { - writer.write(String.valueOf(iterator.next())); - } - writer.flush(); - } catch(IOException e) { - // ignore - } finally { - if (writer != null) { - try { - writer.close(); - } catch (IOException e1) { - // ignore - } - } - } - System.out.println(filename + " creation complete"); //$NON-NLS-1$ -} -private final static String[] buildFileForName(String filename, String contents) { - String[] result = new String[contents.length()]; - result[0] = null; - int resultCount = 1; - - StringBuffer buffer = new StringBuffer(); - - int start = contents.indexOf("name[]"); //$NON-NLS-1$ - start = contents.indexOf('\"', start); - int end = contents.indexOf("};", start); //$NON-NLS-1$ - - contents = contents.substring(start, end); - - boolean addLineSeparator = false; - int tokenStart = -1; - StringBuffer currentToken = new StringBuffer(); - for (int i = 0; i < contents.length(); i++) { - char c = contents.charAt(i); - if(c == '\"') { - if(tokenStart == -1) { - tokenStart = i + 1; - } else { - if(addLineSeparator) { - buffer.append('\n'); - result[resultCount++] = currentToken.toString(); - currentToken = new StringBuffer(); - } - String token = contents.substring(tokenStart, i); - if(token.equals(ERROR_TOKEN)){ - token = INVALID_CHARACTER; - } else if(token.equals(EOF_TOKEN)) { - token = UNEXPECTED_EOF; - } - buffer.append(token); - currentToken.append(token); - addLineSeparator = true; - tokenStart = -1; - } - } - if(tokenStart == -1 && c == '+'){ - addLineSeparator = false; - } - } - if(currentToken.length() > 0) { - result[resultCount++] = currentToken.toString(); - } - - buildFileForTable(filename, buffer.toString().toCharArray()); - - System.arraycopy(result, 0, result = new String[resultCount], 0, resultCount); - return result; -} -private static void buildFileForReadableName( - String file, - char[] newLhs, - char[] newNonTerminalIndex, - String[] newName, - String[] tokens) { - - ArrayList entries = new ArrayList(); - - boolean[] alreadyAdded = new boolean[newName.length]; - - for (int i = 0; i < tokens.length; i = i + 3) { - if("1".equals(tokens[i])) { //$NON-NLS-1$ - int index = newNonTerminalIndex[newLhs[Integer.parseInt(tokens[i + 1])]]; - StringBuffer buffer = new StringBuffer(); - if(!alreadyAdded[index]) { - alreadyAdded[index] = true; - buffer.append(newName[index]); - buffer.append('='); - buffer.append(tokens[i+2].trim()); - buffer.append('\n'); - entries.add(String.valueOf(buffer)); - } - } - } - int i = 1; - while(!INVALID_CHARACTER.equals(newName[i])) i++; - i++; - for (; i < alreadyAdded.length; i++) { - if(!alreadyAdded[i]) { - System.out.println(newName[i] + " has no readable name"); //$NON-NLS-1$ - } - } - Collections.sort(entries); - buildFile(file, entries); -} -private static void buildFilesForRecoveryTemplates( - String indexFilename, - String templatesFilename, - char[] newTerminalIndex, - char[] newNonTerminalIndex, - String[] newName, - char[] newLhs, - String[] tokens) { - - int[] newReverse = computeReverseTable(newTerminalIndex, newNonTerminalIndex, newName); - - char[] newRecoveyTemplatesIndex = new char[newNonTerminalIndex.length]; - char[] newRecoveyTemplates = new char[newNonTerminalIndex.length]; - int newRecoveyTemplatesPtr = 0; - - for (int i = 0; i < tokens.length; i = i + 3) { - if("3".equals(tokens[i])) { //$NON-NLS-1$ - int length = newRecoveyTemplates.length; - if(length == newRecoveyTemplatesPtr + 1) { - System.arraycopy(newRecoveyTemplates, 0, newRecoveyTemplates = new char[length * 2], 0, length); - } - newRecoveyTemplates[newRecoveyTemplatesPtr++] = 0; - - int index = newLhs[Integer.parseInt(tokens[i + 1])]; - - newRecoveyTemplatesIndex[index] = (char)newRecoveyTemplatesPtr; - - String token = tokens[i + 2].trim(); - java.util.StringTokenizer st = new java.util.StringTokenizer(new String(token), " "); //$NON-NLS-1$ - String[] terminalNames = new String[st.countTokens()]; - int t = 0; - while (st.hasMoreTokens()) { - terminalNames[t++] = st.nextToken(); - } - - for (int j = 0; j < terminalNames.length; j++) { - int symbol = getSymbol(terminalNames[j], newName, newReverse); - if(symbol > -1) { - length = newRecoveyTemplates.length; - if(length == newRecoveyTemplatesPtr + 1) { - System.arraycopy(newRecoveyTemplates, 0, newRecoveyTemplates = new char[length * 2], 0, length); - } - newRecoveyTemplates[newRecoveyTemplatesPtr++] = (char)symbol; - } - } - } - } - newRecoveyTemplates[newRecoveyTemplatesPtr++] = 0; - System.arraycopy(newRecoveyTemplates, 0, newRecoveyTemplates = new char[newRecoveyTemplatesPtr], 0, newRecoveyTemplatesPtr); - - buildFileForTable(indexFilename, newRecoveyTemplatesIndex); - buildFileForTable(templatesFilename, newRecoveyTemplates); -} -private static void buildFilesForStatementsRecoveryFilter( - String filename, - char[] newNonTerminalIndex, - char[] newLhs, - String[] tokens) { - - char[] newStatementsRecoveryFilter = new char[newNonTerminalIndex.length]; - - for (int i = 0; i < tokens.length; i = i + 3) { - if("4".equals(tokens[i])) { //$NON-NLS-1$ - int index = newLhs[Integer.parseInt(tokens[i + 1])]; - - newStatementsRecoveryFilter[index] = 1; - } - } - buildFileForTable(filename, newStatementsRecoveryFilter); - } - -private static void buildFilesForFlags( - String filename, - int size, - String[] tokens) { - - byte[] flags = new byte[size]; - - for (int i = 0; i < tokens.length; i = i + 3) { - if("5".equals(tokens[i])) { //$NON-NLS-1$ - int index = Integer.parseInt(tokens[i + 1]); - byte value =(byte) Integer.parseInt(tokens[i + 2].trim()); - flags[index]=value; - } - } - buildFileForTable(filename, flags); - } - -private static void buildFileForCompliance( - String file, - int length, - String[] tokens) { - - byte[] result = new byte[length * 8]; - - for (int i = 0; i < tokens.length; i = i + 3) { - if("2".equals(tokens[i])) { //$NON-NLS-1$ - int index = Integer.parseInt(tokens[i + 1]); - String token = tokens[i + 2].trim(); - long compliance = 0; - if("1.4".equals(token)) { //$NON-NLS-1$ - compliance = ClassFileConstants.JDK1_4; - } else if("1.5".equals(token)) { //$NON-NLS-1$ - compliance = ClassFileConstants.JDK1_5; - } else if("recovery".equals(token)) { //$NON-NLS-1$ - compliance = ClassFileConstants.JDK_DEFERRED; - } - - int j = index * 8; - result[j] = (byte)(compliance >>> 56); - result[j + 1] = (byte)(compliance >>> 48); - result[j + 2] = (byte)(compliance >>> 40); - result[j + 3] = (byte)(compliance >>> 32); - result[j + 4] = (byte)(compliance >>> 24); - result[j + 5] = (byte)(compliance >>> 16); - result[j + 6] = (byte)(compliance >>> 8); - result[j + 7] = (byte)(compliance); - } - } - - buildFileForTable(file, result); - } -private final static void buildFileForTable(String filename, byte[] bytes) { - java.io.FileOutputStream stream = null; - try { - stream = new java.io.FileOutputStream(filename); - stream.write(bytes); - } catch(IOException e) { - // ignore - } finally { - if (stream != null) { - try { - stream.close(); - } catch (IOException e1) { - // ignore - } - } - } - System.out.println(filename + " creation complete"); //$NON-NLS-1$ - } - private final static void buildFileForTable(String filename, char[] chars) { - byte[] bytes = new byte[chars.length * 2]; - for (int i = 0; i < chars.length; i++) { - bytes[2 * i] = (byte) (chars[i] >>> 8); - bytes[2 * i + 1] = (byte) (chars[i] & 0xFF); - } - - java.io.FileOutputStream stream = null; - try { - stream = new java.io.FileOutputStream(filename); - stream.write(bytes); - } catch(IOException e) { - // ignore - } finally { - if (stream != null) { - try { - stream.close(); - } catch (IOException e1) { - // ignore - } - } - } - System.out.println(filename + " creation complete"); //$NON-NLS-1$ - } - private final static byte[] buildFileOfByteFor(String filename, String tag, String[] tokens) { - - //transform the String tokens into chars before dumping then into file - - int i = 0; - //read upto the tag - while (!tokens[i++].equals(tag)){/*empty*/} - //read upto the } - - byte[] bytes = new byte[tokens.length]; //can't be bigger - int ic = 0; - String token; - while (!(token = tokens[i++]).equals("}")) { //$NON-NLS-1$ - int c = Integer.parseInt(token); - bytes[ic++] = (byte) c; - } - - //resize - System.arraycopy(bytes, 0, bytes = new byte[ic], 0, ic); - - buildFileForTable(filename, bytes); - return bytes; - } - private final static char[] buildFileOfIntFor(String filename, String tag, String[] tokens) { - - //transform the String tokens into chars before dumping then into file - - int i = 0; - //read upto the tag - while (!tokens[i++].equals(tag)){/*empty*/} - //read upto the } - - char[] chars = new char[tokens.length]; //can't be bigger - int ic = 0; - String token; - while (!(token = tokens[i++]).equals("}")) { //$NON-NLS-1$ - int c = Integer.parseInt(token); - chars[ic++] = (char) c; - } - - //resize - System.arraycopy(chars, 0, chars = new char[ic], 0, ic); - - buildFileForTable(filename, chars); - return chars; - } - private final static void buildFileOfShortFor(String filename, String tag, String[] tokens) { - - //transform the String tokens into chars before dumping then into file - - int i = 0; - //read upto the tag - while (!tokens[i++].equals(tag)){/*empty*/} - //read upto the } - - char[] chars = new char[tokens.length]; //can't be bigger - int ic = 0; - String token; - while (!(token = tokens[i++]).equals("}")) { //$NON-NLS-1$ - int c = Integer.parseInt(token); - chars[ic++] = (char) (c + 32768); - } - - //resize - System.arraycopy(chars, 0, chars = new char[ic], 0, ic); - - buildFileForTable(filename, chars); - } -public final static void buildFilesFromLPG(String dataFilename, String dataFilename2) { - - //RUN THIS METHOD TO GENERATE PARSER*.RSC FILES - - //build from the lpg javadcl.java files that represents the parser tables - //lhs check_table asb asr symbol_index - - //[org.eclipse.wst.jsdt.internal.compiler.parser.Parser.buildFilesFromLPG("d:/leapfrog/grammar/javadcl.java")] - char[] contents = CharOperation.NO_CHAR; - try { - contents = Util.getFileCharContent(new File(dataFilename), null); - } catch (IOException ex) { - System.out.println(Messages.parser_incorrectPath); - return; - } - java.util.StringTokenizer st = - new java.util.StringTokenizer(new String(contents), " \t\n\r[]={,;"); //$NON-NLS-1$ - String[] tokens = new String[st.countTokens()]; - int j = 0; - while (st.hasMoreTokens()) { - tokens[j++] = st.nextToken(); - } - final String prefix = FILEPREFIX; - int i = 0; - - char[] newLhs = buildFileOfIntFor(prefix + (++i) + ".rsc", "lhs", tokens); //$NON-NLS-1$ //$NON-NLS-2$ - buildFileOfShortFor(prefix + (++i) + ".rsc", "check_table", tokens); //$NON-NLS-2$ //$NON-NLS-1$ - buildFileOfIntFor(prefix + (++i) + ".rsc", "asb", tokens); //$NON-NLS-2$ //$NON-NLS-1$ - buildFileOfIntFor(prefix + (++i) + ".rsc", "asr", tokens); //$NON-NLS-2$ //$NON-NLS-1$ - buildFileOfIntFor(prefix + (++i) + ".rsc", "nasb", tokens); //$NON-NLS-2$ //$NON-NLS-1$ - buildFileOfIntFor(prefix + (++i) + ".rsc", "nasr", tokens); //$NON-NLS-2$ //$NON-NLS-1$ - char[] newTerminalIndex = buildFileOfIntFor(prefix + (++i) + ".rsc", "terminal_index", tokens); //$NON-NLS-2$ //$NON-NLS-1$ - char[] newNonTerminalIndex = buildFileOfIntFor(prefix + (++i) + ".rsc", "non_terminal_index", tokens); //$NON-NLS-1$ //$NON-NLS-2$ - buildFileOfIntFor(prefix + (++i) + ".rsc", "term_action", tokens); //$NON-NLS-2$ //$NON-NLS-1$ - - buildFileOfIntFor(prefix + (++i) + ".rsc", "scope_prefix", tokens); //$NON-NLS-2$ //$NON-NLS-1$ - buildFileOfIntFor(prefix + (++i) + ".rsc", "scope_suffix", tokens); //$NON-NLS-2$ //$NON-NLS-1$ - buildFileOfIntFor(prefix + (++i) + ".rsc", "scope_lhs", tokens); //$NON-NLS-2$ //$NON-NLS-1$ - buildFileOfIntFor(prefix + (++i) + ".rsc", "scope_state_set", tokens); //$NON-NLS-2$ //$NON-NLS-1$ - buildFileOfIntFor(prefix + (++i) + ".rsc", "scope_rhs", tokens); //$NON-NLS-2$ //$NON-NLS-1$ - buildFileOfIntFor(prefix + (++i) + ".rsc", "scope_state", tokens); //$NON-NLS-2$ //$NON-NLS-1$ - buildFileOfIntFor(prefix + (++i) + ".rsc", "in_symb", tokens); //$NON-NLS-2$ //$NON-NLS-1$ - - byte[] newRhs = buildFileOfByteFor(prefix + (++i) + ".rsc", "rhs", tokens); //$NON-NLS-2$ //$NON-NLS-1$ - buildFileOfByteFor(prefix + (++i) + ".rsc", "term_check", tokens); //$NON-NLS-2$ //$NON-NLS-1$ - buildFileOfByteFor(prefix + (++i) + ".rsc", "scope_la", tokens); //$NON-NLS-2$ //$NON-NLS-1$ - - String[] newName = buildFileForName(prefix + (++i) + ".rsc", new String(contents)); //$NON-NLS-1$ - - contents = CharOperation.NO_CHAR; - try { - contents = Util.getFileCharContent(new File(dataFilename2), null); - } catch (IOException ex) { - System.out.println(Messages.parser_incorrectPath); - return; - } - st = new java.util.StringTokenizer(new String(contents), "\t\n\r#"); //$NON-NLS-1$ - tokens = new String[st.countTokens()]; - j = 0; - while (st.hasMoreTokens()) { - tokens[j++] = st.nextToken(); - } - - buildFileForCompliance(prefix + (++i) + ".rsc", newRhs.length, tokens);//$NON-NLS-1$ - buildFileForReadableName(READABLE_NAMES_FILE+".properties", newLhs, newNonTerminalIndex, newName, tokens);//$NON-NLS-1$ - - buildFilesForRecoveryTemplates( - prefix + (++i) + ".rsc", //$NON-NLS-1$ - prefix + (++i) + ".rsc", //$NON-NLS-1$ - newTerminalIndex, - newNonTerminalIndex, - newName, - newLhs, - tokens); - - buildFilesForStatementsRecoveryFilter( - prefix + (++i) + ".rsc", //$NON-NLS-1$ - newNonTerminalIndex, - newLhs, - tokens); - - buildFilesForFlags( - prefix + (++i) + ".rsc", //$NON-NLS-1$ - rhs.length, - tokens); - - - System.out.println(Messages.parser_moveFiles); -} -public static int in_symbol(int state) { - return in_symb[original_state(state)]; -} -public final static void initTables() throws java.io.IOException { - - final String prefix = FILEPREFIX; - int i = 0; - lhs = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ - char[] chars = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ - check_table = new short[chars.length]; - for (int c = chars.length; c-- > 0;) { - check_table[c] = (short) (chars[c] - 32768); - } - asb = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ - asr = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ - nasb = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ - nasr = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ - terminal_index = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ - non_terminal_index = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ - term_action = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ - - scope_prefix = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ - scope_suffix = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ - scope_lhs = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ - scope_state_set = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ - scope_rhs = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ - scope_state = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ - in_symb = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ - - rhs = readByteTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ - term_check = readByteTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ - scope_la = readByteTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ - - name = readNameTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ - - rules_compliance = readLongTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ - - readableName = readReadableNameTable(READABLE_NAMES_FILE_NAME); - - reverse_index = computeReverseTable(terminal_index, non_terminal_index, name); - - recovery_templates_index = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ - recovery_templates = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ - - statements_recovery_filter = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ - state_flags = readByteTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ - - base_action = lhs; - - optionalSemicolonState =new boolean[base_action.length]; - for ( i = 0; i < optionalSemicolonState.length; i++) { - if (base_action[i]+TokenNameSEMICOLONERROR_ACTION) - act-=ERROR_ACTION; - boolean isEmptyStatementsState = false; - if (act0; - if (!isEmptyStatementsState) - optionalSemicolonState[i]=true; - } - } - -} -public static int nasi(int state) { - return nasb[original_state(state)]; -} -public static int ntAction(int state, int sym) { - return base_action[state + sym]; -} -protected static int original_state(int state) { - return -base_check(state); -} -protected static int[] computeReverseTable(char[] newTerminalIndex, char[] newNonTerminalIndex, String[] newName) { - int[] newReverseTable = new int[newName.length]; - for (int j = 0; j < newName.length; j++) { - found : { - for (int k = 0; k < newTerminalIndex.length; k++) { - if(newTerminalIndex[k] == j) { - newReverseTable[j] = k; - break found; - } - } - for (int k = 0; k < newNonTerminalIndex.length; k++) { - if(newNonTerminalIndex[k] == j) { - newReverseTable[j] = -k; - break found; - } - } - } - } - return newReverseTable; -} - -private static int getSymbol(String terminalName, String[] newName, int[] newReverse) { - for (int j = 0; j < newName.length; j++) { - if(terminalName.equals(newName[j])) { - return newReverse[j]; - } - } - return -1; -} - -protected static byte[] readByteTable(String filename) throws java.io.IOException { - - //files are located at Parser.class directory - - InputStream stream = Parser.class.getResourceAsStream(filename); - if (stream == null) { - throw new java.io.IOException(Messages.bind(Messages.parser_missingFile, filename)); - } - byte[] bytes = null; - try { - stream = new BufferedInputStream(stream); - bytes = Util.getInputStreamAsByteArray(stream, -1); - } finally { - try { - stream.close(); - } catch (IOException e) { - // ignore - } - } - return bytes; -} - -protected static String[] readNameTable(String filename) throws java.io.IOException { - char[] contents = readTable(filename); - char[][] nameAsChar = CharOperation.splitOn('\n', contents); - - String[] result = new String[nameAsChar.length + 1]; - result[0] = null; - for (int i = 0; i < nameAsChar.length; i++) { - result[i + 1] = new String(nameAsChar[i]); - } - - return result; -} -protected static String[] readReadableNameTable(String filename) { - String[] result = new String[name.length]; - - ResourceBundle bundle; - try { - bundle = ResourceBundle.getBundle(filename, Locale.getDefault()); - } catch(MissingResourceException e) { - System.out.println("Missing resource : " + filename.replace('.', '/') + ".properties for locale " + Locale.getDefault()); //$NON-NLS-1$//$NON-NLS-2$ - throw e; - } - for (int i = 0; i < NT_OFFSET + 1; i++) { - result[i] = name[i]; - } - for (int i = NT_OFFSET; i < name.length; i++) { - try { - String n = bundle.getString(name[i]); - if(n != null && n.length() > 0) { - result[i] = n; - } else { - result[i] = name[i]; - } - } catch(MissingResourceException e) { - result[i] = name[i]; - } - } - return result; -} -protected static char[] readTable(String filename) throws java.io.IOException { - - //files are located at Parser.class directory - - InputStream stream = Parser.class.getResourceAsStream(filename); - if (stream == null) { - throw new java.io.IOException(Messages.bind(Messages.parser_missingFile, filename)); - } - byte[] bytes = null; - try { - stream = new BufferedInputStream(stream); - bytes = Util.getInputStreamAsByteArray(stream, -1); - } finally { - try { - stream.close(); - } catch (IOException e) { - // ignore - } - } - - //minimal integrity check (even size expected) - int length = bytes.length; - if ((length & 1) != 0) - throw new java.io.IOException(Messages.bind(Messages.parser_corruptedFile, filename)); - - // convert bytes into chars - char[] chars = new char[length / 2]; - int i = 0; - int charIndex = 0; - - while (true) { - chars[charIndex++] = (char) (((bytes[i++] & 0xFF) << 8) + (bytes[i++] & 0xFF)); - if (i == length) - break; - } - return chars; -} -protected static long[] readLongTable(String filename) throws java.io.IOException { - - //files are located at Parser.class directory - - InputStream stream = Parser.class.getResourceAsStream(filename); - if (stream == null) { - throw new java.io.IOException(Messages.bind(Messages.parser_missingFile, filename)); - } - byte[] bytes = null; - try { - stream = new BufferedInputStream(stream); - bytes = Util.getInputStreamAsByteArray(stream, -1); - } finally { - try { - stream.close(); - } catch (IOException e) { - // ignore - } - } - - //minimal integrity check (even size expected) - int length = bytes.length; - if (length % 8 != 0) - throw new java.io.IOException(Messages.bind(Messages.parser_corruptedFile, filename)); - - // convert bytes into longs - long[] longs = new long[length / 8]; - int i = 0; - int longIndex = 0; - - while (true) { - longs[longIndex++] = - (((long) (bytes[i++] & 0xFF)) << 56) - + (((long) (bytes[i++] & 0xFF)) << 48) - + (((long) (bytes[i++] & 0xFF)) << 40) - + (((long) (bytes[i++] & 0xFF)) << 32) - + (((long) (bytes[i++] & 0xFF)) << 24) - + (((long) (bytes[i++] & 0xFF)) << 16) - + (((long) (bytes[i++] & 0xFF)) << 8) - + (bytes[i++] & 0xFF); - - if (i == length) - break; - } - return longs; -} -public static int tAction(int state, int sym) { - return term_action[term_check[base_action[state]+sym] == sym ? base_action[state] + sym : base_action[state]]; -} - -public Parser(ProblemReporter problemReporter, boolean optimizeStringLiterals) { - - this.problemReporter = problemReporter; - this.options = problemReporter.options; - this.optimizeStringLiterals = optimizeStringLiterals; - this.initializeScanner(); - this.astLengthStack = new int[50]; - this.expressionLengthStack = new int[30]; - this.intStack = new int[50]; - this.identifierStack = new char[30][]; - this.identifierLengthStack = new int[30]; - this.nestedMethod = new int[30]; - this.realBlockStack = new int[30]; - this.identifierPositionStack = new long[30]; - this.variablesCounter = new int[30]; - - // javadoc support - this.javadocParser = createJavadocParser(); - -} -protected void annotationRecoveryCheckPoint(int start, int end) { - if(this.lastCheckPoint > start && this.lastCheckPoint < end) { - this.lastCheckPoint = end + 1; - } -} -public void arrayInitializer(int length) { - //length is the size of the array Initializer - //expressionPtr points on the last elt of the arrayInitializer, - // in other words, it has not been decremented yet. - - ArrayInitializer ai = new ArrayInitializer(); - if (length != 0) { - this.expressionPtr -= length; - System.arraycopy(this.expressionStack, this.expressionPtr + 1, ai.expressions = new Expression[length], 0, length); - } - pushOnExpressionStack(ai); - //positionning - ai.sourceEnd = this.endStatementPosition; - ai.sourceStart = this.intStack[this.intPtr--]; -} -protected void blockReal() { - // See consumeLocalVariableDeclarationStatement in case of change: duplicated code - // increment the amount of declared variables for this block - this.realBlockStack[this.realBlockPtr]++; -} -/* - * Build initial recovery state. - * Recovery state is inferred from the current state of the parser (reduced node stack). - */ -public RecoveredElement buildInitialRecoveryState(){ - - /* initialize recovery by retrieving available reduced nodes - * also rebuild bracket balance - */ - this.lastCheckPoint = 0; - this.lastErrorEndPositionBeforeRecovery = this.scanner.currentPosition; - - RecoveredElement element = null; - if (this.referenceContext instanceof CompilationUnitDeclaration){ - if (!DO_DIET_PARSE) - { - this.methodRecoveryActivated=true; -// this.statementRecoveryActivated=true; - } - element = new RecoveredUnit(this.compilationUnit, 0, this); - - /* ignore current stack state, since restarting from the beginnning - since could not trust simple brace count */ - if (false){ // experimenting restart recovery from scratch - this.compilationUnit.currentPackage = null; - this.compilationUnit.imports = null; - this.compilationUnit.types = null; - this.compilationUnit.statements = null; - this.currentToken = 0; - this.listLength = 0; - this.listTypeParameterLength = 0; - this.endPosition = 0; - this.endStatementPosition = 0; - return element; - } - else - { - this.currentToken = 0; -// if (this.astPtr<0&&this.compilationUnit.sourceEnd>0) -// this.lastCheckPoint = this.compilationUnit.sourceEnd; - - } - - if (this.compilationUnit.currentPackage != null){ - this.lastCheckPoint = this.compilationUnit.currentPackage.declarationSourceEnd+1; - } - if (this.compilationUnit.imports != null){ - this.lastCheckPoint = this.compilationUnit.imports[this.compilationUnit.imports.length -1].declarationSourceEnd+1; - } - } else { - if (this.referenceContext instanceof AbstractMethodDeclaration){ - element = new RecoveredMethod((AbstractMethodDeclaration) this.referenceContext, null, 0, this); - this.lastCheckPoint = ((AbstractMethodDeclaration) this.referenceContext).bodyStart; - if(this.statementRecoveryActivated) { - element = element.add(new Block(0), 0); - } - } else { - /* Initializer bodies are parsed in the context of the type declaration, we must thus search it inside */ - if (this.referenceContext instanceof TypeDeclaration){ - TypeDeclaration type = (TypeDeclaration) this.referenceContext; - for (int i = 0; i < type.fields.length; i++){ - FieldDeclaration field = type.fields[i]; - if (field != null - && field.getKind() == AbstractVariableDeclaration.INITIALIZER - && field.declarationSourceStart <= this.scanner.initialPosition - && this.scanner.initialPosition <= field.declarationSourceEnd - && this.scanner.eofPosition <= field.declarationSourceEnd+1){ - element = new RecoveredInitializer(field, null, 1, this); - this.lastCheckPoint = field.declarationSourceStart; - break; - } - } - } - } - } - - if (element == null) return element; - - element = recoverAST(element); - if (this.statementRecoveryActivated) { - if (this.pendingRecoveredType != null && - this.scanner.startPosition - 1 <= this.pendingRecoveredType.declarationSourceEnd) { - // Add the pending type to the AST if this type isn't already added in the AST. - element = element.add(this.pendingRecoveredType, 0); - this.lastCheckPoint = this.pendingRecoveredType.declarationSourceEnd + 1; - this.pendingRecoveredType = null; - } - } - ProgramElement[] compUnitStatments = this.compilationUnit.statements; - if (compUnitStatments!=null && compUnitStatments.length>0 && - this.lastCheckPoint=0) - { - expression=new Assignment(this.expressionStack[start],funcExpr,method.sourceEnd); - } - if (expression!=null) - { - element = element.add(expression, 1); - if (method.declarationSourceEnd == 0){ - element = element.add(method, 0); - this.lastCheckPoint = method.bodyStart; - } else { - element = element.add(method, 0); - this.lastCheckPoint = method.declarationSourceEnd + 1; - } - if (element instanceof RecoveredMethod) - element.add(new Block(0), 0); - } - - return element; -} -protected void checkAndSetModifiers(int flag){ - /*modify the current modifiers buffer. - When the startPosition of the modifiers is 0 - it means that the modifier being parsed is the first - of a list of several modifiers. The startPosition - is zeroed when a copy of modifiers-buffer is push - onto the this.astStack. */ - - if ((this.modifiers & flag) != 0){ // duplicate modifier - this.modifiers |= ExtraCompilerModifiers.AccAlternateModifierProblem; - } - this.modifiers |= flag; - - if (this.modifiersSourceStart < 0) this.modifiersSourceStart = this.scanner.startPosition; -} -public void checkComment() { - - // discard obsolete comments while inside methods or fields initializer (see bug 74369) - // don't discard if the expression being worked on is an ObjectLiteral (see bug 322412 ) - if (!(this.diet && this.dietInt == 0) && this.scanner.commentPtr >= 0 && !(expressionPtr >= 0 && expressionStack[expressionPtr] instanceof ObjectLiteral)) { - flushCommentsDefinedPriorTo(this.endStatementPosition); - } - - int lastComment = this.scanner.commentPtr; - -// if (this.modifiersSourceStart >= 0) { -// // eliminate comments located after modifierSourceStart if positionned -// while (lastComment >= 0 && this.scanner.commentStarts[lastComment] > this.modifiersSourceStart) lastComment--; -// } - if (lastComment >= 0) { - // consider all remaining leading comments to be part of current declaration - this.modifiersSourceStart = this.scanner.commentStarts[0]; - - // check deprecation in last comment if javadoc (can be followed by non-javadoc comments which are simply ignored) - while (lastComment >= 0 && this.scanner.commentStops[lastComment] < 0) lastComment--; // non javadoc comment have negative end positions - if (lastComment >= 0 && this.javadocParser != null) { - int commentEnd = this.scanner.commentStops[lastComment] - 1; //stop is one over, - // do not report problem before last parsed comment while recovering code... - this.javadocParser.reportProblems = this.currentElement == null || commentEnd > this.lastJavadocEnd; - if (this.javadocParser.checkDeprecation(lastComment)) { - checkAndSetModifiers(ClassFileConstants.AccDeprecated); - } - this.javadoc = this.javadocParser.docComment; // null if check javadoc is not activated - if (currentElement == null) this.lastJavadocEnd = commentEnd; - } - } -} -protected void checkNonNLSAfterBodyEnd(int declarationEnd){ - if(this.scanner.currentPosition - 1 <= declarationEnd) { - this.scanner.eofPosition = declarationEnd < Integer.MAX_VALUE ? declarationEnd + 1 : declarationEnd; - try { - while(this.scanner.getNextToken() != TokenNameEOF){/*empty*/} - } catch (InvalidInputException e) { - // Nothing to do - } - } -} -protected void classInstanceCreation(boolean isQualified, boolean isShort) { - // ClassInstanceCreationExpression ::= 'new' ClassType '(' ArgumentListopt ')' ClassBodyopt - - // ClassBodyopt produces a null item on the astStak if it produces NO class body - // An empty class body produces a 0 on the length stack..... - - AllocationExpression alloc = new AllocationExpression(); - int length; -// if (((length = this.astLengthStack[this.astLengthPtr--]) == 1) -// && (this.astStack[this.astPtr] == null)) { -// //NO ClassBody -// this.astPtr--; -// if (isQualified) { -// alloc = new QualifiedAllocationExpression(); -// } else { - alloc = new AllocationExpression(); -// } - - alloc.isShort=isShort; - if (!isShort) - { - alloc.sourceEnd = this.intStack[this.intPtr--]; //the position has been stored explicitly - if ((length = this.expressionLengthStack[this.expressionLengthPtr--]) != 0) { - this.expressionPtr -= length; - System.arraycopy( - this.expressionStack, - this.expressionPtr + 1, - alloc.arguments = new Expression[length], - 0, - length); - } - - } - - alloc.member = this.expressionStack[this.expressionPtr--]; - this.expressionLengthPtr--; - - //the default constructor with the correct number of argument - //will be created and added by the TC (see createsInternalConstructorWithBinding) - alloc.sourceStart = this.intStack[this.intPtr--]; - if (isShort) - alloc.sourceEnd=alloc.member.sourceEnd; - pushOnExpressionStack(alloc); -// } else { -// dispatchDeclarationInto(length); -// TypeDeclaration anonymousTypeDeclaration = (TypeDeclaration)this.astStack[this.astPtr]; -// anonymousTypeDeclaration.declarationSourceEnd = this.endStatementPosition; -// anonymousTypeDeclaration.bodyEnd = this.endStatementPosition; -// if (anonymousTypeDeclaration.allocation != null) { -// anonymousTypeDeclaration.allocation.sourceEnd = this.endStatementPosition; -// } -// if (length == 0 && !containsComment(anonymousTypeDeclaration.bodyStart, anonymousTypeDeclaration.bodyEnd)) { -// anonymousTypeDeclaration.bits |= ASTNode.UndocumentedEmptyBlock; -// } -// this.astPtr--; -// this.astLengthPtr--; -// -// // mark initializers with local type mark if needed -// markInitializersWithLocalType(anonymousTypeDeclaration); -// } -} -protected void concatExpressionLists() { - this.expressionLengthStack[--this.expressionLengthPtr]++; -} -protected void concatNodeLists() { - /* - * This is a case where you have two sublists into the this.astStack that you want - * to merge in one list. There is no action required on the this.astStack. The only - * thing you need to do is merge the two lengths specified on the astStackLength. - * The top two length are for example: - * ... p n - * and you want to result in a list like: - * ... n+p - * This means that the p could be equals to 0 in case there is no astNode pushed - * on the this.astStack. - * Look at the InterfaceMemberDeclarations for an example. - */ - - this.astLengthStack[this.astLengthPtr - 1] += this.astLengthStack[this.astLengthPtr--]; -} -protected void consumeAnnotationAsModifier() { - Expression expression = this.expressionStack[this.expressionPtr]; - int sourceStart = expression.sourceStart; - if (this.modifiersSourceStart < 0) { - this.modifiersSourceStart = sourceStart; - } -} -protected void consumeArgumentList() { - // ArgumentList ::= ArgumentList ',' Expression - concatExpressionLists(); -} -protected void consumeArguments() { - // Arguments ::= '(' ArgumentListopt ')' - // nothing to do, the expression stack is already updated - pushOnIntStack(rParenPos); -} -protected void consumeAssignment() { - // Assignment ::= LeftHandSide AssignmentOperator AssignmentExpression - //optimize the push/pop - - int op = this.intStack[this.intPtr--] ; //<--the encoded operator - - this.expressionPtr -- ; this.expressionLengthPtr -- ; - checkComment(); - - if(op != EQUAL) { - CompoundAssignment compoundAssignment = new CompoundAssignment( - this.expressionStack[this.expressionPtr] , - this.expressionStack[this.expressionPtr+1], - op, - this.scanner.startPosition - 1); - if (this.javadoc != null) { - compoundAssignment.javadoc = this.javadoc; - this.javadoc = null; - } - this.expressionStack[this.expressionPtr] = compoundAssignment; - } - else { - Assignment assignment = new Assignment( - this.expressionStack[this.expressionPtr] , - this.expressionStack[this.expressionPtr+1], - this.scanner.startPosition - 1); - if (this.javadoc != null) { - assignment.javadoc = this.javadoc; - this.javadoc = null; - } - this.expressionStack[this.expressionPtr] = assignment; - } - - if (this.pendingRecoveredType != null) { - // Used only in statements recovery. - // This is not a real assignment but a placeholder for an existing anonymous type. - // The assignment must be replace by the anonymous type. - if (this.pendingRecoveredType.allocation != null && - this.scanner.startPosition - 1 <= this.pendingRecoveredType.declarationSourceEnd) { - this.expressionStack[this.expressionPtr] = this.pendingRecoveredType.allocation; - this.pendingRecoveredType = null; - return; - } - this.pendingRecoveredType = null; - } -} -protected void consumeAssignmentOperator(int pos) { - // AssignmentOperator ::= '=' - // AssignmentOperator ::= '*=' - // AssignmentOperator ::= '/=' - // AssignmentOperator ::= '%=' - // AssignmentOperator ::= '+=' - // AssignmentOperator ::= '-=' - // AssignmentOperator ::= '<<=' - // AssignmentOperator ::= '>>=' - // AssignmentOperator ::= '>>>=' - // AssignmentOperator ::= '&=' - // AssignmentOperator ::= '^=' - // AssignmentOperator ::= '|=' - - pushOnIntStack(pos); -} -protected void consumeBinaryExpression(int op) { - // MultiplicativeExpression ::= MultiplicativeExpression '*' UnaryExpression - // MultiplicativeExpression ::= MultiplicativeExpression '/' UnaryExpression - // MultiplicativeExpression ::= MultiplicativeExpression '%' UnaryExpression - // AdditiveExpression ::= AdditiveExpression '+' MultiplicativeExpression - // AdditiveExpression ::= AdditiveExpression '-' MultiplicativeExpression - // ShiftExpression ::= ShiftExpression '<<' AdditiveExpression - // ShiftExpression ::= ShiftExpression '>>' AdditiveExpression - // ShiftExpression ::= ShiftExpression '>>>' AdditiveExpression - // RelationalExpression ::= RelationalExpression '<' ShiftExpression - // RelationalExpression ::= RelationalExpression '>' ShiftExpression - // RelationalExpression ::= RelationalExpression '<=' ShiftExpression - // RelationalExpression ::= RelationalExpression '>=' ShiftExpression - // AndExpression ::= AndExpression '&' EqualityExpression - // ExclusiveOrExpression ::= ExclusiveOrExpression '^' AndExpression - // InclusiveOrExpression ::= InclusiveOrExpression '|' ExclusiveOrExpression - // ConditionalAndExpression ::= ConditionalAndExpression '&&' InclusiveOrExpression - // ConditionalOrExpression ::= ConditionalOrExpression '||' ConditionalAndExpression - - //optimize the push/pop - - this.expressionPtr--; - this.expressionLengthPtr--; - Expression expr1 = this.expressionStack[this.expressionPtr]; - Expression expr2 = this.expressionStack[this.expressionPtr + 1]; - switch(op) { - case OR_OR : - this.expressionStack[this.expressionPtr] = - new OR_OR_Expression( - expr1, - expr2, - op); - break; - case AND_AND : - this.expressionStack[this.expressionPtr] = - new AND_AND_Expression( - expr1, - expr2, - op); - break; - case PLUS : - // look for "string1" + "string2" - // look for "string1" + "string2" - if (this.optimizeStringLiterals) { - if (expr1 instanceof StringLiteral) { - if (expr2 instanceof StringLiteral) { //string+string - this.expressionStack[this.expressionPtr] = - ((StringLiteral) expr1).extendWith((StringLiteral) expr2); - } else { - this.expressionStack[this.expressionPtr] = new BinaryExpression(expr1, expr2, PLUS); - } - } else if (expr1 instanceof CombinedBinaryExpression) { - CombinedBinaryExpression cursor; - // left branch is comprised of PLUS BEs - // cursor is shifted upwards, while needed BEs are added - // on demand; past the arityMax-th - // consecutive BE, a CBE is inserted that holds a - // full-fledged references table - if ((cursor = (CombinedBinaryExpression)expr1).arity < - cursor.arityMax) { - cursor.left = new BinaryExpression(cursor.left, - cursor.right, PLUS); - cursor.arity++; - } else { - cursor.left = new CombinedBinaryExpression(cursor.left, - cursor.right, PLUS, cursor.arity); - cursor.arity = 0; - cursor.tuneArityMax(); - } - cursor.right = expr2; - cursor.sourceEnd = expr2.sourceEnd; - this.expressionStack[this.expressionPtr] = cursor; - // BE_INSTRUMENTATION: neutralized in the released code -// cursor.depthTracker = ((BinaryExpression)cursor.left). -// depthTracker + 1; - } else if (expr1 instanceof BinaryExpression && - // single out the a + b case, which is a BE - // instead of a CBE (slightly more than a half of - // strings concatenation are one-deep binary - // expressions) - ((expr1.bits & ASTNode.OperatorMASK) >> - ASTNode.OperatorSHIFT) == OperatorIds.PLUS) { - this.expressionStack[this.expressionPtr] = - new CombinedBinaryExpression(expr1, expr2, PLUS, 1); - } else { - this.expressionStack[this.expressionPtr] = - new BinaryExpression(expr1, expr2, PLUS); - } - } else if (expr1 instanceof StringLiteral) { - if (expr2 instanceof StringLiteral) { - // string + string - this.expressionStack[this.expressionPtr] = - ((StringLiteral) expr1).extendsWith((StringLiteral) expr2); - } else { - // single out the a + b case - this.expressionStack[this.expressionPtr] = - new BinaryExpression(expr1, expr2, PLUS); - } - } else if (expr1 instanceof CombinedBinaryExpression) { - CombinedBinaryExpression cursor; - // shift cursor; create BE/CBE as needed - if ((cursor = (CombinedBinaryExpression)expr1).arity < - cursor.arityMax) { - cursor.left = new BinaryExpression(cursor.left, - cursor.right, PLUS); - cursor.arity++; - } else { - cursor.left = new CombinedBinaryExpression(cursor.left, - cursor.right, PLUS, cursor.arity); - cursor.arity = 0; - cursor.tuneArityMax(); - } - cursor.right = expr2; - cursor.sourceEnd = expr2.sourceEnd; - // BE_INSTRUMENTATION: neutralized in the released code -// cursor.depthTracker = ((BinaryExpression)cursor.left). -// depthTracker + 1; - this.expressionStack[this.expressionPtr] = cursor; - } else if (expr1 instanceof BinaryExpression && - // single out the a + b case - ((expr1.bits & ASTNode.OperatorMASK) >> - ASTNode.OperatorSHIFT) == OperatorIds.PLUS) { - this.expressionStack[this.expressionPtr] = - new CombinedBinaryExpression(expr1, expr2, PLUS, 1); - } else { - this.expressionStack[this.expressionPtr] = - new BinaryExpression(expr1, expr2, PLUS); - } - break; - case LESS : - this.intPtr--; - this.expressionStack[this.expressionPtr] = - new BinaryExpression( - expr1, - expr2, - op); - break; - default : - this.expressionStack[this.expressionPtr] = - new BinaryExpression( - expr1, - expr2, - op); - } -} -protected void consumeBlock() { - // Block ::= OpenBlock '{' BlockStatementsopt '}' - // simpler action for empty blocks - - int statementsLength = this.astLengthStack[this.astLengthPtr--]; - Block block; - if (statementsLength == 0) { // empty block - block = new Block(0); - block.sourceStart = this.intStack[this.intPtr--]; - block.sourceEnd = this.endStatementPosition; - // check whether this block at least contains some comment in it - if (!containsComment(block.sourceStart, block.sourceEnd)) { - block.bits |= ASTNode.UndocumentedEmptyBlock; - } - this.realBlockPtr--; // still need to pop the block variable counter - } else { - block = new Block(this.realBlockStack[this.realBlockPtr--]); - this.astPtr -= statementsLength; - System.arraycopy( - this.astStack, - this.astPtr + 1, - block.statements = new Statement[statementsLength], - 0, - statementsLength); - block.sourceStart = this.intStack[this.intPtr--]; - block.sourceEnd = this.endStatementPosition; - } - pushOnAstStack(block); -} -protected void consumeBlockStatements() { - // BlockStatements ::= BlockStatements BlockStatement - concatNodeLists(); -} -protected void consumeProgramElements() { - // BlockStatements ::= BlockStatements BlockStatement - concatNodeLists(); -} -protected void consumeCallExpressionWithArguments() { - //optimize the push/pop - //FunctionInvocation ::= Primary '.' 'Identifier' '(' ArgumentListopt ')' - - MessageSend m = newMessageSend(); -// m.sourceStart = -// (int) ((m.nameSourcePosition = this.identifierPositionStack[this.identifierPtr]) >>> 32); -// m.selector = this.identifierStack[this.identifierPtr--]; -// this.identifierLengthPtr--; - - Expression receiver = this.expressionStack[this.expressionPtr]; - m.sourceStart = receiver.sourceStart; - if (receiver instanceof SingleNameReference) - { - SingleNameReference singleNameReference = (SingleNameReference)receiver; - m.selector=singleNameReference.token; - m.nameSourcePosition = (((long) singleNameReference.sourceStart) << 32)+(singleNameReference.sourceStart+m.selector.length-1); - receiver=null; - - } else if (receiver instanceof FieldReference) { - FieldReference fieldReference = (FieldReference) receiver; - m.selector=fieldReference.token; - m.nameSourcePosition= (((long) (fieldReference.sourceEnd-(m.selector.length-1))) << 32)+(fieldReference.sourceEnd); - receiver=fieldReference.receiver; - } - - - m.receiver = receiver; - m.sourceEnd = this.intStack[this.intPtr--]; - this.expressionStack[this.expressionPtr] = m; -} -protected void consumeCallExpressionWithArrayReference() { - this.expressionPtr--; - this.expressionLengthPtr--; - Expression exp = - this.expressionStack[this.expressionPtr] = - new ArrayReference( - this.expressionStack[this.expressionPtr], - this.expressionStack[this.expressionPtr + 1]); - exp.sourceEnd = this.endPosition; -} -protected void consumeCallExpressionWithSimpleName() { - FieldReference fr = - new FieldReference( - this.identifierStack[this.identifierPtr], - this.identifierPositionStack[this.identifierPtr--]); - this.identifierLengthPtr--; - //optimize push/pop - fr.receiver = this.expressionStack[this.expressionPtr]; - //fieldreference begins at the receiver - fr.sourceStart = fr.receiver.sourceStart; - this.expressionStack[this.expressionPtr] = fr; -} -protected void consumeCaseLabel() { - // SwitchLabel ::= 'case' ConstantExpression ':' - this.expressionLengthPtr--; - Expression expression = this.expressionStack[this.expressionPtr--]; - pushOnAstStack(new CaseStatement(expression, expression.sourceEnd, this.intStack[this.intPtr--])); -} -protected void consumeCatches() { - // Catches ::= Catches CatchClause - optimizedConcatNodeLists(); -} -protected void consumeCatchHeader() { - // CatchDeclaration ::= 'catch' '(' FormalParameter ')' '{' - - if (this.currentElement == null){ - return; // should never occur, this consumeRule is only used in recovery mode - } - // current element should be a block due to the presence of the opening brace - if (!(this.currentElement instanceof RecoveredBlock)){ - if(!(this.currentElement instanceof RecoveredMethod)) { - return; - } - RecoveredMethod rMethod = (RecoveredMethod) this.currentElement; - if(!(rMethod.methodBody == null && rMethod.bracketBalance > 0)) { - return; - } - } - - Argument arg = (Argument)this.astStack[this.astPtr--]; - // convert argument to local variable - LocalDeclaration localDeclaration = new LocalDeclaration(arg.name, arg.sourceStart, arg.sourceEnd); - localDeclaration.type = arg.type; - localDeclaration.declarationSourceStart = arg.declarationSourceStart; - localDeclaration.declarationSourceEnd = arg.declarationSourceEnd; - - this.currentElement = this.currentElement.add(localDeclaration, 0); - this.lastCheckPoint = this.scanner.startPosition; // force to restart at this exact position - this.restartRecovery = true; // request to restart from here on - this.lastIgnoredToken = -1; -} -protected void consumeClassOrInterfaceName() { - pushOnGenericsIdentifiersLengthStack(this.identifierLengthStack[this.identifierLengthPtr]); - pushOnGenericsLengthStack(0); // handle type arguments -} -protected void consumeCompilationUnit() { - // JavaScriptUnit ::= EnterCompilationUnit InternalCompilationUnit - // do nothing by default -} -protected void consumeConditionalExpression(int op) { - // ConditionalExpression ::= ConditionalOrExpression '?' Expression ':' ConditionalExpression - //optimize the push/pop - this.intPtr -= 2;//consume position of the question mark - this.expressionPtr -= 2; - this.expressionLengthPtr -= 2; - this.expressionStack[this.expressionPtr] = - new ConditionalExpression( - this.expressionStack[this.expressionPtr], - this.expressionStack[this.expressionPtr + 1], - this.expressionStack[this.expressionPtr + 2]); -} -protected void consumeDefaultLabel() { - // SwitchLabel ::= 'default' ':' - pushOnAstStack(new CaseStatement(null, this.intStack[this.intPtr--], this.intStack[this.intPtr--])); -} -protected void consumeDefaultModifiers() { - checkComment(); // might update modifiers with AccDeprecated - pushOnIntStack(this.modifiers); // modifiers - pushOnIntStack( - this.modifiersSourceStart >= 0 ? this.modifiersSourceStart : this.scanner.startPosition); - resetModifiers(); -// pushOnExpressionStackLengthStack(0); // no annotation -} -protected void consumeDiet() { - // Diet ::= $empty - checkComment(); - pushOnIntStack(this.modifiersSourceStart); // push the start position of a javadoc comment if there is one - resetModifiers(); - jumpOverMethodBody(); -} -protected void consumeDebuggerStatement() { - pushOnAstStack(new DebuggerStatement(this.intStack[this.intPtr--], this.endStatementPosition)); -} -protected void consumeEmptyArgumentListopt() { - // ArgumentListopt ::= $empty - pushOnExpressionStackLengthStack(0); -} -protected void consumeEmptyArguments() { - // Argumentsopt ::= $empty - final FieldDeclaration fieldDeclaration = (FieldDeclaration) this.astStack[this.astPtr]; - pushOnIntStack(fieldDeclaration.sourceEnd); - pushOnExpressionStackLengthStack(0); -} -protected void consumeEmptyBlockStatementsopt() { - // BlockStatementsopt ::= $empty - pushOnAstLengthStack(0); -} -protected void consumeEmptyCatchesopt() { - // Catchesopt ::= $empty - pushOnAstLengthStack(0); -} -protected void consumeEmptyExpression() { - // Expressionopt ::= $empty - pushOnExpressionStackLengthStack(0); -} -protected void consumeEmptyForInitopt() { - // ForInitopt ::= $empty - pushOnAstLengthStack(0); -} -protected void consumeEmptyForUpdateopt() { - // ForUpdateopt ::= $empty - pushOnExpressionStackLengthStack(0); -} -protected void consumeEmptyInternalCompilationUnit() { - // InternalCompilationUnit ::= $empty - // nothing to do by default - if (this.compilationUnit.isPackageInfo()) { - this.compilationUnit.types = new TypeDeclaration[1]; - // create a fake interface declaration - TypeDeclaration declaration = new TypeDeclaration(compilationUnit.compilationResult); - declaration.name = TypeConstants.PACKAGE_INFO_NAME; - declaration.modifiers = ClassFileConstants.AccDefault; - this.compilationUnit.types[0] = declaration; - declaration.javadoc = this.compilationUnit.javadoc; - } -} -protected void consumeEmptyProgramElements() { - pushOnAstLengthStack(0); -} -protected void consumeEmptyObjectLiteral() { - ObjectLiteral objectLiteral = new ObjectLiteral(); - objectLiteral.sourceEnd = this.endStatementPosition; - objectLiteral.sourceStart = this.intStack[this.intPtr--]; - - pushOnExpressionStack(objectLiteral); -} -protected void consumeEmptyPropertySetParameterList() { - pushOnExpressionStackLengthStack(0); -} -protected void consumeEmptyStatement() { - this.intPtr--; - // EmptyStatement ::= ';' - char[] source = this.scanner.source; - if (this.endStatementPosition >= source.length) { - // this would be inserted as a fake empty statement - pushOnAstStack(new EmptyStatement(this.endStatementPosition, this.endStatementPosition)); - return; - } - int sourceStart = this.endStatementPosition; - - if (source[this.endStatementPosition] != ';') { - if(source.length > 5) { - int c1 = 0, c2 = 0, c3 = 0, c4 = 0; - int pos = this.endStatementPosition - 4; - while (source[pos] == 'u') { - pos--; - } - if (source[pos] == '\\' && - !((c1 = ScannerHelper.getNumericValue(source[this.endStatementPosition - 3])) > 15 - || c1 < 0 - || (c2 = ScannerHelper.getNumericValue(source[this.endStatementPosition - 2])) > 15 - || c2 < 0 - || (c3 = ScannerHelper.getNumericValue(source[this.endStatementPosition - 1])) > 15 - || c3 < 0 - || (c4 = ScannerHelper.getNumericValue(source[this.endStatementPosition])) > 15 - || c4 < 0) && - ((char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4)) == ';'){ - // we have a Unicode for the ';' (/u003B) - sourceStart = pos; - } - } - } - if (this.astPtr > -1) { - if (this.astStack[this.astPtr] instanceof IDoStatement) { - ASTNode node = this.astStack[this.astPtr]; - node.setSourceEnd(this.endStatementPosition); - pushOnAstLengthStack(0); - return; - } - } - pushOnAstStack(new EmptyStatement(sourceStart, this.endStatementPosition)); -} -protected void consumeEmptySwitchBlock() { - // SwitchBlock ::= '{' '}' - pushOnAstLengthStack(0); -} -protected void consumeEnterCompilationUnit() { - // EnterCompilationUnit ::= $empty - // do nothing by default -} -protected void consumeEnterVariable() { - // EnterVariable ::= $empty - // do nothing by default - checkComment(); - resetModifiers(); - - char[] identifierName = this.identifierStack[this.identifierPtr]; - long namePosition = this.identifierPositionStack[this.identifierPtr]; -// int extendedDimension = this.intStack[this.intPtr--]; - AbstractVariableDeclaration declaration; - // create the ast node -// boolean isLocalDeclaration = this.nestedMethod[this.nestedType] != 0; -// if (isLocalDeclaration) { -// // create the local variable declarations - declaration = - this.createLocalDeclaration(identifierName, (int) (namePosition >>> 32), (int) namePosition); -// } else { - // create the field declaration -// declaration = -// this.createFieldDeclaration(identifierName, (int) (namePosition >>> 32), (int) namePosition); -// } - - this.identifierPtr--; - this.identifierLengthPtr--; -// TypeReference type; - int variableIndex = this.variablesCounter[this.nestedType]; -// int typeDim = 0; - if (variableIndex == 0) { - // first variable of the declaration (FieldDeclaration or LocalDeclaration) -// if (isLocalDeclaration) { -// declaration.declarationSourceStart = this.intStack[this.intPtr--]; -// declaration.modifiers = this.intStack[this.intPtr--]; -// // consume annotations -// int length; -// if ((length = this.expressionLengthStack[this.expressionLengthPtr--]) != 0) { -// System.arraycopy( -// this.expressionStack, -// (this.expressionPtr -= length) + 1, -// declaration.annotations = new Annotation[length], -// 0, -// length); -// } -// type = getTypeReference(typeDim = this.intStack[this.intPtr--]); // type dimension -// if (declaration.declarationSourceStart == -1) { -// // this is true if there is no modifiers for the local variable declaration -// declaration.declarationSourceStart = type.sourceStart; -// } -// pushOnAstStack(type); -// } else { -// type = getTypeReference(typeDim = this.intStack[this.intPtr--]); // type dimension -// pushOnAstStack(type); - int modifiersStart = this.intStack[this.intPtr--]; - declaration.modifiers = this.intStack[this.intPtr--]; - int varPosition = this.intStack[this.intPtr--]; - declaration.declarationSourceStart=(modifiersStart>=0)?modifiersStart:varPosition; - this.expressionLengthPtr--; - - // Store javadoc only on first declaration as it is the same for all ones - LocalDeclaration fieldDeclaration = (LocalDeclaration) declaration; - fieldDeclaration.javadoc = this.javadoc; - this.javadoc = null; -// } - } else { -// type = (TypeReference) this.astStack[this.astPtr - variableIndex]; -// typeDim = type.dimensions(); - AbstractVariableDeclaration previousVariable = - (AbstractVariableDeclaration) this.astStack[this.astPtr]; - declaration.declarationSourceStart = previousVariable.declarationSourceStart; - declaration.modifiers = previousVariable.modifiers; -// final Annotation[] annotations = previousVariable.annotations; -// if (annotations != null) { -// final int annotationsLength = annotations.length; -// System.arraycopy(annotations, 0, declaration.annotations = new Annotation[annotationsLength], 0, annotationsLength); -// } - } - -// if (extendedDimension == 0) { -// declaration.type = type; -// } else { -// int dimension = typeDim + extendedDimension; -// declaration.type = this.copyDims(type, dimension); -// } - this.variablesCounter[this.nestedType]++; - pushOnAstStack(declaration); - // recovery - if (this.currentElement != null) { - if (!(this.currentElement instanceof RecoveredUnit) - && (this.currentToken == TokenNameDOT - //|| declaration.modifiers != 0 - || (Util.getLineNumber(declaration.sourceStart, this.scanner.lineEnds, 0, this.scanner.linePtr) - != Util.getLineNumber((int) (namePosition >>> 32), this.scanner.lineEnds, 0, this.scanner.linePtr)))){ - this.lastCheckPoint = (int) (namePosition >>> 32); - this.restartRecovery = true; - return; - } -// if (isLocalDeclaration){ -// LocalDeclaration localDecl = (LocalDeclaration) this.astStack[this.astPtr]; -// this.lastCheckPoint = localDecl.sourceEnd + 1; -// this.currentElement = this.currentElement.add(localDecl, 0); -// } else { - LocalDeclaration fieldDecl = (LocalDeclaration) this.astStack[this.astPtr]; - this.lastCheckPoint = fieldDecl.sourceEnd + 1; - this.currentElement = this.currentElement.add(fieldDecl, 0); -// } - this.lastIgnoredToken = -1; - } -} -protected void consumeEqualityExpression(int op) { - // EqualityExpression ::= EqualityExpression '==' RelationalExpression - // EqualityExpression ::= EqualityExpression '!=' RelationalExpression - - //optimize the push/pop - - this.expressionPtr--; - this.expressionLengthPtr--; - this.expressionStack[this.expressionPtr] = - new EqualExpression( - this.expressionStack[this.expressionPtr], - this.expressionStack[this.expressionPtr + 1], - op); -} -protected void consumeExitTryBlock() { - //ExitTryBlock ::= $empty - if(this.currentElement != null) { - this.restartRecovery = true; - } -} -protected void consumeExitVariableWithInitialization() { - // ExitVariableWithInitialization ::= $empty - // do nothing by default - this.expressionLengthPtr--; - AbstractVariableDeclaration variableDecl = (AbstractVariableDeclaration) this.astStack[this.astPtr]; - variableDecl.initialization = this.expressionStack[this.expressionPtr--]; - // we need to update the declarationSourceEnd of the local variable declaration to the - // source end position of the initialization expression - variableDecl.declarationSourceEnd = variableDecl.initialization.sourceEnd; - variableDecl.declarationEnd = variableDecl.initialization.sourceEnd; - - this.recoveryExitFromVariable(); -} -protected void consumeExitVariableWithoutInitialization() { - // ExitVariableWithoutInitialization ::= $empty - // do nothing by default - - AbstractVariableDeclaration variableDecl = (AbstractVariableDeclaration) this.astStack[this.astPtr]; - variableDecl.declarationSourceEnd = variableDecl.declarationEnd; - if(this.currentElement != null && this.currentElement instanceof RecoveredField) { - if(this.endStatementPosition > variableDecl.sourceEnd) { - this.currentElement.updateSourceEndIfNecessary(this.endStatementPosition); - } - } - this.recoveryExitFromVariable(); -} -protected void consumeExpressionStatement() { - // ExpressionStatement ::= StatementExpression ';' - this.expressionLengthPtr--; - Expression expression = this.expressionStack[this.expressionPtr--]; - expression.statementEnd = this.endStatementPosition; - pushOnAstStack(expression); -} -protected void consumeForceNoDiet() { - // ForceNoDiet ::= $empty - this.dietInt++; -} -protected void consumeForInit() { - // ForInit ::= StatementExpressionList - pushOnAstLengthStack(-1); -} -protected void consumeFormalParameter(boolean isVarArgs) { - // FormalParameter ::= Type VariableDeclaratorId ==> false - // FormalParameter ::= Modifiers Type VariableDeclaratorId ==> true - /* - this.astStack : - this.identifierStack : type identifier - this.intStack : dim dim - ==> - this.astStack : Argument - this.identifierStack : - this.intStack : - */ - - this.identifierLengthPtr--; - char[] identifierName = this.identifierStack[this.identifierPtr]; - long namePositions = this.identifierPositionStack[this.identifierPtr--]; -// int extendedDimensions = this.intStack[this.intPtr--]; -// int endOfEllipsis = 0; -// if (isVarArgs) { -// endOfEllipsis = this.intStack[this.intPtr--]; -// } -// int firstDimensions = this.intStack[this.intPtr--]; -// final int typeDimensions = firstDimensions + extendedDimensions; -// TypeReference type = getTypeReference(typeDimensions); -// if (isVarArgs) { -// type = copyDims(type, typeDimensions + 1); -// if (extendedDimensions == 0) { -// type.sourceEnd = endOfEllipsis; -// } -// type.bits |= ASTNode.IsVarArgs; // set isVarArgs -// } -// int modifierPositions = this.intStack[this.intPtr--]; -// this.intPtr--; - int modifierPositions=(int) (namePositions >>> 32); - Argument arg = - new Argument( - identifierName, - namePositions, - null, - ClassFileConstants.AccDefault); -// this.intStack[this.intPtr + 1] & ~ClassFileConstants.AccDeprecated); // modifiers - arg.declarationSourceStart = modifierPositions; - // consume annotations -// int length; -// if ((length = this.expressionLengthStack[this.expressionLengthPtr--]) != 0) { -// System.arraycopy( -// this.expressionStack, -// (this.expressionPtr -= length) + 1, -// arg.annotations = new Annotation[length], -// 0, -// length); -// } - if (this.options.inferOptions.saveArgumentComments) - { - handleArgumentComment(arg); - } - - - pushOnAstStack(arg); - - /* if incomplete method header, this.listLength counter will not have been reset, - indicating that some arguments are available on the stack */ - this.listLength++; -} - -protected void handleArgumentComment(Argument arg) -{ - int lastComment = this.scanner.commentPtr; - -// if (this.modifiersSourceStart >= 0) { -// // eliminate comments located after modifierSourceStart if positionned -// while (lastComment >= 0 && this.scanner.commentStarts[lastComment] > this.modifiersSourceStart) lastComment--; -// } - if (lastComment >= 0 && this.scanner.commentStops[0]<0) { - // consider all remaining leading comments to be part of current declaration - int start=this.scanner.commentStarts[0]; - int end=this.scanner.commentStops[0]; - arg.comment=CharOperation.subarray(this.scanner.source, start+2, (-end)-2); - this.scanner.commentPtr=-1; - } -} -protected void consumeFormalParameterList() { - // FormalParameterList ::= FormalParameterList ',' FormalParameter - optimizedConcatNodeLists(); -} -protected void consumeFormalParameterListopt() { - // FormalParameterListopt ::= $empty - pushOnAstLengthStack(0); -} -protected void consumeGetSetPropertyAssignment(boolean isSetter) { - // remove two expressions property name/remove an optional property set parameter list - // remove all statement from function body - this.intPtr -= 2; // int pushed by consumeNestedMethod() and consumeOpenBlock() (called inside consumeMethodBody()) - int length = this.astLengthStack[this.astLengthPtr--]; - Statement[] statements = new Statement[length]; - this.astPtr -= length; - System.arraycopy( - this.astStack, - this.astPtr + 1, - statements, - 0, - length); - Expression varName = null; - if (isSetter) { - this.expressionLengthPtr--; - varName = this.expressionStack[this.expressionPtr--]; - } - // property name - this.expressionLengthPtr--; - Expression propertyName = this.expressionStack[this.expressionPtr--]; - // set or get - this.expressionLengthPtr--; - Expression expression = this.expressionStack[this.expressionPtr--]; - int end = this.endStatementPosition; - int start = expression.sourceStart; - - if (expression instanceof SingleNameReference) { - SingleNameReference reference = (SingleNameReference) expression; - if (isSetter) { - if (!CharOperation.equals(reference.token, "set".toCharArray())) { - // report error - this.problemReporter.invalidValueForGetterSetter(expression, true); - } - } else { - if (!CharOperation.equals(reference.token, "get".toCharArray())) { - // report error - this.problemReporter.invalidValueForGetterSetter(expression, false); - } - } - } - ObjectGetterSetterField getterSetterField = new ObjectGetterSetterField(propertyName, statements, varName, start, end); - pushOnExpressionStack(getterSetterField); -} -protected void consumeInternalCompilationUnitWithTypes() { - // InternalCompilationUnit ::= PackageDeclaration ImportDeclarations ReduceImports TypeDeclarations - // InternalCompilationUnit ::= PackageDeclaration TypeDeclarations - // InternalCompilationUnit ::= TypeDeclarations - // InternalCompilationUnit ::= ImportDeclarations ReduceImports TypeDeclarations - // consume type declarations - int length; - if ((length = this.astLengthStack[this.astLengthPtr--]) != 0) { - this.compilationUnit.statements = new ProgramElement[length]; - this.astPtr -= length; - System.arraycopy(this.astStack, this.astPtr + 1, this.compilationUnit.statements, 0, length); - } -} -protected void consumeLabel() { - // Do nothing -} -protected void consumeLeftParen() { - // PushLPAREN ::= '(' - pushOnIntStack(this.lParenPos); -} -protected void consumeLocalVariableDeclaration() { - // LocalVariableDeclaration ::= Modifiers Type VariableDeclarators ';' - - /* - this.astStack : - this.expressionStack: Expression Expression ...... Expression - this.identifierStack : type identifier identifier ...... identifier - this.intStack : typeDim dim dim dim - ==> - this.astStack : FieldDeclaration FieldDeclaration ...... FieldDeclaration - this.expressionStack : - this.identifierStack : - this.intStack : - - */ -// int variableDeclaratorsCounter = this.astLengthStack[this.astLengthPtr]; -// -// // update the this.astStack, this.astPtr and this.astLengthStack -// int startIndex = this.astPtr - this.variablesCounter[this.nestedType] + 1; -// System.arraycopy( -// this.astStack, -// startIndex, -// this.astStack, -// startIndex - 1, -// variableDeclaratorsCounter); -// this.astPtr--; // remove the type reference -// this.astLengthStack[--this.astLengthPtr] = variableDeclaratorsCounter; - this.variablesCounter[this.nestedType] = 0; -} -protected void consumeLocalVariableDeclarationStatement() { - // LocalVariableDeclarationStatement ::= LocalVariableDeclaration ';' - // see blockReal in case of change: duplicated code - // increment the amount of declared variables for this block - this.realBlockStack[this.realBlockPtr]++; - - // update source end to include the semi-colon - int variableDeclaratorsCounter = this.astLengthStack[this.astLengthPtr]; - AbstractVariableDeclaration nextDeclaration =null; - for (int i = 0; i - this.astStack : FunctionDeclaration - this.identifierStack : - this.intStack : - */ - - - this.nestedType--; - int length; - if (isNotAbstract) { - // pop the position of the { (body of the method) pushed in block decl - this.intPtr--; - this.intPtr--; - } - - int explicitDeclarations = 0; - Statement[] statements = null; - if (isNotAbstract) { - //statements - explicitDeclarations = this.realBlockStack[this.realBlockPtr--]; - if ((length = this.astLengthStack[this.astLengthPtr--]) != 0) { - System.arraycopy( - this.astStack, - (this.astPtr -= length) + 1, - statements = new Statement[length], - 0, - length); - } - } - - // now we know that we have a method declaration at the top of the ast stack - MethodDeclaration md = (MethodDeclaration) this.astStack[this.astPtr]; - md.statements = statements; - md.explicitDeclarations = explicitDeclarations; - - // cannot be done in consumeMethodHeader because we have no idea whether or not there - // is a body when we reduce the method header - if (!isNotAbstract) { //remember the fact that the method has a semicolon body - md.modifiers |= ExtraCompilerModifiers.AccSemicolonBody; - } else if (!(this.diet && this.dietInt == 0) && statements == null && !containsComment(md.bodyStart, this.endPosition)) { - md.bits |= ASTNode.UndocumentedEmptyBlock; - } - // store the this.endPosition (position just before the '}') in case there is - // a trailing comment behind the end of the method - md.bodyEnd = this.endPosition; - md.sourceEnd = this.endPosition; - md.declarationSourceEnd = flushCommentsDefinedPriorTo(this.endStatementPosition); -} -protected void consumeMethodHeader() { - // MethodHeader ::= MethodHeaderName MethodHeaderParameters MethodHeaderExtendedDims ThrowsClauseopt - // AnnotationMethodHeader ::= AnnotationMethodHeaderName FormalParameterListopt MethodHeaderRightParen MethodHeaderExtendedDims AnnotationMethodHeaderDefaultValueopt - // RecoveryMethodHeader ::= RecoveryMethodHeaderName FormalParameterListopt MethodHeaderRightParen MethodHeaderExtendedDims AnnotationMethodHeaderDefaultValueopt - // RecoveryMethodHeader ::= RecoveryMethodHeaderName FormalParameterListopt MethodHeaderRightParen MethodHeaderExtendedDims MethodHeaderThrowsClause - - // retrieve end position of method declarator - AbstractMethodDeclaration method = (AbstractMethodDeclaration)this.astStack[this.astPtr]; - - if (this.currentToken == TokenNameLBRACE){ - method.bodyStart = this.scanner.currentPosition; - } - else if (currentToken != TokenNameSEMICOLON) { // insert semicolon - currentToken = TokenNameSEMICOLON; - scanner.pushBack(); - } - // recovery - if (this.currentElement != null){ -// if(method.isAnnotationMethod()) { -// method.modifiers |= AccSemicolonBody; -// method.declarationSourceEnd = this.scanner.currentPosition-1; -// method.bodyEnd = this.scanner.currentPosition-1; -// this.currentElement = this.currentElement.parent; -// } else - if (this.currentToken == TokenNameSEMICOLON /*&& !method.isAnnotationMethod()*/){ - method.modifiers |= ExtraCompilerModifiers.AccSemicolonBody; - method.declarationSourceEnd = this.scanner.currentPosition-1; - method.bodyEnd = this.scanner.currentPosition-1; -// if (this.currentElement.parseTree() == method && this.currentElement.parent != null) { -// this.currentElement = this.currentElement.parent; -// } - } else if(this.currentToken == TokenNameLBRACE) { - if (this.currentElement instanceof RecoveredMethod && - ((RecoveredMethod)this.currentElement).methodDeclaration != method) { - this.ignoreNextOpeningBrace = true; - this.currentElement.bracketBalance++; - } } - this.restartRecovery = true; // used to avoid branching back into the regular automaton - } -} -protected void consumeMethodHeaderName(boolean isAnonymous) { - // MethodHeaderName ::= Modifiersopt Type 'Identifier' '(' - // AnnotationMethodHeaderName ::= Modifiersopt Type 'Identifier' '(' - // RecoveryMethodHeaderName ::= Modifiersopt Type 'Identifier' '(' - MethodDeclaration md = null; -// if(isAnnotationMethod) { -// md = new AnnotationMethodDeclaration(this.compilationUnit.compilationResult); -// this.recordStringLiterals = false; -// } else { - md = new MethodDeclaration(this.compilationUnit.compilationResult); -// } - - md.exprStackPtr=this.expressionPtr; - //name - long selectorSource =-1; - if (!isAnonymous) - { - md.selector = this.identifierStack[this.identifierPtr]; - selectorSource = this.identifierPositionStack[this.identifierPtr--]; - this.identifierLengthPtr--; - } - - - if (this.nestedType>0) - markEnclosingMemberWithLocalType(); - - //type -// md.returnType = getTypeReference(this.intStack[this.intPtr--]); - //modifiers - int functionPos = this.intStack[this.intPtr--]; - int modifierPos = this.intStack[this.intPtr--]; - md.declarationSourceStart = (functionPos>modifierPos)? modifierPos:functionPos; - md.modifiers = this.intStack[this.intPtr--]; - // consume annotations -// int length; -// if ((length = this.expressionLengthStack[this.expressionLengthPtr--]) != 0) { -// System.arraycopy( -// this.expressionStack, -// (this.expressionPtr -= length) + 1, -// md.annotations = new Annotation[length], -// 0, -// length); -// } - // javadoc - md.javadoc = this.javadoc; - this.javadoc = null; - - //highlight starts at selector start - if (selectorSource>=0) - md.sourceStart = (int) (selectorSource >>> 32); - else - md.sourceStart=md.declarationSourceStart; - pushOnAstStack(md); - md.sourceEnd = this.lParenPos; - md.bodyStart = this.lParenPos+1; - this.listLength = 0; // initialize this.listLength before reading parameters/throws - - - - - incrementNestedType(); - - // recovery - if (this.currentElement != null){ - if (this.currentElement instanceof RecoveredType - //|| md.modifiers != 0 - || true/* (this.scanner.getLineNumber(md.returnType.sourceStart) - == this.scanner.getLineNumber(md.sourceStart))*/){ - this.lastCheckPoint = md.bodyStart; - this.currentElement = this.currentElement.add(md, 0); - this.lastIgnoredToken = -1; - } else { - this.lastCheckPoint = md.sourceStart; - this.restartRecovery = true; - } - } -} -protected void consumeMethodHeaderRightParen() { - // MethodHeaderParameters ::= FormalParameterListopt ')' - int length = this.astLengthStack[this.astLengthPtr--]; - this.astPtr -= length; - AbstractMethodDeclaration md = (AbstractMethodDeclaration) this.astStack[this.astPtr]; - md.sourceEnd = this.rParenPos; - //arguments - if (length != 0) { - System.arraycopy( - this.astStack, - this.astPtr + 1, - md.arguments = new Argument[length], - 0, - length); - } - md.bodyStart = this.rParenPos+1; - this.listLength = 0; // reset this.listLength after having read all parameters - // recovery - if (this.currentElement != null){ - this.lastCheckPoint = md.bodyStart; - if (this.currentElement.parseTree() == md) return; - - // might not have been attached yet - in some constructor scenarii - if (md.isConstructor()){ - if ((length != 0) - || (this.currentToken == TokenNameLBRACE) - || (this.currentToken == TokenNamethrows)){ - this.currentElement = this.currentElement.add(md, 0); - this.lastIgnoredToken = -1; - } - } - } -} -protected void consumeModifiers2() { - this.expressionLengthStack[this.expressionLengthPtr - 1] += this.expressionLengthStack[this.expressionLengthPtr--]; -} -protected void consumeNestedMethod() { - // NestedMethod ::= $empty - jumpOverMethodBody(); - this.nestedMethod[this.nestedType] ++; - pushOnIntStack(this.scanner.currentPosition); - consumeOpenBlock(); -} -protected void consumeNestedType() { - // NestedType ::= $empty - incrementNestedType(); -} -protected void incrementNestedType() { - int length = this.nestedMethod.length; - if (++this.nestedType >= length) { - System.arraycopy( - this.nestedMethod, 0, - this.nestedMethod = new int[length + 30], 0, - length); - // increase the size of the variablesCounter as well. It has to be consistent with the size of the nestedMethod collection - System.arraycopy( - this.variablesCounter, 0, - this.variablesCounter = new int[length + 30], 0, - length); - } - this.nestedMethod[this.nestedType] = 0; - this.variablesCounter[this.nestedType] = 0; -} -protected void consumeNewExpression() { - classInstanceCreation(false, true); -} -protected void consumeNewMemberExpressionWithArguments() { - classInstanceCreation(false, false); -} -protected void consumeOpenBlock() { - // OpenBlock ::= $empty - - pushOnIntStack(this.scanner.startPosition); - int stackLength = this.realBlockStack.length; - if (++this.realBlockPtr >= stackLength) { - System.arraycopy( - this.realBlockStack, 0, - this.realBlockStack = new int[stackLength + StackIncrement], 0, - stackLength); - } - this.realBlockStack[this.realBlockPtr] = 0; -} -protected void consumePostfixExpression() { - // PostfixExpression ::= Name - pushOnExpressionStack(getUnspecifiedReferenceOptimized()); -} -protected void consumePrimaryNoNewArray() { - // PrimaryNoNewArray ::= PushLPAREN Expression PushRPAREN - final Expression parenthesizedExpression = this.expressionStack[this.expressionPtr]; - updateSourcePosition(parenthesizedExpression); - int numberOfParenthesis = (parenthesizedExpression.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT; - parenthesizedExpression.bits &= ~ASTNode.ParenthesizedMASK; - parenthesizedExpression.bits |= (numberOfParenthesis + 1) << ASTNode.ParenthesizedSHIFT; -} -protected void consumePrimaryNoNewArrayThis() { - // PrimaryNoNewArray ::= 'this' - pushOnExpressionStack(new ThisReference(this.intStack[this.intPtr--], this.endPosition)); -} -protected void consumePrimarySimpleName() { - // PrimaryNoNewArray ::= SimpleName - pushOnExpressionStack(getUnspecifiedReferenceOptimized()); -} -protected void consumePropertyAssignment() { - // MemberValuePair ::= SimpleName '=' MemberValue - this.modifiersSourceStart=-1; - this.checkComment(); - this.resetModifiers(); - - Expression value = this.expressionStack[this.expressionPtr--]; - this.expressionLengthPtr--; - - Expression field = this.expressionStack[this.expressionPtr--]; - this.expressionLengthPtr--; - int end = value.sourceEnd; - int start = field.sourceStart; - - ObjectLiteralField literalField = new ObjectLiteralField(field, value, start, end); - pushOnExpressionStack(literalField); - - if (this.javadoc!=null) { - literalField.javaDoc = this.javadoc; - } - else if (value instanceof FunctionExpression) - { - MethodDeclaration methodDeclaration = ((FunctionExpression)value).methodDeclaration; - literalField.javaDoc=methodDeclaration.javadoc; - methodDeclaration.javadoc=null; - } - this.javadoc = null; - - // discard obsolete comments while inside methods or fields initializer (see bug 74369) - if (!(this.diet && this.dietInt==0) && this.scanner.commentPtr >= 0) { - flushCommentsDefinedPriorTo(literalField.sourceEnd); - } - resetModifiers(); -} -protected void consumePropertyName() { - pushOnExpressionStack(getUnspecifiedReferenceOptimized()); -} -protected void consumePropertyNameAndValueList() { - concatExpressionLists(); -} -protected void consumePropertySetParameterList() { - pushOnExpressionStack(getUnspecifiedReferenceOptimized()); -} -protected void consumePushLeftBrace() { - pushOnIntStack(this.endPosition); // modifiers -} - -protected void consumeArrayLiteralHeader() { - pushOnIntStack(this.endPosition); // modifiers - pushOnIntStack(0); // numExprs -} -protected void consumePushModifiers() { - checkComment(); // might update modifiers with AccDeprecated - pushOnIntStack(this.modifiers); // modifiers - pushOnIntStack(this.modifiersSourceStart); - resetModifiers(); - pushOnExpressionStackLengthStack(0); -} -protected void consumePushPosition() { - // for source managment purpose - // PushPosition ::= $empty - pushOnIntStack(this.endPosition); -} -protected void consumeQualifiedName() { - // QualifiedName ::= Name '.' SimpleName - /*back from the recursive loop of QualifiedName. - Updates identifier length into the length stack*/ - - this.identifierLengthStack[--this.identifierLengthPtr]++; -} -protected void consumeRecoveryMethodHeaderName() { - // this method is call only inside recovery -// boolean isAnnotationMethod = false; -// if(this.currentElement instanceof RecoveredType) { -// isAnnotationMethod = (((RecoveredType)this.currentElement).typeDeclaration.modifiers & ClassFileConstants.AccAnnotation) != 0; -// } else { -// RecoveredType recoveredType = this.currentElement.enclosingType(); -// if(recoveredType != null) { -// isAnnotationMethod = (recoveredType.typeDeclaration.modifiers & ClassFileConstants.AccAnnotation) != 0; -// } -// } - this.consumeMethodHeaderName(false); -} -protected void consumeRestoreDiet() { - // RestoreDiet ::= $empty - this.dietInt--; -} -protected void consumeRightParen() { - // PushRPAREN ::= ')' - pushOnIntStack(this.rParenPos); -} -private void consumeFunctionExpression() { - - consumeMethodDeclaration(true); - MethodDeclaration md = (MethodDeclaration) this.astStack[this.astPtr--]; - this.astLengthPtr--; - FunctionExpression funcExpr=new FunctionExpression(md); - funcExpr.sourceEnd=md.declarationSourceEnd; - funcExpr.sourceStart=md.declarationSourceStart; - pushOnExpressionStack(funcExpr); -} - -private void consumeStatementForIn() { -// int length; - Expression collection = null; - Statement iteratorVar; - boolean scope = true; - - //statements - this.astLengthPtr--; - Statement statement = (Statement) this.astStack[this.astPtr--]; - - if (this.expressionLengthStack[this.expressionLengthPtr--] != 0) - collection = this.expressionStack[this.expressionPtr--]; - - this.astLengthPtr--; - iteratorVar = (Statement) this.astStack[this.astPtr--]; - pushOnAstStack( - new ForInStatement( - iteratorVar, - collection, - statement, - scope, - this.intStack[this.intPtr--], - this.endStatementPosition)); - -} - -private void consumeArrayLiteralList() { - concatExpressionLists(); - this.intStack[this.intPtr]&= ~(UNCONSUMED_ELISION|UNCONSUMED_LIT_ELEMENT); -} -private void consumeArrayLiteralListOne() { - if ( (this.intStack[this.intPtr]&UNCONSUMED_ELISION)!=0) - { - concatExpressionLists(); - this.intStack[this.intPtr]&= ~(UNCONSUMED_ELISION|UNCONSUMED_LIT_ELEMENT); - } - - -} - -private void consumeListExpression() { - this.expressionPtr--; - this.expressionLengthPtr--; - Expression expr1 = this.expressionStack[this.expressionPtr]; - Expression expr2 = this.expressionStack[this.expressionPtr + 1]; - this.expressionStack[this.expressionPtr] = - new ListExpression( - expr1, - expr2); - -} - -protected void consumePostDoc() { - - if (this.options.inferOptions.docLocation==InferOptions.DOC_LOCATION_AFTER) - { - - } -} - -// This method is part of an automatic generation : do NOT edit-modify -protected void consumeRule(int act) { - switch ( act ) { - case 23 : if (DEBUG) { System.out.println("CompilationUnit ::= EnterCompilationUnit..."); } //$NON-NLS-1$ - consumeCompilationUnit(); - break; - - case 24 : if (DEBUG) { System.out.println("InternalCompilationUnit ::= ProgramElements"); } //$NON-NLS-1$ - consumeInternalCompilationUnitWithTypes(); - break; - - case 25 : if (DEBUG) { System.out.println("InternalCompilationUnit ::="); } //$NON-NLS-1$ - consumeEmptyInternalCompilationUnit(); - break; - - case 26 : if (DEBUG) { System.out.println("EnterCompilationUnit ::="); } //$NON-NLS-1$ - consumeEnterCompilationUnit(); - break; - - case 30 : if (DEBUG) { System.out.println("CatchHeader ::= catch LPAREN FormalParameter RPAREN..."); } //$NON-NLS-1$ - consumeCatchHeader(); - break; - - case 32 : if (DEBUG) { System.out.println("VariableDeclarators ::= VariableDeclarators COMMA..."); } //$NON-NLS-1$ - consumeVariableDeclarators(); - break; - - case 34 : if (DEBUG) { System.out.println("VariableDeclaratorsNoIn ::= VariableDeclaratorsNoIn COMMA"); } //$NON-NLS-1$ - consumeVariableDeclarators(); - break; - - case 39 : if (DEBUG) { System.out.println("EnterVariable ::="); } //$NON-NLS-1$ - consumeEnterVariable(); - break; - - case 40 : if (DEBUG) { System.out.println("ExitVariableWithInitialization ::="); } //$NON-NLS-1$ - consumeExitVariableWithInitialization(); - break; - - case 41 : if (DEBUG) { System.out.println("ExitVariableWithoutInitialization ::="); } //$NON-NLS-1$ - consumeExitVariableWithoutInitialization(); - break; - - case 42 : if (DEBUG) { System.out.println("ForceNoDiet ::="); } //$NON-NLS-1$ - consumeForceNoDiet(); - break; - - case 43 : if (DEBUG) { System.out.println("RestoreDiet ::="); } //$NON-NLS-1$ - consumeRestoreDiet(); - break; - - case 47 : if (DEBUG) { System.out.println("FunctionExpression ::= FunctionExpressionHeader..."); } //$NON-NLS-1$ - // set to true to consume a method with a body - consumeFunctionExpression(); - break; - - case 48 : if (DEBUG) { System.out.println("FunctionExpressionHeader ::= FunctionExpressionHeaderName"); } //$NON-NLS-1$ - consumeMethodHeader(); - break; - - case 49 : if (DEBUG) { System.out.println("FunctionExpressionHeaderName ::= Modifiersopt function..."); } //$NON-NLS-1$ - consumeMethodHeaderName(false); - break; - - case 50 : if (DEBUG) { System.out.println("FunctionExpressionHeaderName ::= Modifiersopt function..."); } //$NON-NLS-1$ - consumeMethodHeaderName(true); - break; - - case 52 : if (DEBUG) { System.out.println("MethodDeclaration ::= MethodHeader MethodBody"); } //$NON-NLS-1$ - // set to true to consume a method with a body - consumeMethodDeclaration(true); - break; - - case 53 : if (DEBUG) { System.out.println("AbstractMethodDeclaration ::= MethodHeader SEMICOLON"); } //$NON-NLS-1$ - // set to false to consume a method without body - consumeMethodDeclaration(false); - break; - - case 54 : if (DEBUG) { System.out.println("MethodHeader ::= MethodHeaderName FormalParameterListopt"); } //$NON-NLS-1$ - consumeMethodHeader(); - break; - - case 55 : if (DEBUG) { System.out.println("MethodHeaderName ::= Modifiersopt function Identifier..."); } //$NON-NLS-1$ - consumeMethodHeaderName(false); - break; - - case 56 : if (DEBUG) { System.out.println("MethodHeaderRightParen ::= RPAREN"); } //$NON-NLS-1$ - consumeMethodHeaderRightParen(); - break; - - case 58 : if (DEBUG) { System.out.println("FormalParameterList ::= FormalParameterList COMMA..."); } //$NON-NLS-1$ - consumeFormalParameterList(); - break; - - case 59 : if (DEBUG) { System.out.println("FormalParameter ::= VariableDeclaratorId"); } //$NON-NLS-1$ - consumeFormalParameter(false); - break; - - case 60 : if (DEBUG) { System.out.println("MethodBody ::= NestedMethod LBRACE PostDoc..."); } //$NON-NLS-1$ - consumeMethodBody(); - break; - - case 61 : if (DEBUG) { System.out.println("NestedMethod ::="); } //$NON-NLS-1$ - consumeNestedMethod(); - break; - - case 62 : if (DEBUG) { System.out.println("PostDoc ::="); } //$NON-NLS-1$ - consumePostDoc(); - break; - - case 63 : if (DEBUG) { System.out.println("PushLeftBraceObjectLiteral ::="); } //$NON-NLS-1$ - consumePushLeftBrace(); - break; - - case 64 : if (DEBUG) { System.out.println("Block ::= OpenBlock LBRACE BlockStatementsopt RBRACE"); } //$NON-NLS-1$ - consumeBlock(); - break; - - case 65 : if (DEBUG) { System.out.println("OpenBlock ::="); } //$NON-NLS-1$ - consumeOpenBlock() ; - break; - - case 67 : if (DEBUG) { System.out.println("ProgramElements ::= ProgramElements ProgramElement"); } //$NON-NLS-1$ - consumeProgramElements() ; - break; - - case 70 : if (DEBUG) { System.out.println("BlockStatements ::= BlockStatements BlockStatement"); } //$NON-NLS-1$ - consumeBlockStatements() ; - break; - - case 74 : if (DEBUG) { System.out.println("LocalVariableDeclarationStatement ::=..."); } //$NON-NLS-1$ - consumeLocalVariableDeclarationStatement(); - break; - - case 75 : if (DEBUG) { System.out.println("LocalVariableDeclaration ::= var PushModifiers..."); } //$NON-NLS-1$ - consumeLocalVariableDeclaration(); - break; - - case 76 : if (DEBUG) { System.out.println("LocalVariableDeclarationNoIn ::= var PushModifiers..."); } //$NON-NLS-1$ - consumeLocalVariableDeclaration(); - break; - - case 77 : if (DEBUG) { System.out.println("PushModifiers ::="); } //$NON-NLS-1$ - consumePushModifiers(); - break; - - case 102 : if (DEBUG) { System.out.println("EmptyStatement ::= PushPosition SEMICOLON"); } //$NON-NLS-1$ - consumeEmptyStatement(); - break; - - case 103 : if (DEBUG) { System.out.println("LabeledStatement ::= Label COLON Statement"); } //$NON-NLS-1$ - consumeStatementLabel() ; - break; - - case 104 : if (DEBUG) { System.out.println("LabeledStatementNoShortIf ::= Label COLON..."); } //$NON-NLS-1$ - consumeStatementLabel() ; - break; - - case 105 : if (DEBUG) { System.out.println("Label ::= Identifier"); } //$NON-NLS-1$ - consumeLabel() ; - break; - - case 106 : if (DEBUG) { System.out.println("ExpressionStatement ::= StatementExpression SEMICOLON"); } //$NON-NLS-1$ - consumeExpressionStatement(); - break; - - case 108 : if (DEBUG) { System.out.println("IfThenStatement ::= if LPAREN Expression RPAREN..."); } //$NON-NLS-1$ - consumeStatementIfNoElse(); - break; - - case 109 : if (DEBUG) { System.out.println("IfThenElseStatement ::= if LPAREN Expression RPAREN..."); } //$NON-NLS-1$ - consumeStatementIfWithElse(); - break; - - case 110 : if (DEBUG) { System.out.println("IfThenElseStatementNoShortIf ::= if LPAREN Expression..."); } //$NON-NLS-1$ - consumeStatementIfWithElse(); - break; - - case 111 : if (DEBUG) { System.out.println("IfThenElseStatement ::= if LPAREN Expression RPAREN..."); } //$NON-NLS-1$ - consumeStatementIfWithElse(); - break; - - case 112 : if (DEBUG) { System.out.println("IfThenElseStatementNoShortIf ::= if LPAREN Expression..."); } //$NON-NLS-1$ - consumeStatementIfWithElse(); - break; - - case 113 : if (DEBUG) { System.out.println("SwitchStatement ::= switch LPAREN Expression RPAREN..."); } //$NON-NLS-1$ - consumeStatementSwitch() ; - break; - - case 114 : if (DEBUG) { System.out.println("SwitchBlock ::= LBRACE RBRACE"); } //$NON-NLS-1$ - consumeEmptySwitchBlock() ; - break; - - case 117 : if (DEBUG) { System.out.println("SwitchBlock ::= LBRACE SwitchBlockStatements..."); } //$NON-NLS-1$ - consumeSwitchBlock() ; - break; - - case 119 : if (DEBUG) { System.out.println("SwitchBlockStatements ::= SwitchBlockStatements..."); } //$NON-NLS-1$ - consumeSwitchBlockStatements() ; - break; - - case 120 : if (DEBUG) { System.out.println("SwitchBlockStatement ::= SwitchLabels BlockStatements"); } //$NON-NLS-1$ - consumeSwitchBlockStatement() ; - break; - - case 122 : if (DEBUG) { System.out.println("SwitchLabels ::= SwitchLabels SwitchLabel"); } //$NON-NLS-1$ - consumeSwitchLabels() ; - break; - - case 123 : if (DEBUG) { System.out.println("SwitchLabel ::= case ConstantExpression COLON"); } //$NON-NLS-1$ - consumeCaseLabel(); - break; - - case 124 : if (DEBUG) { System.out.println("SwitchLabel ::= default COLON"); } //$NON-NLS-1$ - consumeDefaultLabel(); - break; - - case 125 : if (DEBUG) { System.out.println("WhileStatement ::= while LPAREN Expression RPAREN..."); } //$NON-NLS-1$ - consumeStatementWhile() ; - break; - - case 126 : if (DEBUG) { System.out.println("WhileStatementNoShortIf ::= while LPAREN Expression..."); } //$NON-NLS-1$ - consumeStatementWhile() ; - break; - - case 127 : if (DEBUG) { System.out.println("WithStatement ::= with LPAREN Expression RPAREN..."); } //$NON-NLS-1$ - consumeStatementWith() ; - break; - - case 128 : if (DEBUG) { System.out.println("WithStatementNoShortIf ::= with LPAREN Expression RPAREN"); } //$NON-NLS-1$ - consumeStatementWith() ; - break; - - case 129 : if (DEBUG) { System.out.println("DoStatement ::= do Statement while LPAREN Expression..."); } //$NON-NLS-1$ - consumeStatementDo() ; - break; - - case 130 : if (DEBUG) { System.out.println("ForStatement ::= for LPAREN ForInitopt SEMICOLON..."); } //$NON-NLS-1$ - consumeStatementFor() ; - break; - - case 131 : if (DEBUG) { System.out.println("ForStatement ::= for LPAREN ForInInit in Expression..."); } //$NON-NLS-1$ - consumeStatementForIn() ; - break; - - case 132 : if (DEBUG) { System.out.println("ForStatementNoShortIf ::= for LPAREN ForInitopt..."); } //$NON-NLS-1$ - consumeStatementFor() ; - break; - - case 133 : if (DEBUG) { System.out.println("ForStatementNoShortIf ::= for LPAREN ForInInit in..."); } //$NON-NLS-1$ - consumeStatementForIn() ; - break; - - case 134 : if (DEBUG) { System.out.println("ForInInit ::= LeftHandSideExpression"); } //$NON-NLS-1$ - consumeForInInit() ; - break; - - case 136 : if (DEBUG) { System.out.println("ForInit ::= ExpressionNoIn"); } //$NON-NLS-1$ - consumeForInit() ; - break; - - case 140 : if (DEBUG) { System.out.println("StatementExpressionList ::= StatementExpressionList..."); } //$NON-NLS-1$ - consumeStatementExpressionList() ; - break; - - case 141 : if (DEBUG) { System.out.println("BreakStatement ::= break SEMICOLON"); } //$NON-NLS-1$ - consumeStatementBreak() ; - break; - - case 142 : if (DEBUG) { System.out.println("BreakStatement ::= break Identifier SEMICOLON"); } //$NON-NLS-1$ - consumeStatementBreakWithLabel() ; - break; - - case 143 : if (DEBUG) { System.out.println("ContinueStatement ::= continue SEMICOLON"); } //$NON-NLS-1$ - consumeStatementContinue() ; - break; - - case 144 : if (DEBUG) { System.out.println("ContinueStatement ::= continue Identifier SEMICOLON"); } //$NON-NLS-1$ - consumeStatementContinueWithLabel() ; - break; - - case 145 : if (DEBUG) { System.out.println("ReturnStatement ::= return Expressionopt SEMICOLON"); } //$NON-NLS-1$ - consumeStatementReturn() ; - break; - - case 146 : if (DEBUG) { System.out.println("ThrowStatement ::= throw Expression SEMICOLON"); } //$NON-NLS-1$ - consumeStatementThrow(); - break; - - case 147 : if (DEBUG) { System.out.println("TryStatement ::= try TryBlock Catches"); } //$NON-NLS-1$ - consumeStatementTry(false); - break; - - case 148 : if (DEBUG) { System.out.println("TryStatement ::= try TryBlock Catchesopt Finally"); } //$NON-NLS-1$ - consumeStatementTry(true); - break; - - case 150 : if (DEBUG) { System.out.println("ExitTryBlock ::="); } //$NON-NLS-1$ - consumeExitTryBlock(); - break; - - case 152 : if (DEBUG) { System.out.println("Catches ::= Catches CatchClause"); } //$NON-NLS-1$ - consumeCatches(); - break; - - case 153 : if (DEBUG) { System.out.println("CatchClause ::= catch LPAREN FormalParameter RPAREN..."); } //$NON-NLS-1$ - consumeStatementCatch() ; - break; - - case 155 : if (DEBUG) { System.out.println("DebuggerStatement ::= debugger SEMICOLON"); } //$NON-NLS-1$ - consumeDebuggerStatement() ; - break; - - case 156 : if (DEBUG) { System.out.println("PushLPAREN ::= LPAREN"); } //$NON-NLS-1$ - consumeLeftParen(); - break; - - case 157 : if (DEBUG) { System.out.println("PushRPAREN ::= RPAREN"); } //$NON-NLS-1$ - consumeRightParen(); - break; - - case 162 : if (DEBUG) { System.out.println("PrimaryNoNewArray ::= SimpleName"); } //$NON-NLS-1$ - consumePrimarySimpleName(); - break; - - case 163 : if (DEBUG) { System.out.println("PrimaryNoNewArray ::= this"); } //$NON-NLS-1$ - consumePrimaryNoNewArrayThis(); - break; - - case 164 : if (DEBUG) { System.out.println("PrimaryNoNewArray ::= PushLPAREN Expression PushRPAREN"); } //$NON-NLS-1$ - consumePrimaryNoNewArray(); - break; - - case 165 : if (DEBUG) { System.out.println("ObjectLiteral ::= LBRACE PushLeftBraceObjectLiteral..."); } //$NON-NLS-1$ - consumeEmptyObjectLiteral(); - break; - - case 166 : if (DEBUG) { System.out.println("ObjectLiteral ::= LBRACE PushLeftBraceObjectLiteral..."); } //$NON-NLS-1$ - consumeObjectLiteral(); - break; - - case 167 : if (DEBUG) { System.out.println("ObjectLiteral ::= LBRACE PushLeftBraceObjectLiteral..."); } //$NON-NLS-1$ - consumeObjectLiteral(); - break; - - case 169 : if (DEBUG) { System.out.println("PropertyNameAndValueList ::= PropertyNameAndValueList..."); } //$NON-NLS-1$ - consumePropertyNameAndValueList(); - break; - - case 170 : if (DEBUG) { System.out.println("PropertyAssignment ::= PropertyName COLON..."); } //$NON-NLS-1$ - consumePropertyAssignment(); - break; - - case 171 : if (DEBUG) { System.out.println("PropertyAssignment ::= PropertyName PropertyName LPAREN"); } //$NON-NLS-1$ - consumeGetSetPropertyAssignment(false); - break; - - case 172 : if (DEBUG) { System.out.println("PropertyAssignment ::= PropertyName PropertyName LPAREN"); } //$NON-NLS-1$ - consumeGetSetPropertyAssignment(true); - break; - - case 173 : if (DEBUG) { System.out.println("PropertySetParameterList ::= SimpleName"); } //$NON-NLS-1$ - consumePropertySetParameterList(); - break; - - case 174 : if (DEBUG) { System.out.println("FunctionBody ::= NestedMethod LBRACE PostDoc..."); } //$NON-NLS-1$ - consumeMethodBody(); - break; - - case 175 : if (DEBUG) { System.out.println("ProgramElementsopt ::="); } //$NON-NLS-1$ - consumeEmptyProgramElements(); - break; - - case 177 : if (DEBUG) { System.out.println("PropertyName ::= SimpleName"); } //$NON-NLS-1$ - consumePropertyName(); - break; - - case 181 : if (DEBUG) { System.out.println("ArrayLiteral ::= ArrayLiteralHeader ElisionOpt RBRACKET"); } //$NON-NLS-1$ - consumeArrayLiteral(false); - break; - - case 182 : if (DEBUG) { System.out.println("ArrayLiteral ::= ArrayLiteralHeader..."); } //$NON-NLS-1$ - consumeArrayLiteral(false); - break; - - case 183 : if (DEBUG) { System.out.println("ArrayLiteral ::= ArrayLiteralHeader..."); } //$NON-NLS-1$ - consumeArrayLiteral(true); - break; - - case 184 : if (DEBUG) { System.out.println("ArrayLiteralHeader ::= LBRACKET"); } //$NON-NLS-1$ - consumeArrayLiteralHeader(); - break; - - case 185 : if (DEBUG) { System.out.println("ElisionOpt ::="); } //$NON-NLS-1$ - consumeElisionEmpty(); - break; - - case 187 : if (DEBUG) { System.out.println("Elision ::= COMMA"); } //$NON-NLS-1$ - consumeElisionOne(); - break; - - case 188 : if (DEBUG) { System.out.println("Elision ::= Elision COMMA"); } //$NON-NLS-1$ - consumeElisionList(); - break; - - case 189 : if (DEBUG) { System.out.println("ArrayLiteralElementList ::= ElisionOpt..."); } //$NON-NLS-1$ - consumeArrayLiteralListOne(); - break; - - case 190 : if (DEBUG) { System.out.println("ArrayLiteralElementList ::= ArrayLiteralElementList..."); } //$NON-NLS-1$ - consumeArrayLiteralList(); - break; - - case 191 : if (DEBUG) { System.out.println("ArrayLiteralElement ::= AssignmentExpression"); } //$NON-NLS-1$ - consumeArrayLiteralElement(); - break; - - case 194 : if (DEBUG) { System.out.println("MemberExpression ::= MemberExpression LBRACKET..."); } //$NON-NLS-1$ - consumeMemberExpressionWithArrayReference(); - break; - - case 195 : if (DEBUG) { System.out.println("MemberExpression ::= MemberExpression DOT SimpleName"); } //$NON-NLS-1$ - consumeMemberExpressionWithSimpleName(); - break; - - case 196 : if (DEBUG) { System.out.println("MemberExpression ::= new MemberExpression Arguments"); } //$NON-NLS-1$ - consumeNewMemberExpressionWithArguments(); - break; - - case 198 : if (DEBUG) { System.out.println("NewExpression ::= new NewExpression"); } //$NON-NLS-1$ - consumeNewExpression(); - break; - - case 199 : if (DEBUG) { System.out.println("CallExpression ::= MemberExpression Arguments"); } //$NON-NLS-1$ - consumeCallExpressionWithArguments(); - break; - - case 200 : if (DEBUG) { System.out.println("CallExpression ::= CallExpression Arguments"); } //$NON-NLS-1$ - consumeCallExpressionWithArguments(); - break; - - case 201 : if (DEBUG) { System.out.println("CallExpression ::= CallExpression LBRACKET Expression..."); } //$NON-NLS-1$ - consumeCallExpressionWithArrayReference(); - break; - - case 202 : if (DEBUG) { System.out.println("CallExpression ::= CallExpression DOT SimpleName"); } //$NON-NLS-1$ - consumeCallExpressionWithSimpleName(); - break; - - case 206 : if (DEBUG) { System.out.println("PostfixExpression ::= LeftHandSideExpression PLUS_PLUS"); } //$NON-NLS-1$ - consumeUnaryExpression(OperatorIds.PLUS, true); - break; - - case 207 : if (DEBUG) { System.out.println("PostfixExpression ::= LeftHandSideExpression MINUS_MINUS"); } //$NON-NLS-1$ - consumeUnaryExpression(OperatorIds.MINUS, true); - break; - - case 209 : if (DEBUG) { System.out.println("ListExpression ::= ListExpression COMMA..."); } //$NON-NLS-1$ - consumeListExpression(); - break; - - case 211 : if (DEBUG) { System.out.println("ListExpressionNoIn ::= ListExpressionNoIn COMMA..."); } //$NON-NLS-1$ - consumeListExpression(); - break; - - case 213 : if (DEBUG) { System.out.println("ListExpressionStmt ::= ListExpressionStmt COMMA..."); } //$NON-NLS-1$ - consumeListExpression(); - break; - - case 215 : if (DEBUG) { System.out.println("ArgumentList ::= ArgumentList COMMA AssignmentExpression"); } //$NON-NLS-1$ - consumeArgumentList(); - break; - - case 216 : if (DEBUG) { System.out.println("PushPosition ::="); } //$NON-NLS-1$ - consumePushPosition(); - break; - - case 219 : if (DEBUG) { System.out.println("UnaryExpression ::= PLUS PushPosition UnaryExpression"); } //$NON-NLS-1$ - consumeUnaryExpression(OperatorIds.PLUS); - break; - - case 220 : if (DEBUG) { System.out.println("UnaryExpression ::= MINUS PushPosition UnaryExpression"); } //$NON-NLS-1$ - consumeUnaryExpression(OperatorIds.MINUS); - break; - - case 222 : if (DEBUG) { System.out.println("PreIncrementExpression ::= PLUS_PLUS PushPosition..."); } //$NON-NLS-1$ - consumeUnaryExpression(OperatorIds.PLUS, false); - break; - - case 223 : if (DEBUG) { System.out.println("PreDecrementExpression ::= MINUS_MINUS PushPosition..."); } //$NON-NLS-1$ - consumeUnaryExpression(OperatorIds.MINUS, false); - break; - - case 225 : if (DEBUG) { System.out.println("UnaryExpressionNotPlusMinus ::= TWIDDLE PushPosition..."); } //$NON-NLS-1$ - consumeUnaryExpression(OperatorIds.TWIDDLE); - break; - - case 226 : if (DEBUG) { System.out.println("UnaryExpressionNotPlusMinus ::= NOT PushPosition..."); } //$NON-NLS-1$ - consumeUnaryExpression(OperatorIds.NOT); - break; - - case 227 : if (DEBUG) { System.out.println("UnaryExpressionNotPlusMinus ::= delete PushPosition..."); } //$NON-NLS-1$ - consumeUnaryExpression(OperatorIds.DELETE); - break; - - case 228 : if (DEBUG) { System.out.println("UnaryExpressionNotPlusMinus ::= void PushPosition..."); } //$NON-NLS-1$ - consumeUnaryExpression(OperatorIds.VOID); - break; - - case 229 : if (DEBUG) { System.out.println("UnaryExpressionNotPlusMinus ::= typeof PushPosition..."); } //$NON-NLS-1$ - consumeUnaryExpression(OperatorIds.TYPEOF); - break; - - case 231 : if (DEBUG) { System.out.println("MultiplicativeExpression ::= MultiplicativeExpression..."); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.MULTIPLY); - break; - - case 232 : if (DEBUG) { System.out.println("MultiplicativeExpression ::= MultiplicativeExpression..."); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.DIVIDE); - break; - - case 233 : if (DEBUG) { System.out.println("MultiplicativeExpression ::= MultiplicativeExpression..."); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.REMAINDER); - break; - - case 235 : if (DEBUG) { System.out.println("AdditiveExpression ::= AdditiveExpression PLUS..."); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.PLUS); - break; - - case 236 : if (DEBUG) { System.out.println("AdditiveExpression ::= AdditiveExpression MINUS..."); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.MINUS); - break; - - case 238 : if (DEBUG) { System.out.println("ShiftExpression ::= ShiftExpression LEFT_SHIFT..."); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.LEFT_SHIFT); - break; - - case 239 : if (DEBUG) { System.out.println("ShiftExpression ::= ShiftExpression RIGHT_SHIFT..."); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.RIGHT_SHIFT); - break; - - case 240 : if (DEBUG) { System.out.println("ShiftExpression ::= ShiftExpression UNSIGNED_RIGHT_SHIFT"); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.UNSIGNED_RIGHT_SHIFT); - break; - - case 242 : if (DEBUG) { System.out.println("RelationalExpression ::= RelationalExpression LESS..."); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.LESS); - break; - - case 243 : if (DEBUG) { System.out.println("RelationalExpression ::= RelationalExpression GREATER..."); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.GREATER); - break; - - case 244 : if (DEBUG) { System.out.println("RelationalExpression ::= RelationalExpression LESS_EQUAL"); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.LESS_EQUAL); - break; - - case 245 : if (DEBUG) { System.out.println("RelationalExpression ::= RelationalExpression..."); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.GREATER_EQUAL); - break; - - case 246 : if (DEBUG) { System.out.println("RelationalExpression ::= RelationalExpression instanceof"); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.INSTANCEOF); - break; - - case 247 : if (DEBUG) { System.out.println("RelationalExpression ::= RelationalExpression in..."); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.IN); - break; - - case 249 : if (DEBUG) { System.out.println("RelationalExpressionNoIn ::= RelationalExpressionNoIn..."); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.LESS); - break; - - case 250 : if (DEBUG) { System.out.println("RelationalExpressionNoIn ::= RelationalExpressionNoIn..."); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.GREATER); - break; - - case 251 : if (DEBUG) { System.out.println("RelationalExpressionNoIn ::= RelationalExpressionNoIn..."); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.LESS_EQUAL); - break; - - case 252 : if (DEBUG) { System.out.println("RelationalExpressionNoIn ::= RelationalExpressionNoIn..."); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.GREATER_EQUAL); - break; - - case 253 : if (DEBUG) { System.out.println("RelationalExpressionNoIn ::= RelationalExpressionNoIn..."); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.INSTANCEOF); - break; - - case 255 : if (DEBUG) { System.out.println("EqualityExpression ::= EqualityExpression EQUAL_EQUAL..."); } //$NON-NLS-1$ - consumeEqualityExpression(OperatorIds.EQUAL_EQUAL); - break; - - case 256 : if (DEBUG) { System.out.println("EqualityExpression ::= EqualityExpression NOT_EQUAL..."); } //$NON-NLS-1$ - consumeEqualityExpression(OperatorIds.NOT_EQUAL); - break; - - case 257 : if (DEBUG) { System.out.println("EqualityExpression ::= EqualityExpression..."); } //$NON-NLS-1$ - consumeEqualityExpression(OperatorIds.EQUAL_EQUAL_EQUAL); - break; - - case 258 : if (DEBUG) { System.out.println("EqualityExpression ::= EqualityExpression..."); } //$NON-NLS-1$ - consumeEqualityExpression(OperatorIds.NOT_EQUAL_EQUAL); - break; - - case 260 : if (DEBUG) { System.out.println("EqualityExpressionNoIn ::= EqualityExpressionNoIn..."); } //$NON-NLS-1$ - consumeEqualityExpression(OperatorIds.EQUAL_EQUAL); - break; - - case 261 : if (DEBUG) { System.out.println("EqualityExpressionNoIn ::= EqualityExpressionNoIn..."); } //$NON-NLS-1$ - consumeEqualityExpression(OperatorIds.NOT_EQUAL); - break; - - case 262 : if (DEBUG) { System.out.println("EqualityExpressionNoIn ::= EqualityExpressionNoIn..."); } //$NON-NLS-1$ - consumeEqualityExpression(OperatorIds.EQUAL_EQUAL_EQUAL); - break; - - case 263 : if (DEBUG) { System.out.println("EqualityExpressionNoIn ::= EqualityExpressionNoIn..."); } //$NON-NLS-1$ - consumeEqualityExpression(OperatorIds.NOT_EQUAL_EQUAL); - break; - - case 265 : if (DEBUG) { System.out.println("AndExpression ::= AndExpression AND EqualityExpression"); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.AND); - break; - - case 267 : if (DEBUG) { System.out.println("AndExpressionNoIn ::= AndExpressionNoIn AND..."); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.AND); - break; - - case 269 : if (DEBUG) { System.out.println("ExclusiveOrExpression ::= ExclusiveOrExpression XOR..."); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.XOR); - break; - - case 271 : if (DEBUG) { System.out.println("ExclusiveOrExpressionNoIn ::= ExclusiveOrExpressionNoIn"); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.XOR); - break; - - case 273 : if (DEBUG) { System.out.println("InclusiveOrExpression ::= InclusiveOrExpression OR..."); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.OR); - break; - - case 275 : if (DEBUG) { System.out.println("InclusiveOrExpressionNoIn ::= InclusiveOrExpressionNoIn"); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.OR); - break; - - case 277 : if (DEBUG) { System.out.println("ConditionalAndExpression ::= ConditionalAndExpression..."); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.AND_AND); - break; - - case 279 : if (DEBUG) { System.out.println("ConditionalAndExpressionNoIn ::=..."); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.AND_AND); - break; - - case 281 : if (DEBUG) { System.out.println("ConditionalOrExpression ::= ConditionalOrExpression..."); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.OR_OR); - break; - - case 283 : if (DEBUG) { System.out.println("ConditionalOrExpressionNoIn ::=..."); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.OR_OR); - break; - - case 285 : if (DEBUG) { System.out.println("ConditionalExpression ::= ConditionalOrExpression..."); } //$NON-NLS-1$ - consumeConditionalExpression(OperatorIds.QUESTIONCOLON); - break; - - case 287 : if (DEBUG) { System.out.println("ConditionalExpressionNoIn ::=..."); } //$NON-NLS-1$ - consumeConditionalExpression(OperatorIds.QUESTIONCOLON); - break; - - case 292 : if (DEBUG) { System.out.println("Assignment ::= PostfixExpression AssignmentOperator..."); } //$NON-NLS-1$ - consumeAssignment(); - break; - - case 293 : if (DEBUG) { System.out.println("AssignmentNoIn ::= PostfixExpression AssignmentOperator"); } //$NON-NLS-1$ - consumeAssignment(); - break; - - case 294 : if (DEBUG) { System.out.println("AssignmentOperator ::= EQUAL"); } //$NON-NLS-1$ - consumeAssignmentOperator(EQUAL); - break; - - case 295 : if (DEBUG) { System.out.println("AssignmentOperator ::= MULTIPLY_EQUAL"); } //$NON-NLS-1$ - consumeAssignmentOperator(MULTIPLY); - break; - - case 296 : if (DEBUG) { System.out.println("AssignmentOperator ::= DIVIDE_EQUAL"); } //$NON-NLS-1$ - consumeAssignmentOperator(DIVIDE); - break; - - case 297 : if (DEBUG) { System.out.println("AssignmentOperator ::= REMAINDER_EQUAL"); } //$NON-NLS-1$ - consumeAssignmentOperator(REMAINDER); - break; - - case 298 : if (DEBUG) { System.out.println("AssignmentOperator ::= PLUS_EQUAL"); } //$NON-NLS-1$ - consumeAssignmentOperator(PLUS); - break; - - case 299 : if (DEBUG) { System.out.println("AssignmentOperator ::= MINUS_EQUAL"); } //$NON-NLS-1$ - consumeAssignmentOperator(MINUS); - break; - - case 300 : if (DEBUG) { System.out.println("AssignmentOperator ::= LEFT_SHIFT_EQUAL"); } //$NON-NLS-1$ - consumeAssignmentOperator(LEFT_SHIFT); - break; - - case 301 : if (DEBUG) { System.out.println("AssignmentOperator ::= RIGHT_SHIFT_EQUAL"); } //$NON-NLS-1$ - consumeAssignmentOperator(RIGHT_SHIFT); - break; - - case 302 : if (DEBUG) { System.out.println("AssignmentOperator ::= UNSIGNED_RIGHT_SHIFT_EQUAL"); } //$NON-NLS-1$ - consumeAssignmentOperator(UNSIGNED_RIGHT_SHIFT); - break; - - case 303 : if (DEBUG) { System.out.println("AssignmentOperator ::= AND_EQUAL"); } //$NON-NLS-1$ - consumeAssignmentOperator(AND); - break; - - case 304 : if (DEBUG) { System.out.println("AssignmentOperator ::= XOR_EQUAL"); } //$NON-NLS-1$ - consumeAssignmentOperator(XOR); - break; - - case 305 : if (DEBUG) { System.out.println("AssignmentOperator ::= OR_EQUAL"); } //$NON-NLS-1$ - consumeAssignmentOperator(OR); - break; - - case 308 : if (DEBUG) { System.out.println("Expressionopt ::="); } //$NON-NLS-1$ - consumeEmptyExpression(); - break; - - case 314 : if (DEBUG) { System.out.println("PrimaryNoNewArrayStmt ::= SimpleName"); } //$NON-NLS-1$ - consumePrimarySimpleName(); - break; - - case 315 : if (DEBUG) { System.out.println("PrimaryNoNewArrayStmt ::= this"); } //$NON-NLS-1$ - consumePrimaryNoNewArrayThis(); - break; - - case 316 : if (DEBUG) { System.out.println("PrimaryNoNewArrayStmt ::= PushLPAREN Expression..."); } //$NON-NLS-1$ - consumePrimaryNoNewArray(); - break; - - case 318 : if (DEBUG) { System.out.println("MemberExpressionStmt ::= MemberExpressionStmt LBRACKET"); } //$NON-NLS-1$ - consumeMemberExpressionWithArrayReference(); - break; - - case 319 : if (DEBUG) { System.out.println("MemberExpressionStmt ::= MemberExpressionStmt DOT..."); } //$NON-NLS-1$ - consumeMemberExpressionWithSimpleName(); - break; - - case 320 : if (DEBUG) { System.out.println("MemberExpressionStmt ::= new MemberExpressionStmt..."); } //$NON-NLS-1$ - consumeNewMemberExpressionWithArguments(); - break; - - case 322 : if (DEBUG) { System.out.println("NewExpressionStmt ::= new NewExpressionStmt"); } //$NON-NLS-1$ - consumeNewExpression(); - break; - - case 323 : if (DEBUG) { System.out.println("CallExpressionStmt ::= MemberExpressionStmt Arguments"); } //$NON-NLS-1$ - consumeCallExpressionWithArguments(); - break; - - case 324 : if (DEBUG) { System.out.println("CallExpressionStmt ::= CallExpressionStmt Arguments"); } //$NON-NLS-1$ - consumeCallExpressionWithArguments(); - break; - - case 325 : if (DEBUG) { System.out.println("CallExpressionStmt ::= CallExpressionStmt LBRACKET..."); } //$NON-NLS-1$ - consumeCallExpressionWithArrayReference(); - break; - - case 326 : if (DEBUG) { System.out.println("CallExpressionStmt ::= CallExpressionStmt DOT SimpleName"); } //$NON-NLS-1$ - consumeCallExpressionWithSimpleName(); - break; - - case 327 : if (DEBUG) { System.out.println("Arguments ::= LPAREN ArgumentListopt RPAREN"); } //$NON-NLS-1$ - consumeArguments(); - break; - - case 331 : if (DEBUG) { System.out.println("PostfixExpressionStmt ::= LeftHandSideExpressionStmt..."); } //$NON-NLS-1$ - consumeUnaryExpression(OperatorIds.PLUS, true); - break; - - case 332 : if (DEBUG) { System.out.println("PostfixExpressionStmt ::= LeftHandSideExpressionStmt..."); } //$NON-NLS-1$ - consumeUnaryExpression(OperatorIds.MINUS, true); - break; - - case 333 : if (DEBUG) { System.out.println("PreIncrementExpressionStmt ::= PLUS_PLUS PushPosition..."); } //$NON-NLS-1$ - consumeUnaryExpression(OperatorIds.PLUS, false); - break; - - case 334 : if (DEBUG) { System.out.println("PreDecrementExpressionStmt ::= MINUS_MINUS PushPosition"); } //$NON-NLS-1$ - consumeUnaryExpression(OperatorIds.MINUS, false); - break; - - case 337 : if (DEBUG) { System.out.println("UnaryExpressionStmt ::= PLUS PushPosition..."); } //$NON-NLS-1$ - consumeUnaryExpression(OperatorIds.PLUS); - break; - - case 338 : if (DEBUG) { System.out.println("UnaryExpressionStmt ::= MINUS PushPosition..."); } //$NON-NLS-1$ - consumeUnaryExpression(OperatorIds.MINUS); - break; - - case 341 : if (DEBUG) { System.out.println("UnaryExpressionNotPlusMinusStmt ::= TWIDDLE PushPosition"); } //$NON-NLS-1$ - consumeUnaryExpression(OperatorIds.TWIDDLE); - break; - - case 342 : if (DEBUG) { System.out.println("UnaryExpressionNotPlusMinusStmt ::= NOT PushPosition..."); } //$NON-NLS-1$ - consumeUnaryExpression(OperatorIds.NOT); - break; - - case 343 : if (DEBUG) { System.out.println("UnaryExpressionNotPlusMinusStmt ::= delete PushPosition"); } //$NON-NLS-1$ - consumeUnaryExpression(OperatorIds.DELETE); - break; - - case 344 : if (DEBUG) { System.out.println("UnaryExpressionNotPlusMinusStmt ::= void PushPosition..."); } //$NON-NLS-1$ - consumeUnaryExpression(OperatorIds.VOID); - break; - - case 345 : if (DEBUG) { System.out.println("UnaryExpressionNotPlusMinusStmt ::= typeof PushPosition"); } //$NON-NLS-1$ - consumeUnaryExpression(OperatorIds.TYPEOF); - break; - - case 347 : if (DEBUG) { System.out.println("MultiplicativeExpressionStmt ::=..."); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.MULTIPLY); - break; - - case 348 : if (DEBUG) { System.out.println("MultiplicativeExpressionStmt ::=..."); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.DIVIDE); - break; - - case 349 : if (DEBUG) { System.out.println("MultiplicativeExpressionStmt ::=..."); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.REMAINDER); - break; - - case 351 : if (DEBUG) { System.out.println("AdditiveExpressionStmt ::= AdditiveExpressionStmt PLUS"); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.PLUS); - break; - - case 352 : if (DEBUG) { System.out.println("AdditiveExpressionStmt ::= AdditiveExpressionStmt MINUS"); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.MINUS); - break; - - case 354 : if (DEBUG) { System.out.println("ShiftExpressionStmt ::= ShiftExpressionStmt LEFT_SHIFT"); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.LEFT_SHIFT); - break; - - case 355 : if (DEBUG) { System.out.println("ShiftExpressionStmt ::= ShiftExpressionStmt RIGHT_SHIFT"); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.RIGHT_SHIFT); - break; - - case 356 : if (DEBUG) { System.out.println("ShiftExpressionStmt ::= ShiftExpressionStmt..."); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.UNSIGNED_RIGHT_SHIFT); - break; - - case 358 : if (DEBUG) { System.out.println("RelationalExpressionStmt ::= RelationalExpressionStmt..."); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.LESS); - break; - - case 359 : if (DEBUG) { System.out.println("RelationalExpressionStmt ::= RelationalExpressionStmt..."); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.GREATER); - break; - - case 360 : if (DEBUG) { System.out.println("RelationalExpressionStmt ::= RelationalExpressionStmt..."); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.LESS_EQUAL); - break; - - case 361 : if (DEBUG) { System.out.println("RelationalExpressionStmt ::= RelationalExpressionStmt..."); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.GREATER_EQUAL); - break; - - case 362 : if (DEBUG) { System.out.println("RelationalExpressionStmt ::= RelationalExpressionStmt..."); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.INSTANCEOF); - break; - - case 363 : if (DEBUG) { System.out.println("RelationalExpressionStmt ::= RelationalExpressionStmt in"); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.IN); - break; - - case 365 : if (DEBUG) { System.out.println("EqualityExpressionStmt ::= EqualityExpressionStmt..."); } //$NON-NLS-1$ - consumeEqualityExpression(OperatorIds.EQUAL_EQUAL); - break; - - case 366 : if (DEBUG) { System.out.println("EqualityExpressionStmt ::= EqualityExpressionStmt..."); } //$NON-NLS-1$ - consumeEqualityExpression(OperatorIds.NOT_EQUAL); - break; - - case 367 : if (DEBUG) { System.out.println("EqualityExpressionStmt ::= EqualityExpressionStmt..."); } //$NON-NLS-1$ - consumeEqualityExpression(OperatorIds.EQUAL_EQUAL_EQUAL); - break; - - case 368 : if (DEBUG) { System.out.println("EqualityExpressionStmt ::= EqualityExpressionStmt..."); } //$NON-NLS-1$ - consumeEqualityExpression(OperatorIds.NOT_EQUAL_EQUAL); - break; - - case 370 : if (DEBUG) { System.out.println("AndExpressionStmt ::= AndExpressionStmt AND..."); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.AND); - break; - - case 372 : if (DEBUG) { System.out.println("ExclusiveOrExpressionStmt ::= ExclusiveOrExpressionStmt"); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.XOR); - break; - - case 374 : if (DEBUG) { System.out.println("InclusiveOrExpressionStmt ::= InclusiveOrExpressionStmt"); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.OR); - break; - - case 376 : if (DEBUG) { System.out.println("ConditionalAndExpressionStmt ::=..."); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.AND_AND); - break; - - case 378 : if (DEBUG) { System.out.println("ConditionalOrExpressionStmt ::=..."); } //$NON-NLS-1$ - consumeBinaryExpression(OperatorIds.OR_OR); - break; - - case 380 : if (DEBUG) { System.out.println("ConditionalExpressionStmt ::=..."); } //$NON-NLS-1$ - consumeConditionalExpression(OperatorIds.QUESTIONCOLON) ; - break; - - case 383 : if (DEBUG) { System.out.println("AssignmentStmt ::= PostfixExpressionStmt..."); } //$NON-NLS-1$ - consumeAssignment(); - break; - - case 384 : if (DEBUG) { System.out.println("Modifiersopt ::="); } //$NON-NLS-1$ - consumeDefaultModifiers(); - break; - - case 385 : if (DEBUG) { System.out.println("BlockStatementsopt ::="); } //$NON-NLS-1$ - consumeEmptyBlockStatementsopt(); - break; - - case 387 : if (DEBUG) { System.out.println("ArgumentListopt ::="); } //$NON-NLS-1$ - consumeEmptyArgumentListopt(); - break; - - case 389 : if (DEBUG) { System.out.println("FormalParameterListopt ::="); } //$NON-NLS-1$ - consumeFormalParameterListopt(); - break; - - case 391 : if (DEBUG) { System.out.println("ForInitopt ::="); } //$NON-NLS-1$ - consumeEmptyForInitopt(); - break; - - case 393 : if (DEBUG) { System.out.println("ForUpdateopt ::="); } //$NON-NLS-1$ - consumeEmptyForUpdateopt(); - break; - - case 395 : if (DEBUG) { System.out.println("Catchesopt ::="); } //$NON-NLS-1$ - consumeEmptyCatchesopt(); - break; - - case 397 : if (DEBUG) { System.out.println("RecoveryMethodHeaderName ::= Modifiersopt function..."); } //$NON-NLS-1$ - consumeRecoveryMethodHeaderName(); - break; - - case 398 : if (DEBUG) { System.out.println("RecoveryMethodHeader ::= RecoveryMethodHeaderName..."); } //$NON-NLS-1$ - consumeMethodHeader(); - break; - - } -} - - -private void consumeElisionList() { - int flag=this.intStack[this.intPtr]; - if ((flag&UNCONSUMED_ELISION)!=0) - { - pushOnExpressionStack(new EmptyExpression(this.endPosition,this.endPosition)); - } - concatExpressionLists(); -// this.intStack[this.intPtr]&= ~(UNCONSUMED_ELISION|UNCONSUMED_LIT_ELEMENT); -} -private void consumeElisionOne() { - pushOnExpressionStack(new EmptyExpression(this.endPosition,this.endPosition)); - if ( (this.intStack[this.intPtr]&UNCONSUMED_LIT_ELEMENT)!=0 || (this.intStack[this.intPtr]&WAS_ARRAY_LIT_ELEMENT)!=0) - concatExpressionLists(); - this.intStack[this.intPtr]|=(WAS_ARRAY_LIT_ELEMENT|UNCONSUMED_ELISION) ; - -} -private void consumeArrayLiteralElement() { - this.intStack[this.intPtr]|= (WAS_ARRAY_LIT_ELEMENT|UNCONSUMED_LIT_ELEMENT); -} -private void consumeElisionEmpty() { -} -private void consumeForInInit() { - Expression expression = this.expressionStack[this.expressionPtr--]; - this.expressionLengthPtr--; - Statement var = expression; - pushOnAstStack(var); - -} -private void consumeStatementWith() { - this.expressionLengthPtr--; - Statement statement = (Statement) this.astStack[this.astPtr]; - this.astStack[this.astPtr] = - new WithStatement( - this.expressionStack[this.expressionPtr--], - statement, - this.intStack[this.intPtr--], - this.endStatementPosition); -} - -private void consumeArrayLiteral(boolean addElision) { - int flag=this.intStack[this.intPtr--]; - if (addElision || (flag&UNCONSUMED_ELISION)!=0) - { - pushOnExpressionStack(new EmptyExpression(this.endPosition,this.endPosition)); - concatExpressionLists(); - } - int length = ((flag&WAS_ARRAY_LIT_ELEMENT)>0)? this.expressionLengthStack[this.expressionLengthPtr--] : 0; - arrayInitializer(length); - -} -private void consumeObjectLiteral() { - ObjectLiteral objectLiteral = new ObjectLiteral(); - int length; - if ((length = this.expressionLengthStack[this.expressionLengthPtr--]) != 0) { - this.expressionPtr -= length; - System.arraycopy( - this.expressionStack, - this.expressionPtr + 1, - objectLiteral.fields = new ObjectLiteralField[length], - 0, - length); - } - objectLiteral.sourceEnd = this.endStatementPosition; - objectLiteral.sourceStart = this.intStack[this.intPtr--]; - - pushOnExpressionStack(objectLiteral); -} -protected void consumeStatementBreak() { - // BreakStatement ::= 'break' ';' - // break pushs a position on this.intStack in case there is no label - - pushOnAstStack(new BreakStatement(null, this.intStack[this.intPtr--], this.endStatementPosition)); - if (this.pendingRecoveredType != null) { - // Used only in statements recovery. - // This is not a real break statement but a placeholder for an existing local type. - // The break statement must be replace by the local type. - if (this.pendingRecoveredType.allocation == null && - this.endPosition <= this.pendingRecoveredType.declarationSourceEnd) { - this.astStack[this.astPtr] = this.pendingRecoveredType; - this.pendingRecoveredType = null; - return; - } - this.pendingRecoveredType = null; - } -} -protected void consumeStatementBreakWithLabel() { - // BreakStatement ::= 'break' Identifier ';' - // break pushs a position on this.intStack in case there is no label - - pushOnAstStack( - new BreakStatement( - this.identifierStack[this.identifierPtr--], - this.intStack[this.intPtr--], - this.endStatementPosition)); - this.identifierLengthPtr--; -} -protected void consumeStatementCatch() { - // CatchClause ::= 'catch' '(' FormalParameter ')' Block - - //catch are stored directly into the Try - //has they always comes two by two.... - //we remove one entry from the astlengthPtr. - //The construction of the try statement must - //then fetch the catches using 2*i and 2*i + 1 - - this.astLengthPtr--; - this.listLength = 0; // reset formalParameter counter (incremented for catch variable) -} -protected void consumeStatementContinue() { - // ContinueStatement ::= 'continue' ';' - // continue pushs a position on this.intStack in case there is no label - - pushOnAstStack( - new ContinueStatement( - null, - this.intStack[this.intPtr--], - this.endStatementPosition)); -} -protected void consumeStatementContinueWithLabel() { - // ContinueStatement ::= 'continue' Identifier ';' - // continue pushs a position on this.intStack in case there is no label - - pushOnAstStack( - new ContinueStatement( - this.identifierStack[this.identifierPtr--], - this.intStack[this.intPtr--], - this.endStatementPosition)); - this.identifierLengthPtr--; -} -protected void consumeStatementDo() { - // DoStatement ::= 'do' Statement 'while' '(' Expression ')' ';' - - //the 'while' pushes a value on this.intStack that we need to remove - this.intPtr--; - - Statement statement = (Statement) this.astStack[this.astPtr]; - this.expressionLengthPtr--; - this.astStack[this.astPtr] = - new DoStatement( - this.expressionStack[this.expressionPtr--], - statement, - this.intStack[this.intPtr--], - this.endStatementPosition); -} -protected void consumeStatementExpressionList() { - // StatementExpressionList ::= StatementExpressionList ',' StatementExpression - concatExpressionLists(); -} -protected void consumeStatementFor() { - // ForStatement ::= 'for' '(' ForInitopt ';' Expressionopt ';' ForUpdateopt ')' Statement - // ForStatementNoShortIf ::= 'for' '(' ForInitopt ';' Expressionopt ';' ForUpdateopt ')' StatementNoShortIf - - int length; - Expression cond = null; - Statement[] inits, updates; - boolean scope = true; - - //statements - this.astLengthPtr--; - Statement statement = (Statement) this.astStack[this.astPtr--]; - - //updates are on the expresion stack - if ((length = this.expressionLengthStack[this.expressionLengthPtr--]) == 0) { - updates = null; - } else { - this.expressionPtr -= length; - System.arraycopy( - this.expressionStack, - this.expressionPtr + 1, - updates = new Statement[length], - 0, - length); - } - - if (this.expressionLengthStack[this.expressionLengthPtr--] != 0) - cond = this.expressionStack[this.expressionPtr--]; - - //inits may be on two different stacks - if ((length = this.astLengthStack[this.astLengthPtr--]) == 0) { - inits = null; - scope = false; - } else { - if (length == -1) { //on this.expressionStack - scope = false; - length = this.expressionLengthStack[this.expressionLengthPtr--]; - this.expressionPtr -= length; - System.arraycopy( - this.expressionStack, - this.expressionPtr + 1, - inits = new Statement[length], - 0, - length); - } else { //on this.astStack - this.astPtr -= length; - System.arraycopy( - this.astStack, - this.astPtr + 1, - inits = new Statement[length], - 0, - length); - } - } - pushOnAstStack( - new ForStatement( - inits, - cond, - updates, - statement, - scope, - this.intStack[this.intPtr--], - this.endStatementPosition)); -} -protected void consumeStatementIfNoElse() { - // IfThenStatement ::= 'if' '(' Expression ')' Statement - - //optimize the push/pop - this.expressionLengthPtr--; - Statement thenStatement = (Statement) this.astStack[this.astPtr]; - this.astStack[this.astPtr] = - new IfStatement( - this.expressionStack[this.expressionPtr--], - thenStatement, - this.intStack[this.intPtr--], - this.endStatementPosition); -} -protected void consumeStatementIfWithElse() { - // IfThenElseStatement ::= 'if' '(' Expression ')' StatementNoShortIf 'else' Statement - // IfThenElseStatementNoShortIf ::= 'if' '(' Expression ')' StatementNoShortIf 'else' StatementNoShortIf - - this.expressionLengthPtr--; - - // optimized {..., Then, Else } ==> {..., If } - this.astLengthPtr--; - - //optimize the push/pop - this.astStack[--this.astPtr] = - new IfStatement( - this.expressionStack[this.expressionPtr--], - (Statement) this.astStack[this.astPtr], - (Statement) this.astStack[this.astPtr + 1], - this.intStack[this.intPtr--], - this.endStatementPosition); -} -protected void consumeStatementLabel() { - // LabeledStatement ::= 'Identifier' ':' Statement - // LabeledStatementNoShortIf ::= 'Identifier' ':' StatementNoShortIf - - //optimize push/pop - Statement statement = (Statement) this.astStack[this.astPtr]; - this.astStack[this.astPtr] = - new LabeledStatement( - this.identifierStack[this.identifierPtr], - statement, - this.identifierPositionStack[this.identifierPtr--], - this.endStatementPosition); - this.identifierLengthPtr--; -} -protected void consumeStatementReturn() { - // ReturnStatement ::= 'return' Expressionopt ';' - // return pushs a position on this.intStack in case there is no expression - - if (this.expressionLengthStack[this.expressionLengthPtr--] != 0) { - pushOnAstStack( - new ReturnStatement( - this.expressionStack[this.expressionPtr--], - this.intStack[this.intPtr--], - this.endStatementPosition) - ); - } else { - pushOnAstStack(new ReturnStatement(null, this.intStack[this.intPtr--], this.endStatementPosition)); - } -} -protected void consumeStatementSwitch() { - // SwitchStatement ::= 'switch' OpenBlock '(' Expression ')' SwitchBlock - - //OpenBlock just makes the semantic action blockStart() - //the block is inlined but a scope need to be created - //if some declaration occurs. - - int length; - SwitchStatement switchStatement = new SwitchStatement(); - this.expressionLengthPtr--; - switchStatement.expression = this.expressionStack[this.expressionPtr--]; - if ((length = this.astLengthStack[this.astLengthPtr--]) != 0) { - this.astPtr -= length; - System.arraycopy( - this.astStack, - this.astPtr + 1, - switchStatement.statements = new Statement[length], - 0, - length); - } - switchStatement.explicitDeclarations = this.realBlockStack[this.realBlockPtr--]; - pushOnAstStack(switchStatement); - switchStatement.blockStart = this.intStack[this.intPtr--]; - switchStatement.sourceStart = this.intStack[this.intPtr--]; - switchStatement.sourceEnd = this.endStatementPosition; - if (length == 0 && !containsComment(switchStatement.blockStart, switchStatement.sourceEnd)) { - switchStatement.bits |= ASTNode.UndocumentedEmptyBlock; - } -} - -protected void consumeStatementThrow() { - // ThrowStatement ::= 'throw' Expression ';' - this.expressionLengthPtr--; - pushOnAstStack(new ThrowStatement(this.expressionStack[this.expressionPtr--], this.intStack[this.intPtr--], this.endStatementPosition)); -} -protected void consumeStatementTry(boolean withFinally) { - //TryStatement ::= 'try' Block Catches - //TryStatement ::= 'try' Block Catchesopt Finally - - int length; - TryStatement tryStmt = new TryStatement(); - //finally - if (withFinally) { - this.astLengthPtr--; - tryStmt.finallyBlock = (Block) this.astStack[this.astPtr--]; - } - //catches are handle by two [see statementCatch] - if ((length = this.astLengthStack[this.astLengthPtr--]) != 0) { - if (length == 1) { - tryStmt.catchBlocks = new Block[] {(Block) this.astStack[this.astPtr--]}; - tryStmt.catchArguments = new Argument[] {(Argument) this.astStack[this.astPtr--]}; - } else { - Block[] bks = (tryStmt.catchBlocks = new Block[length]); - Argument[] args = (tryStmt.catchArguments = new Argument[length]); - while (length-- > 0) { - bks[length] = (Block) this.astStack[this.astPtr--]; - args[length] = (Argument) this.astStack[this.astPtr--]; - } - } - } - //try - this.astLengthPtr--; - tryStmt.tryBlock = (Block) this.astStack[this.astPtr--]; - - //positions - tryStmt.sourceEnd = this.endStatementPosition; - tryStmt.sourceStart = this.intStack[this.intPtr--]; - pushOnAstStack(tryStmt); -} -protected void consumeStatementWhile() { - // WhileStatement ::= 'while' '(' Expression ')' Statement - // WhileStatementNoShortIf ::= 'while' '(' Expression ')' StatementNoShortIf - - this.expressionLengthPtr--; - Statement statement = (Statement) this.astStack[this.astPtr]; - this.astStack[this.astPtr] = - new WhileStatement( - this.expressionStack[this.expressionPtr--], - statement, - this.intStack[this.intPtr--], - this.endStatementPosition); -} - -protected void consumeSwitchBlock() { - // SwitchBlock ::= '{' SwitchBlockStatements SwitchLabels '}' - concatNodeLists(); -} -protected void consumeSwitchBlockStatement() { - // SwitchBlockStatement ::= SwitchLabels BlockStatements - concatNodeLists(); -} -protected void consumeSwitchBlockStatements() { - // SwitchBlockStatements ::= SwitchBlockStatements SwitchBlockStatement - concatNodeLists(); -} -protected void consumeSwitchLabels() { - // SwitchLabels ::= SwitchLabels SwitchLabel - optimizedConcatNodeLists(); -} -protected void consumeToken(int type) { - /* remember the last consumed value */ - /* try to minimize the number of build values */ -// // clear the commentPtr of the scanner in case we read something different from a modifier -// switch(type) { -// case TokenNameabstract : -// case TokenNamestrictfp : -// case TokenNamefinal : -// case TokenNamenative : -// case TokenNameprivate : -// case TokenNameprotected : -// case TokenNamepublic : -// case TokenNametransient : -// case TokenNamevolatile : -// case TokenNamestatic : -// case TokenNamesynchronized : -// break; -// default: -// this.scanner.commentPtr = -1; -// } - //System.out.println(this.scanner.toStringAction(type)); - switch (type) { - case TokenNameIdentifier : - pushIdentifier(); - break; - case TokenNameinterface : - //'class' is pushing two int (positions) on the stack ==> 'interface' needs to do it too.... - pushOnIntStack(this.scanner.currentPosition - 1); - pushOnIntStack(this.scanner.startPosition); - break; - case TokenNameabstract : - checkAndSetModifiers(ClassFileConstants.AccAbstract); - pushOnExpressionStackLengthStack(0); - break; - case TokenNamefinal : - checkAndSetModifiers(ClassFileConstants.AccFinal); - pushOnExpressionStackLengthStack(0); - break; - case TokenNamenative : - checkAndSetModifiers(ClassFileConstants.AccNative); - pushOnExpressionStackLengthStack(0); - break; - case TokenNameprivate : - checkAndSetModifiers(ClassFileConstants.AccPrivate); - pushOnExpressionStackLengthStack(0); - break; - case TokenNameprotected : - checkAndSetModifiers(ClassFileConstants.AccProtected); - pushOnExpressionStackLengthStack(0); - break; - case TokenNamepublic : - checkAndSetModifiers(ClassFileConstants.AccPublic); - pushOnExpressionStackLengthStack(0); - break; - case TokenNametransient : - pushOnExpressionStackLengthStack(0); - break; - case TokenNamevolatile : - pushOnExpressionStackLengthStack(0); - break; - case TokenNamestatic : - checkAndSetModifiers(ClassFileConstants.AccStatic); - pushOnExpressionStackLengthStack(0); - break; -// case TokenNamesynchronized : -// this.synchronizedBlockSourceStart = this.scanner.startPosition; -// checkAndSetModifiers(ClassFileConstants.AccSynchronized); -// pushOnExpressionStackLengthStack(0); -// break; - //============================== -// case TokenNamevoid : -// pushIdentifier(-T_void); -// pushOnIntStack(this.scanner.currentPosition - 1); -// pushOnIntStack(this.scanner.startPosition); -// break; - //push a default dimension while void is not part of the primitive - //declaration baseType and so takes the place of a type without getting into - //regular type parsing that generates a dimension on this.intStack - case TokenNameboolean : - pushIdentifier(-T_boolean); - pushOnIntStack(this.scanner.currentPosition - 1); - pushOnIntStack(this.scanner.startPosition); - break; - case TokenNamechar : - pushIdentifier(-T_char); - pushOnIntStack(this.scanner.currentPosition - 1); - pushOnIntStack(this.scanner.startPosition); - break; - case TokenNamedouble : - pushIdentifier(-T_double); - pushOnIntStack(this.scanner.currentPosition - 1); - pushOnIntStack(this.scanner.startPosition); - break; - case TokenNamefloat : - pushIdentifier(-T_float); - pushOnIntStack(this.scanner.currentPosition - 1); - pushOnIntStack(this.scanner.startPosition); - break; - case TokenNameint : - pushIdentifier(-T_int); - pushOnIntStack(this.scanner.currentPosition - 1); - pushOnIntStack(this.scanner.startPosition); - break; - case TokenNamelong : - pushIdentifier(-T_long); - pushOnIntStack(this.scanner.currentPosition - 1); - pushOnIntStack(this.scanner.startPosition); - break; - case TokenNameshort : - pushIdentifier(-T_short); - pushOnIntStack(this.scanner.currentPosition - 1); - pushOnIntStack(this.scanner.startPosition); - break; - //============================== - case TokenNameIntegerLiteral : - pushOnExpressionStack( - new IntLiteral( - this.scanner.getCurrentTokenSource(), - this.scanner.startPosition, - this.scanner.currentPosition - 1)); - break; - case TokenNameLongLiteral : - case TokenNameFloatingPointLiteral : - case TokenNameDoubleLiteral : - pushOnExpressionStack( - new DoubleLiteral( - this.scanner.getCurrentTokenSource(), - this.scanner.startPosition, - this.scanner.currentPosition - 1)); - break; - case TokenNameCharacterLiteral : - StringLiteral stringLiteral; - if (this.recordStringLiterals && this.checkExternalizeStrings && !this.statementRecoveryActivated) { - stringLiteral = this.createStringLiteral( - this.scanner.getCurrentTokenSourceString(), - this.scanner.startPosition, - this.scanner.currentPosition - 1, - Util.getLineNumber(this.scanner.startPosition, this.scanner.lineEnds, 0, this.scanner.linePtr)); - this.compilationUnit.recordStringLiteral(stringLiteral); - } else { - stringLiteral = this.createStringLiteral( - this.scanner.getCurrentTokenSourceString(), - this.scanner.startPosition, - this.scanner.currentPosition - 1, - 0); - } - pushOnExpressionStack(stringLiteral); - break; - case TokenNameRegExLiteral : - pushOnExpressionStack( - new RegExLiteral( - this.scanner.getCurrentTokenSource(), - this.scanner.startPosition, - this.scanner.currentPosition - 1)); - break; - - case TokenNameStringLiteral : - if (this.recordStringLiterals && this.checkExternalizeStrings && !this.statementRecoveryActivated) { - stringLiteral = this.createStringLiteral( - this.scanner.getCurrentTokenSourceString(), - this.scanner.startPosition, - this.scanner.currentPosition - 1, - Util.getLineNumber(this.scanner.startPosition, this.scanner.lineEnds, 0, this.scanner.linePtr)); - this.compilationUnit.recordStringLiteral(stringLiteral); - } else { - stringLiteral = this.createStringLiteral( - this.scanner.getCurrentTokenSourceString(), - this.scanner.startPosition, - this.scanner.currentPosition - 1, - 0); - } - pushOnExpressionStack(stringLiteral); - break; - case TokenNamefalse : - pushOnExpressionStack( - new FalseLiteral(this.scanner.startPosition, this.scanner.currentPosition - 1)); - break; - case TokenNametrue : - pushOnExpressionStack( - new TrueLiteral(this.scanner.startPosition, this.scanner.currentPosition - 1)); - break; - case TokenNamenull : - pushOnExpressionStack( - new NullLiteral(this.scanner.startPosition, this.scanner.currentPosition - 1)); - break; - case TokenNameundefined : - pushOnExpressionStack( - new UndefinedLiteral(this.scanner.startPosition, this.scanner.currentPosition - 1)); - break; - //============================ - case TokenNamesuper : - case TokenNamethis : - this.endPosition = this.scanner.currentPosition - 1; - pushOnIntStack(this.scanner.startPosition); - break; -// case TokenNameassert : - case TokenNameimport : - case TokenNamepackage : - case TokenNamethrow : - case TokenNamedo : - case TokenNameif : - case TokenNamefor : - case TokenNameswitch : - case TokenNametry : - case TokenNamewhile : - case TokenNamebreak : - case TokenNamecontinue : - case TokenNamereturn : - case TokenNamecase : - case TokenNamedebugger : - case TokenNameexport : - case TokenNamefunction : - case TokenNamevar : -// case TokenNamein : -// case TokenNameinfinity : - case TokenNamewith : - pushOnIntStack(this.scanner.startPosition); - break; - case TokenNamenew : - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=40954 - resetModifiers(); - pushOnIntStack(this.scanner.startPosition); - break; - case TokenNameclass : - pushOnIntStack(this.scanner.currentPosition - 1); - pushOnIntStack(this.scanner.startPosition); - break; - case TokenNameenum : - pushOnIntStack(this.scanner.currentPosition - 1); - pushOnIntStack(this.scanner.startPosition); - break; - case TokenNamedefault : - pushOnIntStack(this.scanner.startPosition); - pushOnIntStack(this.scanner.currentPosition - 1); - break; - //let extra semantic action decide when to push - case TokenNameRBRACKET : - this.endPosition = this.scanner.startPosition; - this.endStatementPosition = this.scanner.currentPosition - 1; - break; - case TokenNameLBRACKET : - this.endPosition = this.scanner.startPosition; - break; - case TokenNameLBRACE : - this.endStatementPosition = this.scanner.currentPosition - 1; - case TokenNamePLUS : - case TokenNameMINUS : - case TokenNameNOT : - case TokenNameTWIDDLE : - case TokenNamedelete : - case TokenNamevoid : - case TokenNametypeof : - this.endPosition = this.scanner.startPosition; - break; - case TokenNamePLUS_PLUS : - case TokenNameMINUS_MINUS : - this.endPosition = this.scanner.startPosition; - this.endStatementPosition = this.scanner.currentPosition - 1; - break; - case TokenNameSEMICOLON : - if (this.insertedSemicolonPosition>0) - { - if (this.insertedSemicolonPosition>=this.scanner.source.length) - this.insertedSemicolonPosition--; - this.endStatementPosition = this.insertedSemicolonPosition; - this.endPosition = this.insertedSemicolonPosition; - this.insertedSemicolonPosition=-1; - this.problemReporter().missingSemiColon(null, this.endPosition-1,this.endPosition); - break; - }// else fallthru - case TokenNameRBRACE: - this.endStatementPosition = this.scanner.currentPosition - 1; - this.endPosition = this.scanner.startPosition - 1; - //the item is not part of the potential future expression/statement - break; - case TokenNameRPAREN : - // in order to handle ( expression) ////// (cast)expression///// foo(x) - this.rParenPos = this.scanner.currentPosition - 1; // position of the end of right parenthesis (in case of unicode \u0029) lex00101 - break; - case TokenNameLPAREN : - this.lParenPos = this.scanner.startPosition; - break; - case TokenNameQUESTION : - pushOnIntStack(this.scanner.startPosition); - pushOnIntStack(this.scanner.currentPosition - 1); - break; - case TokenNameLESS : - pushOnIntStack(this.scanner.startPosition); - break; -// case TokenNameELLIPSIS : -// pushOnIntStack(this.scanner.currentPosition - 1); -// break; - // case TokenNameCOMMA : - // case TokenNameCOLON : - // case TokenNameEQUAL : - // case TokenNameLBRACKET : - // case TokenNameDOT : - // case TokenNameERROR : - // case TokenNameEOF : - // case TokenNamecase : - // case TokenNamecatch : - // case TokenNameelse : - // case TokenNameextends : - // case TokenNamefinally : - // case TokenNameimplements : - // case TokenNamethrows : - // case TokenNameinstanceof : - // case TokenNameEQUAL_EQUAL : - // case TokenNameLESS_EQUAL : - // case TokenNameGREATER_EQUAL : - // case TokenNameNOT_EQUAL : - // case TokenNameLEFT_SHIFT : - // case TokenNameRIGHT_SHIFT : - // case TokenNameUNSIGNED_RIGHT_SHIFT : - // case TokenNamePLUS_EQUAL : - // case TokenNameMINUS_EQUAL : - // case TokenNameMULTIPLY_EQUAL : - // case TokenNameDIVIDE_EQUAL : - // case TokenNameAND_EQUAL : - // case TokenNameOR_EQUAL : - // case TokenNameXOR_EQUAL : - // case TokenNameREMAINDER_EQUAL : - // case TokenNameLEFT_SHIFT_EQUAL : - // case TokenNameRIGHT_SHIFT_EQUAL : - // case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : - // case TokenNameOR_OR : - // case TokenNameAND_AND : - // case TokenNameREMAINDER : - // case TokenNameXOR : - // case TokenNameAND : - // case TokenNameMULTIPLY : - // case TokenNameOR : - // case TokenNameDIVIDE : - // case TokenNameGREATER : - } -} -protected void consumeUnaryExpression(int op) { - // UnaryExpression ::= '+' PushPosition UnaryExpression - // UnaryExpression ::= '-' PushPosition UnaryExpression - // UnaryExpressionNotPlusMinus ::= '~' PushPosition UnaryExpression - // UnaryExpressionNotPlusMinus ::= '!' PushPosition UnaryExpression - - //optimize the push/pop - - //handle manually the -2147483648 while it is not a real - //computation of an - and 2147483648 (notice that 2147483648 - //is Integer.MAX_VALUE+1.....) - //Same for -9223372036854775808L ............ - - //this.intStack have the position of the operator - - Expression r, exp = this.expressionStack[this.expressionPtr]; - if (op == MINUS) { - if ((exp instanceof IntLiteral) && (((IntLiteral) exp).mayRepresentMIN_VALUE())) { - r = this.expressionStack[this.expressionPtr] = new IntLiteralMinValue(); - } else { - r = this.expressionStack[this.expressionPtr] = new UnaryExpression(exp, op); - } - } else { - r = this.expressionStack[this.expressionPtr] = new UnaryExpression(exp, op); - } - r.sourceStart = this.intStack[this.intPtr--]; - r.sourceEnd = exp.sourceEnd; -} -protected void consumeUnaryExpression(int op, boolean post) { - // PreIncrementExpression ::= '++' PushPosition UnaryExpression - // PreDecrementExpression ::= '--' PushPosition UnaryExpression - - // ++ and -- operators - //optimize the push/pop - - //this.intStack has the position of the operator when prefix - - Expression leftHandSide = this.expressionStack[this.expressionPtr]; - if (leftHandSide instanceof Reference) { - // ++foo()++ is unvalid - if (post) { - this.expressionStack[this.expressionPtr] = - new PostfixExpression( - leftHandSide, - IntLiteral.getOne(), - op, - this.endStatementPosition); - } else { - this.expressionStack[this.expressionPtr] = - new PrefixExpression( - leftHandSide, - IntLiteral.getOne(), - op, - this.intStack[this.intPtr--]); - } - } else { - //the ++ or the -- is NOT taken into account if code gen proceeds - if (!post) { - this.intPtr--; - } - if(!this.statementRecoveryActivated) problemReporter().invalidUnaryExpression(leftHandSide); - } -} -protected void consumeVariableDeclarators() { - // VariableDeclarators ::= VariableDeclarators ',' VariableDeclarator - optimizedConcatNodeLists(); -} -protected void consumeVariableInitializers() { - // VariableInitializers ::= VariableInitializers ',' VariableInitializer - concatExpressionLists(); -} -/** - * Given the current comment stack, answer whether some comment is available in a certain exclusive range - * - * @param sourceStart int - * @param sourceEnd int - * @return boolean - */ -public boolean containsComment(int sourceStart, int sourceEnd) { - int iComment = this.scanner.commentPtr; - for (; iComment >= 0; iComment--) { - int commentStart = this.scanner.commentStarts[iComment]; - // ignore comments before start - if (commentStart < sourceStart) continue; - // ignore comments after end - if (commentStart > sourceEnd) continue; - return true; - } - return false; -} -public MethodDeclaration convertToMethodDeclaration(ConstructorDeclaration c, CompilationResult compilationResult) { - MethodDeclaration m = new MethodDeclaration(compilationResult); - m.sourceStart = c.sourceStart; - m.sourceEnd = c.sourceEnd; - m.bodyStart = c.bodyStart; - m.bodyEnd = c.bodyEnd; - m.declarationSourceEnd = c.declarationSourceEnd; - m.declarationSourceStart = c.declarationSourceStart; - m.selector = c.selector; - m.statements = c.statements; - m.modifiers = c.modifiers; - m.arguments = c.arguments; - m.explicitDeclarations = c.explicitDeclarations; - m.returnType = null; - m.javadoc = c.javadoc; - return m; -} -protected TypeReference copyDims(TypeReference typeRef, int dim) { - return typeRef.copyDims(dim); -} -protected FieldDeclaration createFieldDeclaration(char[] fieldDeclarationName, int sourceStart, int sourceEnd) { - return new FieldDeclaration(fieldDeclarationName, sourceStart, sourceEnd); -} -protected JavadocParser createJavadocParser() { - return new JavadocParser(this); -} -protected LocalDeclaration createLocalDeclaration(char[] localDeclarationName, int sourceStart, int sourceEnd) { - return new LocalDeclaration(localDeclarationName, sourceStart, sourceEnd); -} -protected StringLiteral createStringLiteral(char[] token, int start, int end, int lineNumber) { - return new StringLiteral(token, start, end, lineNumber); -} - - protected RecoveredType currentRecoveryType() { - if(this.currentElement != null) { - if(this.currentElement instanceof RecoveredType) { - return (RecoveredType) this.currentElement; - } else { - return this.currentElement.enclosingType(); - } - } - return null; -} -public CompilationUnitDeclaration dietParse(ICompilationUnit sourceUnit, CompilationResult compilationResult) { - - CompilationUnitDeclaration parsedUnit; - boolean old = this.diet; - try { - this.diet = DO_DIET_PARSE; - parsedUnit = parse(sourceUnit, compilationResult); - } finally { - this.diet = old; - } - return parsedUnit; -} -protected void dispatchDeclarationInto(int length) { - /* they are length on this.astStack that should go into - methods fields constructors lists of the typeDecl - - Return if there is a constructor declaration in the methods declaration */ - - - // Looks for the size of each array . - - if (length == 0) - return; - int[] flag = new int[length + 1]; //plus one -- see - int size1 = 0, size2 = 0, size3 = 0; - boolean hasAbstractMethods = false; - for (int i = length - 1; i >= 0; i--) { - ASTNode astNode = this.astStack[this.astPtr--]; - if (astNode instanceof AbstractMethodDeclaration) { - //methods and constructors have been regrouped into one single list - flag[i] = 2; - size2++; - if (((AbstractMethodDeclaration) astNode).isAbstract()) { - hasAbstractMethods = true; - } - } else if (astNode instanceof TypeDeclaration) { - flag[i] = 3; - size3++; - } else { - //field - flag[i] = 1; - size1++; - } - } - - //arrays creation - TypeDeclaration typeDecl = (TypeDeclaration) this.astStack[this.astPtr]; - if (size1 != 0) { - typeDecl.fields = new FieldDeclaration[size1]; - } - if (size2 != 0) { - typeDecl.methods = new AbstractMethodDeclaration[size2]; - if (hasAbstractMethods) typeDecl.bits |= ASTNode.HasAbstractMethods; - } - if (size3 != 0) { - typeDecl.memberTypes = new TypeDeclaration[size3]; - } - - //arrays fill up - size1 = size2 = size3 = 0; - int flagI = flag[0], start = 0; - int length2; - for (int end = 0; end <= length; end++) // the plus one allows to - { - if (flagI != flag[end]) //treat the last element as a ended flag..... - { //array copy - switch (flagI) { - case 1 : - size1 += (length2 = end - start); - System.arraycopy( - this.astStack, - this.astPtr + start + 1, - typeDecl.fields, - size1 - length2, - length2); - break; - case 2 : - size2 += (length2 = end - start); - System.arraycopy( - this.astStack, - this.astPtr + start + 1, - typeDecl.methods, - size2 - length2, - length2); - break; - case 3 : - size3 += (length2 = end - start); - System.arraycopy( - this.astStack, - this.astPtr + start + 1, - typeDecl.memberTypes, - size3 - length2, - length2); - break; - } - flagI = flag[start = end]; - } - } - - if (typeDecl.memberTypes != null) { - for (int i = typeDecl.memberTypes.length - 1; i >= 0; i--) { - typeDecl.memberTypes[i].enclosingType = typeDecl; - } - } -} -protected void dispatchDeclarationIntoEnumDeclaration(int length) { - - if (length == 0) - return; - int[] flag = new int[length + 1]; //plus one -- see - int size1 = 0, size2 = 0, size3 = 0; - TypeDeclaration enumDeclaration = (TypeDeclaration) this.astStack[this.astPtr - length]; - boolean hasAbstractMethods = false; - for (int i = length - 1; i >= 0; i--) { - ASTNode astNode = this.astStack[this.astPtr--]; - if (astNode instanceof AbstractMethodDeclaration) { - //methods and constructors have been regrouped into one single list - flag[i] = 2; - size2++; - if (((AbstractMethodDeclaration) astNode).isAbstract()) { - hasAbstractMethods = true; - } - } else if (astNode instanceof TypeDeclaration) { - flag[i] = 3; - size3++; - } else if (astNode instanceof FieldDeclaration) { - flag[i] = 1; - size1++; -// if(astNode instanceof EnumConstant) { -// EnumConstant constant = (EnumConstant) astNode; -// ((AllocationExpression)constant.initialization).type = new SingleTypeReference(enumDeclaration.name, -// (((long) enumDeclaration.sourceStart) << 32) + enumDeclaration.sourceEnd); -// } - } - } - - //arrays creation - if (size1 != 0) { - enumDeclaration.fields = new FieldDeclaration[size1]; - } - if (size2 != 0) { - enumDeclaration.methods = new AbstractMethodDeclaration[size2]; - if (hasAbstractMethods) enumDeclaration.bits |= ASTNode.HasAbstractMethods; - } - if (size3 != 0) { - enumDeclaration.memberTypes = new TypeDeclaration[size3]; - } - - //arrays fill up - size1 = size2 = size3 = 0; - int flagI = flag[0], start = 0; - int length2; - for (int end = 0; end <= length; end++) // the plus one allows to - { - if (flagI != flag[end]) //treat the last element as a ended flag..... - { //array copy - switch (flagI) { - case 1 : - size1 += (length2 = end - start); - System.arraycopy( - this.astStack, - this.astPtr + start + 1, - enumDeclaration.fields, - size1 - length2, - length2); - break; - case 2 : - size2 += (length2 = end - start); - System.arraycopy( - this.astStack, - this.astPtr + start + 1, - enumDeclaration.methods, - size2 - length2, - length2); - break; - case 3 : - size3 += (length2 = end - start); - System.arraycopy( - this.astStack, - this.astPtr + start + 1, - enumDeclaration.memberTypes, - size3 - length2, - length2); - break; - } - flagI = flag[start = end]; - } - } - - if (enumDeclaration.memberTypes != null) { - for (int i = enumDeclaration.memberTypes.length - 1; i >= 0; i--) { - enumDeclaration.memberTypes[i].enclosingType = enumDeclaration; - } - }} -protected CompilationUnitDeclaration endParse(int act) { - - this.lastAct = act; - - if(this.statementRecoveryActivated ) { - RecoveredElement recoveredElement = this.buildInitialRecoveryState(); - recoveredElement.topElement().updateParseTree(); - if(this.hasError) this.resetStacks(); - } else if (this.currentElement != null){ - if (VERBOSE_RECOVERY){ - System.out.print(Messages.parser_syntaxRecovery); - System.out.println("--------------------------"); //$NON-NLS-1$ - System.out.println(this.compilationUnit); - System.out.println("----------------------------------"); //$NON-NLS-1$ - } - recoverAST(this.currentElement); - this.currentElement.topElement().updateParseTree(); - } else { - if (this.diet & VERBOSE_RECOVERY){ - System.out.print(Messages.parser_regularParse); - System.out.println("--------------------------"); //$NON-NLS-1$ - System.out.println(this.compilationUnit); - System.out.println("----------------------------------"); //$NON-NLS-1$ - } - } - persistLineSeparatorPositions(); - for (int i = 0; i < this.scanner.foundTaskCount; i++){ - if(!this.statementRecoveryActivated) problemReporter().task( - new String(this.scanner.foundTaskTags[i]), - new String(this.scanner.foundTaskMessages[i]), - this.scanner.foundTaskPriorities[i] == null ? null : new String(this.scanner.foundTaskPriorities[i]), - this.scanner.foundTaskPositions[i][0], - this.scanner.foundTaskPositions[i][1]); - } - if (this.compilationUnit.statements==null) - this.compilationUnit.statements=new ProgramElement[0]; - return this.compilationUnit; -} -/* - * Flush comments defined prior to a given positions. - * - * Note: comments are stacked in syntactical order - * - * Either answer given , or the end position of a comment line - * immediately following the (same line) - * - * e.g. - * void foo(){ - * } // end of method foo - */ - -public int flushCommentsDefinedPriorTo(int position) { - - int lastCommentIndex = this.scanner.commentPtr; - if (lastCommentIndex < 0) return position; // no comment - - // compute the index of the first obsolete comment - int index = lastCommentIndex; - int validCount = 0; - while (index >= 0){ - int commentEnd = this.scanner.commentStops[index]; - if (commentEnd < 0) commentEnd = -commentEnd; // negative end position for non-javadoc comments - if (commentEnd <= position){ - break; - } - index--; - validCount++; - } - // if the source at is immediately followed by a line comment, then - // flush this comment and shift to the comment end. - if (validCount > 0){ - int immediateCommentEnd = -this.scanner.commentStops[index+1]; //non-javadoc comment end positions are negative - if (immediateCommentEnd > 0){ // only tolerating non-javadoc comments - // is there any line break until the end of the immediate comment ? (thus only tolerating line comment) - immediateCommentEnd--; // comment end in one char too far - if (Util.getLineNumber(position, this.scanner.lineEnds, 0, this.scanner.linePtr) - == Util.getLineNumber(immediateCommentEnd, this.scanner.lineEnds, 0, this.scanner.linePtr)){ - position = immediateCommentEnd; - validCount--; // flush this comment - index++; - } - } - } - - if (index < 0) return position; // no obsolete comment - - switch (validCount) { - case 0: - // do nothing - break; - // move valid comment infos, overriding obsolete comment infos - case 2: - this.scanner.commentStarts[0] = this.scanner.commentStarts[index+1]; - this.scanner.commentStops[0] = this.scanner.commentStops[index+1]; - this.scanner.commentTagStarts[0] = this.scanner.commentTagStarts[index+1]; - this.scanner.commentStarts[1] = this.scanner.commentStarts[index+2]; - this.scanner.commentStops[1] = this.scanner.commentStops[index+2]; - this.scanner.commentTagStarts[1] = this.scanner.commentTagStarts[index+2]; - break; - case 1: - this.scanner.commentStarts[0] = this.scanner.commentStarts[index+1]; - this.scanner.commentStops[0] = this.scanner.commentStops[index+1]; - this.scanner.commentTagStarts[0] = this.scanner.commentTagStarts[index+1]; - break; - default: - System.arraycopy(this.scanner.commentStarts, index + 1, this.scanner.commentStarts, 0, validCount); - System.arraycopy(this.scanner.commentStops, index + 1, this.scanner.commentStops, 0, validCount); - System.arraycopy(this.scanner.commentTagStarts, index + 1, this.scanner.commentTagStarts, 0, validCount); - } - this.scanner.commentPtr = validCount - 1; - return position; -} -public int getFirstToken() { - // the first token is a virtual token that - // allows the parser to parse several goals - // even if they aren't LALR(1).... - // Goal ::= '++' JavaScriptUnit - // Goal ::= '--' MethodBody - // Goal ::= '==' ConstructorBody - // -- Initializer - // Goal ::= '>>' StaticInitializer - // Goal ::= '>>' Block - // -- error recovery - // Goal ::= '>>>' Headers - // Goal ::= '*' BlockStatements - // Goal ::= '*' MethodPushModifiersHeader - // -- JDOM - // Goal ::= '&&' FieldDeclaration - // Goal ::= '||' ImportDeclaration - // Goal ::= '?' PackageDeclaration - // Goal ::= '+' TypeDeclaration - // Goal ::= '/' GenericMethodDeclaration - // Goal ::= '&' ClassBodyDeclaration - // -- code snippet - // Goal ::= '%' Expression - // -- completion parser - // Goal ::= '!' ConstructorBlockStatementsopt - // Goal ::= '~' BlockStatementsopt - - return this.firstToken; -} -/* - * Answer back an array of sourceStart/sourceEnd positions of the available JavaDoc comments. - * The array is a flattened structure: 2*n entries with consecutives start and end positions. - * - * If no JavaDoc is available, then null is answered instead of an empty array. - * - * e.g. { 10, 20, 25, 45 } --> javadoc1 from 10 to 20, javadoc2 from 25 to 45 - */ -public int[] getJavaDocPositions() { - - int javadocCount = 0; - for (int i = 0, max = this.scanner.commentPtr; i <= max; i++){ - // javadoc only (non javadoc comment have negative end positions.) - if (this.scanner.commentStops[i] > 0){ - javadocCount++; - } - } - if (javadocCount == 0) return null; - - int[] positions = new int[2*javadocCount]; - int index = 0; - for (int i = 0, max = this.scanner.commentPtr; i <= max; i++){ - // javadoc only (non javadoc comment have negative end positions.) - if (this.scanner.commentStops[i] > 0){ - positions[index++] = this.scanner.commentStarts[i]; - positions[index++] = this.scanner.commentStops[i]-1; //stop is one over - } - } - return positions; -} - public void getMethodBodies(CompilationUnitDeclaration unit) { - //fill the methods bodies in order for the code to be generated - - if (unit == null) return; - - if (unit.ignoreMethodBodies) { - unit.ignoreFurtherInvestigation = true; - return; - // if initial diet parse did not work, no need to dig into method bodies. - } - - if ((unit.bits & ASTNode.HasAllMethodBodies) != 0) - return; //work already done ... - - // save existing values to restore them at the end of the parsing process - // see bug 47079 for more details - int[] oldLineEnds = this.scanner.lineEnds; - int oldLinePtr = this.scanner.linePtr; - - //real parse of the method.... - CompilationResult compilationResult = unit.compilationResult; - char[] contents = compilationResult.compilationUnit.getContents(); - this.scanner.setSource(contents, compilationResult); - - if (this.javadocParser != null && this.javadocParser.checkDocComment) { - this.javadocParser.scanner.setSource(contents); - } - if (unit.types != null) { - for (int i = unit.types.length; --i >= 0;) - unit.types[i].parseMethod(this, unit); - } - - // tag unit has having read bodies - unit.bits |= ASTNode.HasAllMethodBodies; - - // this is done to prevent any side effects on the compilation unit result - // line separator positions array. - this.scanner.lineEnds = oldLineEnds; - this.scanner.linePtr = oldLinePtr; - } -protected char getNextCharacter(char[] comment, int[] index) { - char nextCharacter = comment[index[0]++]; - switch(nextCharacter) { - case '\\' : - int c1, c2, c3, c4; - index[0]++; - while (comment[index[0]] == 'u') index[0]++; - if (!(((c1 = ScannerHelper.getNumericValue(comment[index[0]++])) > 15 - || c1 < 0) - || ((c2 = ScannerHelper.getNumericValue(comment[index[0]++])) > 15 || c2 < 0) - || ((c3 = ScannerHelper.getNumericValue(comment[index[0]++])) > 15 || c3 < 0) - || ((c4 = ScannerHelper.getNumericValue(comment[index[0]++])) > 15 || c4 < 0))) { - nextCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); - } - break; - } - return nextCharacter; -} -protected Expression getTypeReference(Expression exp) { - - exp.bits &= ~ASTNode.RestrictiveFlagMASK; - exp.bits |= Binding.TYPE; - return exp; -} -protected TypeReference getTypeReference(int dim) { - /* build a Reference on a variable that may be qualified or not - This variable is a type reference and dim will be its dimensions*/ - - TypeReference ref; - int length = this.identifierLengthStack[this.identifierLengthPtr--]; - if (length < 0) { //flag for precompiled type reference on base types - ref = TypeReference.baseTypeReference(-length, dim); - ref.sourceStart = this.intStack[this.intPtr--]; - if (dim == 0) { - ref.sourceEnd = this.intStack[this.intPtr--]; - } else { - this.intPtr--; - ref.sourceEnd = this.endPosition; - } - } else { - int numberOfIdentifiers = this.genericsIdentifiersLengthStack[this.genericsIdentifiersLengthPtr--]; - if (length != numberOfIdentifiers || this.genericsLengthStack[this.genericsLengthPtr] != 0) { - ref = null; - } else if (length == 1) { - // single variable reference - this.genericsLengthPtr--; // pop the 0 - if (dim == 0) { - ref = - new SingleTypeReference( - this.identifierStack[this.identifierPtr], - this.identifierPositionStack[this.identifierPtr--]); - } else { - ref = - new ArrayTypeReference( - this.identifierStack[this.identifierPtr], - dim, - this.identifierPositionStack[this.identifierPtr--]); - ref.sourceEnd = this.endPosition; - } - } else { - this.genericsLengthPtr--; - //Qualified variable reference - char[][] tokens = new char[length][]; - this.identifierPtr -= length; - long[] positions = new long[length]; - System.arraycopy(this.identifierStack, this.identifierPtr + 1, tokens, 0, length); - System.arraycopy( - this.identifierPositionStack, - this.identifierPtr + 1, - positions, - 0, - length); - if (dim == 0) { - ref = new QualifiedTypeReference(tokens, positions); - } else { - ref = new ArrayQualifiedTypeReference(tokens, dim, positions); - ref.sourceEnd = this.endPosition; - } - } - } - return ref; -} -protected NameReference getUnspecifiedReference() { - /* build a (unspecified) NameReference which may be qualified*/ - - int length; - NameReference ref; - if ((length = this.identifierLengthStack[this.identifierLengthPtr--]) == 1) - // single variable reference - ref = - new SingleNameReference( - this.identifierStack[this.identifierPtr], - this.identifierPositionStack[this.identifierPtr--]); - else - //Qualified variable reference - { - char[][] tokens = new char[length][]; - this.identifierPtr -= length; - System.arraycopy(this.identifierStack, this.identifierPtr + 1, tokens, 0, length); - long[] positions = new long[length]; - System.arraycopy(this.identifierPositionStack, this.identifierPtr + 1, positions, 0, length); - ref = - new QualifiedNameReference(tokens, - positions, - (int) (this.identifierPositionStack[this.identifierPtr + 1] >> 32), // sourceStart - (int) this.identifierPositionStack[this.identifierPtr + length]); // sourceEnd - } - return ref; -} -protected NameReference getUnspecifiedReferenceOptimized() { - /* build a (unspecified) NameReference which may be qualified - The optimization occurs for qualified reference while we are - certain in this case the last item of the qualified name is - a field access. This optimization is IMPORTANT while it results - that when a NameReference is build, the type checker should always - look for that it is not a type reference */ - - int length; - NameReference ref; - if ((length = this.identifierLengthStack[this.identifierLengthPtr--]) == 1) { - // single variable reference - ref = - new SingleNameReference( - this.identifierStack[this.identifierPtr], - this.identifierPositionStack[this.identifierPtr--]); - ref.bits &= ~ASTNode.RestrictiveFlagMASK; - ref.bits |= Binding.LOCAL | Binding.FIELD; - return ref; - } - - //Qualified-variable-reference - //In fact it is variable-reference DOT field-ref , but it would result in a type - //conflict tha can be only reduce by making a superclass (or inetrface ) between - //nameReference and FiledReference or putting FieldReference under NameReference - //or else..........This optimisation is not really relevant so just leave as it is - - char[][] tokens = new char[length][]; - this.identifierPtr -= length; - System.arraycopy(this.identifierStack, this.identifierPtr + 1, tokens, 0, length); - long[] positions = new long[length]; - System.arraycopy(this.identifierPositionStack, this.identifierPtr + 1, positions, 0, length); - ref = new QualifiedNameReference( - tokens, - positions, - (int) (this.identifierPositionStack[this.identifierPtr + 1] >> 32), // sourceStart - (int) this.identifierPositionStack[this.identifierPtr + length]); // sourceEnd - ref.bits &= ~ASTNode.RestrictiveFlagMASK; - ref.bits |= Binding.LOCAL | Binding.FIELD; - return ref; -} -public void goForBlockStatementsopt() { - //tells the scanner to go for block statements opt parsing - - this.firstToken = TokenNameTWIDDLE; - this.scanner.recordLineSeparator = false; -} -public void goForProgramElements() { - //tells the scanner to go for block statements opt parsing - - this.firstToken = TokenNamePLUS; - this.scanner.recordLineSeparator = true; -} - -public void goForBlockStatementsOrCatchHeader() { - //tells the scanner to go for block statements or method headers parsing - - this.firstToken = TokenNameMULTIPLY; - this.scanner.recordLineSeparator = false; -} -public void goForClassBodyDeclarations() { - //tells the scanner to go for any body declarations parsing - -// this.firstToken = TokenNameAND; - this.firstToken = TokenNamePLUS; - this.scanner.recordLineSeparator = true; -} -public void goForCompilationUnit(){ - //tells the scanner to go for compilation unit parsing - - this.firstToken = TokenNamePLUS_PLUS ; - this.scanner.foundTaskCount = 0; - this.scanner.recordLineSeparator = true; -} -public void goForExpression() { - //tells the scanner to go for an expression parsing - - this.firstToken = TokenNameREMAINDER; - this.scanner.recordLineSeparator = true; // recovery goals must record line separators -} -public void goForFieldDeclaration(){ - //tells the scanner to go for field declaration parsing - - this.firstToken = TokenNameAND_AND ; - this.scanner.recordLineSeparator = true; -} -public void goForHeaders(){ - //tells the scanner to go for headers only parsing -// RecoveredType currentType = this.currentRecoveryType(); -// if(currentType != null && currentType.insideEnumConstantPart) { -// this.firstToken = TokenNameNOT; -// } else { - this.firstToken = TokenNameUNSIGNED_RIGHT_SHIFT; -// } - this.scanner.recordLineSeparator = true; // recovery goals must record line separators -} -public void goForInitializer(){ - //tells the scanner to go for initializer parsing - - this.firstToken = TokenNameRIGHT_SHIFT ; - this.scanner.recordLineSeparator = false; -} -public void goForMemberValue() { - //tells the scanner to go for a member value parsing - - this.firstToken = TokenNameOR_OR; - this.scanner.recordLineSeparator = true; // recovery goals must record line separators -} -public void goForMethodBody(){ - //tells the scanner to go for method body parsing - - this.firstToken = TokenNameMINUS_MINUS ; - this.scanner.recordLineSeparator = false; -} -public void goForTypeDeclaration() { - //tells the scanner to go for type (interface or class) declaration parsing - - this.firstToken = TokenNamePLUS; - this.scanner.recordLineSeparator = true; -} -protected void ignoreExpressionAssignment() { - // Assignment ::= InvalidArrayInitializerAssignement - // encoded operator would be: this.intStack[this.intPtr] - this.intPtr--; - ArrayInitializer arrayInitializer = (ArrayInitializer) this.expressionStack[this.expressionPtr--]; - this.expressionLengthPtr -- ; -} -public void initialize() { - this.initialize(false); -} -public void initialize(boolean initializeNLS) { - //positionning the parser for a new compilation unit - //avoiding stack reallocation and all that.... - this.astPtr = -1; - this.astLengthPtr = -1; - this.expressionPtr = -1; - this.expressionLengthPtr = -1; - this.identifierPtr = -1; - this.identifierLengthPtr = -1; - this.intPtr = -1; - this.nestedMethod[this.nestedType = 0] = 0; // need to reset for further reuse - this.variablesCounter[this.nestedType] = 0; - this.dimensions = 0 ; - this.realBlockPtr = 0; - this.compilationUnit = null; - this.referenceContext = null; - this.endStatementPosition = 0; - - //remove objects from stack too, while the same parser/compiler couple is - //re-used between two compilations .... - - int astLength = this.astStack.length; - if (this.noAstNodes.length < astLength){ - this.noAstNodes = new ASTNode[astLength]; - //System.out.println("Resized AST stacks : "+ astLength); - - } - System.arraycopy(this.noAstNodes, 0, this.astStack, 0, astLength); - - int expressionLength = this.expressionStack.length; - if (this.noExpressions.length < expressionLength){ - this.noExpressions = new Expression[expressionLength]; - //System.out.println("Resized EXPR stacks : "+ expressionLength); - } - System.arraycopy(this.noExpressions, 0, this.expressionStack, 0, expressionLength); - - // reset this.scanner state - this.scanner.commentPtr = -1; - this.scanner.foundTaskCount = 0; - this.scanner.eofPosition = Integer.MAX_VALUE; - this.recordStringLiterals = true; - final boolean checkNLS = this.options.getSeverity(CompilerOptions.NonExternalizedString) != ProblemSeverities.Ignore; - this.checkExternalizeStrings = checkNLS; - this.scanner.checkNonExternalizedStringLiterals = initializeNLS && checkNLS; - - resetModifiers(); - - // recovery - this.lastCheckPoint = -1; - this.currentElement = null; - this.restartRecovery = false; - this.hasReportedError = false; - this.recoveredStaticInitializerStart = 0; - this.lastIgnoredToken = -1; - this.lastErrorEndPosition = -1; - this.lastErrorEndPositionBeforeRecovery = -1; - this.lastJavadocEnd = -1; - this.listLength = 0; - this.listTypeParameterLength = 0; - - this.rBraceStart = 0; - this.rBraceEnd = 0; - this.rBraceSuccessorStart = 0; - - this.genericsIdentifiersLengthPtr = -1; - this.genericsLengthPtr = -1; - this.genericsPtr = -1; - - this.errorAction= new HashSet(); - -} -public void initializeScanner(){ - this.scanner = new Scanner( - false /*comment*/, - false /*whitespace*/, - false, /* will be set in initialize(boolean) */ - this.options.sourceLevel /*sourceLevel*/, - this.options.complianceLevel /*complianceLevel*/, - this.options.taskTags/*taskTags*/, - this.options.taskPriorites/*taskPriorities*/, - this.options.isTaskCaseSensitive/*taskCaseSensitive*/); -} -public void jumpOverMethodBody() { - //on diet parsing.....do not buffer method statements - - //the scanner.diet is reinitialized to false - //automatically by the scanner once it has jumped over - //the statements - - if (this.diet && (this.dietInt == 0)) - this.scanner.diet = true; -} -private void jumpOverType(){ - if (this.recoveredTypes != null && this.nextTypeStart > -1 && this.nextTypeStart < this.scanner.currentPosition) { - - if (DEBUG_AUTOMATON) { - System.out.println("Jump -"); //$NON-NLS-1$ - } - - TypeDeclaration typeDeclaration = this.recoveredTypes[this.recoveredTypePtr]; - boolean isAnonymous = typeDeclaration.allocation != null; - - int end = this.scanner.eofPosition; - this.scanner.resetTo(typeDeclaration.declarationSourceEnd + 1, end - 1); - if(!isAnonymous) { - ((RecoveryScanner)this.scanner).setPendingTokens(new int[]{TokenNameSEMICOLON, TokenNamebreak}); - } else { - ((RecoveryScanner)this.scanner).setPendingTokens(new int[]{TokenNameIdentifier, TokenNameEQUAL, TokenNameIdentifier}); - } - - this.pendingRecoveredType = typeDeclaration; - - try { - this.currentToken = this.scanner.getNextToken(); - } catch(InvalidInputException e){ - // it's impossible because we added pending tokens before - } - - if(++this.recoveredTypePtr < this.recoveredTypes.length) { - TypeDeclaration nextTypeDeclaration = this.recoveredTypes[this.recoveredTypePtr]; - this.nextTypeStart = - nextTypeDeclaration.allocation == null - ? nextTypeDeclaration.declarationSourceStart - : nextTypeDeclaration.allocation.sourceStart; - } else { - this.nextTypeStart = Integer.MAX_VALUE; - } - } -} -protected void markEnclosingMemberWithLocalType() { - if (this.currentElement != null) return; // this is already done in the recovery code - for (int i = this.astPtr; i >= 0; i--) { - ASTNode node = this.astStack[i]; - if (node instanceof AbstractMethodDeclaration - || node instanceof FieldDeclaration - || (node instanceof TypeDeclaration // mark type for now: all initializers will be marked when added to this type - // and enclosing type must not be closed (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=147485) - && ((TypeDeclaration) node).declarationSourceEnd == 0)) { - node.bits |= ASTNode.HasLocalType; - return; - } - } - // default to reference context (case of parse method body) - if (this.referenceContext instanceof AbstractMethodDeclaration - || this.referenceContext instanceof TypeDeclaration) { - ((ASTNode)this.referenceContext).bits |= ASTNode.HasLocalType; - } -} -protected void markInitializersWithLocalType(TypeDeclaration type) { - if (type.fields == null || (type.bits & ASTNode.HasLocalType) == 0) return; - for (int i = 0, length = type.fields.length; i < length; i++) { - FieldDeclaration field = type.fields[i]; - if (field instanceof Initializer) { - field.bits |= ASTNode.HasLocalType; - } - } -} - -/* - * Move checkpoint location (current implementation is moving it by one token) - * - * Answers true if successfully moved checkpoint (in other words, it did not attempt to move it - * beyond end of file). - */ -protected boolean moveRecoveryCheckpoint() { - - int pos = this.lastCheckPoint; - /* reset this.scanner, and move checkpoint by one token */ - this.scanner.startPosition = pos; - this.scanner.currentPosition = pos; - this.scanner.currentToken=this.scanner.currentNonWhitespaceToken=TokenNameUNKNOWN; - this.scanner.diet = false; // quit jumping over method bodies - - /* if about to restart, then no need to shift token */ - if (this.restartRecovery){ - this.lastIgnoredToken = -1; - this.scanner.insideRecovery = true; - return true; - } - - /* protect against shifting on an invalid token */ - this.lastIgnoredToken = this.nextIgnoredToken; - this.nextIgnoredToken = -1; - do { - try { - this.nextIgnoredToken = this.scanner.getNextToken(); - if(this.scanner.currentPosition == this.scanner.startPosition){ - this.scanner.currentPosition++; // on fake completion identifier - this.nextIgnoredToken = -1; - } - - } catch(InvalidInputException e){ - pos = this.scanner.currentPosition; - } - } while (this.nextIgnoredToken < 0); - - if (this.nextIgnoredToken == TokenNameEOF) { // no more recovery after this point - if (this.currentToken == TokenNameEOF) { // already tried one iteration on EOF - return false; - } - } - this.lastCheckPoint = this.scanner.currentPosition; - - /* reset this.scanner again to previous checkpoint location*/ - this.scanner.startPosition = pos; - this.scanner.currentPosition = pos; - this.scanner.currentToken=TokenNameUNKNOWN; - this.scanner.commentPtr = -1; - this.scanner.foundTaskCount = 0; - return true; - -/* - The following implementation moves the checkpoint location by one line: - - int pos = this.lastCheckPoint; - // reset this.scanner, and move checkpoint by one token - this.scanner.startPosition = pos; - this.scanner.currentPosition = pos; - this.scanner.diet = false; // quit jumping over method bodies - - // if about to restart, then no need to shift token - if (this.restartRecovery){ - this.lastIgnoredToken = -1; - return true; - } - - // protect against shifting on an invalid token - this.lastIgnoredToken = this.nextIgnoredToken; - this.nextIgnoredToken = -1; - - boolean wasTokenizingWhiteSpace = this.scanner.tokenizeWhiteSpace; - this.scanner.tokenizeWhiteSpace = true; - checkpointMove: - do { - try { - this.nextIgnoredToken = this.scanner.getNextToken(); - switch(this.nextIgnoredToken){ - case Scanner.TokenNameWHITESPACE : - if(this.scanner.getLineNumber(this.scanner.startPosition) - == this.scanner.getLineNumber(this.scanner.currentPosition)){ - this.nextIgnoredToken = -1; - } - break; - case TokenNameSEMICOLON : - case TokenNameLBRACE : - case TokenNameRBRACE : - break; - case TokenNameIdentifier : - if(this.scanner.currentPosition == this.scanner.startPosition){ - this.scanner.currentPosition++; // on fake completion identifier - } - default: - this.nextIgnoredToken = -1; - break; - case TokenNameEOF : - break checkpointMove; - } - } catch(InvalidInputException e){ - pos = this.scanner.currentPosition; - } - } while (this.nextIgnoredToken < 0); - this.scanner.tokenizeWhiteSpace = wasTokenizingWhiteSpace; - - if (this.nextIgnoredToken == TokenNameEOF) { // no more recovery after this point - if (this.currentToken == TokenNameEOF) { // already tried one iteration on EOF - return false; - } - } - this.lastCheckPoint = this.scanner.currentPosition; - - // reset this.scanner again to previous checkpoint location - this.scanner.startPosition = pos; - this.scanner.currentPosition = pos; - this.scanner.commentPtr = -1; - - return true; -*/ -} -protected MessageSend newMessageSend() { - // '(' ArgumentListopt ')' - // the arguments are on the expression stack - - MessageSend m = new MessageSend(); - int length; - if ((length = this.expressionLengthStack[this.expressionLengthPtr--]) != 0) { - this.expressionPtr -= length; - System.arraycopy( - this.expressionStack, - this.expressionPtr + 1, - m.arguments = new Expression[length], - 0, - length); - } - return m; -} -protected void optimizedConcatNodeLists() { - /*back from a recursive loop. Virtualy group the - astNode into an array using this.astLengthStack*/ - - /* - * This is a case where you have two sublists into the this.astStack that you want - * to merge in one list. There is no action required on the this.astStack. The only - * thing you need to do is merge the two lengths specified on the astStackLength. - * The top two length are for example: - * ... p n - * and you want to result in a list like: - * ... n+p - * This means that the p could be equals to 0 in case there is no astNode pushed - * on the this.astStack. - * Look at the InterfaceMemberDeclarations for an example. - * This case optimizes the fact that p == 1. - */ - - this.astLengthStack[--this.astLengthPtr]++; -} - -protected boolean isErrorState(int act) { - int stackTop=this.stateStackTop; - int [] tempStack=new int[this.stack.length+2]; - System.arraycopy(this.stack, 0, tempStack, 0, this.stack.length); - boolean first=true; - int currentAction = act; - ProcessTerminals : for (;;) { - int stackLength = tempStack.length; - if (!first) - { - if (++stackTop >= stackLength) { - System.arraycopy( - tempStack, 0, - tempStack = new int[stackLength + StackIncrement], 0, - stackLength); - } - tempStack[stackTop] = currentAction; - } - first=false; - currentAction = tAction(currentAction, this.currentToken); - if (currentAction == ERROR_ACTION) { - return true; - } - if (currentAction <= NUM_RULES) { - stackTop--; - - } else if (currentAction > ERROR_ACTION) { /* shift-reduce */ - if (DEBUG) System.out.println("<>shift-reduce Next Token: "+scanner.dumpCurrent()); -// } catch(InvalidInputException e){ -// if (!this.hasReportedError){ -// this.problemReporter().scannerError(this, e.getMessage()); -// this.hasReportedError = true; -// } -// this.lastCheckPoint = this.scanner.currentPosition; -// this.restartRecovery = true; -// } -// if(this.statementRecoveryActivated) { -// jumpOverTypeAfterReduce = true; -// } -// act -= ERROR_ACTION; - - } else { - if (currentAction < ACCEPT_ACTION) { /* shift */ - if (DEBUG) System.out.println("<>shift next Token: "+scanner.dumpCurrent()); -// } catch(InvalidInputException e){ -// if (!this.hasReportedError){ -// this.problemReporter().scannerError(this, e.getMessage()); -// this.hasReportedError = true; -// } -// this.lastCheckPoint = this.scanner.currentPosition; -// this.restartRecovery = true; -// } -// if(this.statementRecoveryActivated) { -// this.jumpOverType(); -// } -// continue ProcessTerminals; - } - break ProcessTerminals; - } - - // ProcessNonTerminals : - do { /* reduce */ - stackTop -= (rhs[currentAction] - 1); - currentAction = ntAction(tempStack[stackTop], lhs[currentAction]); - } while (currentAction <= NUM_RULES); - } -return false; -} - - -/*main loop of the automat -When a rule is reduced, the method consumeRule(int) is called with the number -of the consumed rule. When a terminal is consumed, the method consumeToken(int) is -called in order to remember (when needed) the consumed token */ -// (int)asr[asi(act)] -// name[symbol_index[currentKind]] -protected void parse() { - if (DEBUG) System.out.println("-- ENTER INSIDE PARSE METHOD --"); //$NON-NLS-1$ - - if (DEBUG_AUTOMATON) { - System.out.println("- Start --------------------------------"); //$NON-NLS-1$ - } - - boolean isDietParse = this.diet; - int oldFirstToken = getFirstToken(); - this.hasError = false; - - this.hasReportedError = false; - boolean insertedSemicolon = false; - int prevAct = START_STATE, - prevToken = getFirstToken(), - prevPos = scanner.startPosition; - - int act = START_STATE; - this.stateStackTop = -1; - this.currentToken = getFirstToken(); - ProcessTerminals : for (;;) { - int stackLength = this.stack.length; - if (++this.stateStackTop >= stackLength) { - System.arraycopy( - this.stack, 0, - this.stack = new int[stackLength + StackIncrement], 0, - stackLength); - } - this.stack[this.stateStackTop] = act; - - if (DEBUG) - System.out.println("action="+act+ ((term_check[base_action[act]+this.currentToken] == this.currentToken)?"":" - take default") ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - prevAct=act; - - if (optionalSemicolonState[act]) - { - if (term_check[base_action[act]+this.currentToken] != this.currentToken) - { - if (isErrorState(act)) - { - if (!insertedSemicolon && shouldInsertSemicolon(prevPos, prevToken) ) - { - currentToken = TokenNameSEMICOLON; - this.insertedSemicolonPosition=prevPos; - scanner.pushBack(); - insertedSemicolon = true; - - } - } - } - } - - act = tAction(act, this.currentToken); - if (act == ERROR_ACTION || this.restartRecovery) { -// if ( act == ERROR_ACTION && -// !insertedSemicolon && -// shouldInsertSemicolon(prevPos, prevToken) -// ) { -// act = prevAct; -// --stateStackTop; -// currentToken = TokenNameSEMICOLON; -// scanner.pushBack(); -// insertedSemicolon = true; -// continue ProcessTerminals; -// } - - if (DEBUG_AUTOMATON) { - if (this.restartRecovery) { - System.out.println("Restart - "); //$NON-NLS-1$ - } else { - System.out.println("Error - "); //$NON-NLS-1$ - } - } - - int errorPos = this.scanner.currentPosition; - if (!this.hasReportedError) { - this.hasError = true; - } - if (resumeOnSyntaxError()) { - if (act == ERROR_ACTION) this.lastErrorEndPosition = errorPos; - act = START_STATE; - this.stateStackTop = -1; - this.currentToken = getFirstToken(); - if (DEBUG) System.out.println("!! Resume on syntax error"); //$NON-NLS-1$ - continue ProcessTerminals; - } - act = ERROR_ACTION; - break ProcessTerminals; - } - if (act <= NUM_RULES) { - insertedSemicolon = false; - this.stateStackTop--; - - if (DEBUG_AUTOMATON) { - System.out.print("Reduce - "); //$NON-NLS-1$ - } - - } else if (act > ERROR_ACTION) { /* shift-reduce */ - if (DEBUG) System.out.println("<>shift-reduce Next Token: "+scanner.dumpCurrent()); //$NON-NLS-1$ - } catch(InvalidInputException e){ - if (!this.hasReportedError){ - this.problemReporter().scannerError(this, e.getMessage()); - this.hasReportedError = true; - } - this.lastCheckPoint = this.scanner.currentPosition; - this.restartRecovery = true; - } - if(this.statementRecoveryActivated) { - this.jumpOverType(); - } - act -= ERROR_ACTION; - - if (DEBUG_AUTOMATON) { - System.out.print("Shift/Reduce - (" + name[terminal_index[this.currentToken]]+") "); //$NON-NLS-1$ //$NON-NLS-2$ - } - - } else { - if (act < ACCEPT_ACTION) { /* shift */ - if (DEBUG) System.out.println("<>shift next Token: "+scanner.dumpCurrent()); //$NON-NLS-1$ - } catch(InvalidInputException e){ - if (!this.hasReportedError){ - this.problemReporter().scannerError(this, e.getMessage()); - this.hasReportedError = true; - } - this.lastCheckPoint = this.scanner.currentPosition; - this.restartRecovery = true; - } - if(this.statementRecoveryActivated) { - this.jumpOverType(); - } - if (DEBUG_AUTOMATON) { - System.out.println("Shift - (" + name[terminal_index[this.currentToken]]+")"); //$NON-NLS-1$ //$NON-NLS-2$ - } - continue ProcessTerminals; - } - break ProcessTerminals; - } - - // ProcessNonTerminals : - do { /* reduce */ - - if (DEBUG_AUTOMATON) { - System.out.println(name[non_terminal_index[lhs[act]]]); - } - - consumeRule(act); - this.stateStackTop -= (rhs[act] - 1); - act = ntAction(this.stack[this.stateStackTop], lhs[act]); - if (DEBUG_AUTOMATON && act <= NUM_RULES) { - System.out.print(" - "); //$NON-NLS-1$ - } - - } while (act <= NUM_RULES); - if (DEBUG_AUTOMATON) { - System.out.println("----------------------------------------"); //$NON-NLS-1$ - } - } - if (DEBUG_AUTOMATON) { - System.out.println("- End ----------------------------------"); //$NON-NLS-1$ - } - - endParse(act); - // record all nls tags in the corresponding compilation unit - final NLSTag[] tags = this.scanner.getNLSTags(); - if (tags != null) { - this.compilationUnit.nlsTags = tags; - } - - this.scanner.checkNonExternalizedStringLiterals = false; - if (this.reportSyntaxErrorIsRequired && this.hasError && !(this.statementRecoveryActivated && DO_DIET_PARSE)) { - if(!this.options.performStatementsRecovery) { - reportSyntaxErrors(isDietParse, oldFirstToken); - } else { - RecoveryScannerData data = this.referenceContext.compilationResult().recoveryScannerData; - - if(this.recoveryScanner == null) { - this.recoveryScanner = new RecoveryScanner(this.scanner, data); - } else { - this.recoveryScanner.setData(data); - } - - this.recoveryScanner.setSource(scanner.source); - this.recoveryScanner.lineEnds = this.scanner.lineEnds; - this.recoveryScanner.linePtr = this.scanner.linePtr; - - reportSyntaxErrors(isDietParse, oldFirstToken); - - if(data == null) { - this.referenceContext.compilationResult().recoveryScannerData = - this.recoveryScanner.getData(); - } - - if (this.methodRecoveryActivated && this.options.performStatementsRecovery && !this.enteredRecoverStatements) { - this.methodRecoveryActivated = false; - this.enteredRecoverStatements=true; - this.recoverStatements(); - this.methodRecoveryActivated = true; - - this.lastAct = ERROR_ACTION; - } - } - } - - if (DEBUG) System.out.println("-- EXIT FROM PARSE METHOD --"); //$NON-NLS-1$ -} -public void parse(ConstructorDeclaration cd, CompilationUnitDeclaration unit) { - parse(cd, unit, false); -} -public void parse(ConstructorDeclaration cd, CompilationUnitDeclaration unit, boolean recordLineSeparator) { - //only parse the method body of cd - //fill out its statements - - //convert bugs into parse error - - boolean oldMethodRecoveryActivated = this.methodRecoveryActivated; - if(this.options.performMethodsFullRecovery) { - this.methodRecoveryActivated = true; - } - - initialize(); - goForBlockStatementsopt(); - if (recordLineSeparator) { - this.scanner.recordLineSeparator = true; - } - this.nestedMethod[this.nestedType]++; - pushOnRealBlockStack(0); - - this.referenceContext = cd; - this.compilationUnit = unit; - - this.scanner.resetTo(cd.bodyStart, cd.bodyEnd); - try { - parse(); - } catch (AbortCompilation ex) { - this.lastAct = ERROR_ACTION; - } finally { - this.nestedMethod[this.nestedType]--; - if(this.options.performStatementsRecovery) { - this.methodRecoveryActivated = oldMethodRecoveryActivated; - } - } - - checkNonNLSAfterBodyEnd(cd.declarationSourceEnd); - - if (this.lastAct == ERROR_ACTION) { - initialize(); - return; - } - - //statements - cd.explicitDeclarations = this.realBlockStack[this.realBlockPtr--]; - int length; - if (astLengthPtr > -1 && (length = this.astLengthStack[this.astLengthPtr--]) != 0) { - this.astPtr -= length; - if (this.astStack[this.astPtr + 1] instanceof ExplicitConstructorCall) - //avoid a isSomeThing that would only be used here BUT what is faster between two alternatives ? - { - System.arraycopy( - this.astStack, - this.astPtr + 2, - cd.statements = new Statement[length - 1], - 0, - length - 1); - cd.constructorCall = (ExplicitConstructorCall) this.astStack[this.astPtr + 1]; - } else { //need to add explicitly the super(); - System.arraycopy( - this.astStack, - this.astPtr + 1, - cd.statements = new Statement[length], - 0, - length); - cd.constructorCall = SuperReference.implicitSuperConstructorCall(); - } - } else { - cd.constructorCall = SuperReference.implicitSuperConstructorCall(); - if (!containsComment(cd.bodyStart, cd.bodyEnd)) { - cd.bits |= ASTNode.UndocumentedEmptyBlock; - } - } - - if (cd.constructorCall.sourceEnd == 0) { - cd.constructorCall.sourceEnd = cd.sourceEnd; - cd.constructorCall.sourceStart = cd.sourceStart; - } -} -// A P I - -public void parse( - FieldDeclaration field, - TypeDeclaration type, - CompilationUnitDeclaration unit, - char[] initializationSource) { - //only parse the initializationSource of the given field - - //convert bugs into parse error - - initialize(); - goForExpression(); - this.nestedMethod[this.nestedType]++; - - this.referenceContext = type; - this.compilationUnit = unit; - - this.scanner.setSource(initializationSource); - this.scanner.resetTo(0, initializationSource.length-1); - try { - parse(); - } catch (AbortCompilation ex) { - this.lastAct = ERROR_ACTION; - } finally { - this.nestedMethod[this.nestedType]--; - } - - if (this.lastAct == ERROR_ACTION) { - return; - } - - field.initialization = this.expressionStack[this.expressionPtr]; - - // mark field with local type if one was found during parsing - if ((type.bits & ASTNode.HasLocalType) != 0) { - field.bits |= ASTNode.HasLocalType; - } -} -// A P I - -public CompilationUnitDeclaration parse( - ICompilationUnit sourceUnit, - CompilationResult compilationResult) { - // parses a compilation unit and manages error handling (even bugs....) - - return parse(sourceUnit, compilationResult, -1, -1/*parse without reseting the scanner*/); -} -// A P I - -public CompilationUnitDeclaration parse( - ICompilationUnit sourceUnit, - CompilationResult compilationResult, - int start, - int end) { - // parses a compilation unit and manages error handling (even bugs....) - - CompilationUnitDeclaration unit; - try { - /* automaton initialization */ - initialize(true); - goForCompilationUnit(); - - /* unit creation */ - this.referenceContext = - this.compilationUnit = - new CompilationUnitDeclaration( - this.problemReporter, - compilationResult, - 0); - - - initializeInferenceEngine(this.compilationUnit); - - /* scanners initialization */ - char[] contents; - try { - contents = sourceUnit.getContents(); - } catch(AbortCompilationUnit abortException) { - this.problemReporter().cannotReadSource(this.compilationUnit, abortException, this.options.verbose); - contents = CharOperation.NO_CHAR; // pretend empty from thereon - } - this.scanner.setSource(contents); - this.compilationUnit.sourceEnd = this.scanner.source.length - 1; - if (end != -1) this.scanner.resetTo(start, end); - if (this.javadocParser != null && this.javadocParser.checkDocComment) { - this.javadocParser.scanner.setSource(contents); - if (end != -1) { - this.javadocParser.scanner.resetTo(start, end); - } - } - /* run automaton */ -if (false) - System.out.println("parsing "+new String(sourceUnit.getFileName())); //$NON-NLS-1$ - parse(); - } finally { - unit = this.compilationUnit; - this.compilationUnit = null; // reset parser - // tag unit has having read bodies - if (!this.diet) unit.bits |= ASTNode.HasAllMethodBodies; - } - return unit; -} - -public void initializeInferenceEngine(CompilationUnitDeclaration compilationUnitDeclaration) { - if (this.inferenceEngines==null) - this.inferenceEngines = InferrenceManager.getInstance().getInferenceEngines(compilationUnitDeclaration); - for (int i = 0; i < this.inferenceEngines.length; i++) { - this.inferenceEngines[i].initializeOptions(this.options.inferOptions); - } -} - -public void parse( - Initializer initializer, - TypeDeclaration type, - CompilationUnitDeclaration unit) { - //only parse the method body of md - //fill out method statements - - //convert bugs into parse error - - boolean oldMethodRecoveryActivated = this.methodRecoveryActivated; - if(this.options.performMethodsFullRecovery) { - this.methodRecoveryActivated = true; - } - - initialize(); - goForBlockStatementsopt(); - this.nestedMethod[this.nestedType]++; - pushOnRealBlockStack(0); - - this.referenceContext = type; - this.compilationUnit = unit; - - this.scanner.resetTo(initializer.bodyStart, initializer.bodyEnd); // just on the beginning { - try { - parse(); - } catch (AbortCompilation ex) { - this.lastAct = ERROR_ACTION; - } finally { - this.nestedMethod[this.nestedType]--; - if(this.options.performStatementsRecovery) { - this.methodRecoveryActivated = oldMethodRecoveryActivated; - } - } - - checkNonNLSAfterBodyEnd(initializer.declarationSourceEnd); - - if (this.lastAct == ERROR_ACTION) { - return; - } - - //refill statements - initializer.block.explicitDeclarations = this.realBlockStack[this.realBlockPtr--]; - int length; - if (astLengthPtr > -1 && (length = this.astLengthStack[this.astLengthPtr--]) > 0) { - System.arraycopy(this.astStack, (this.astPtr -= length) + 1, initializer.block.statements = new Statement[length], 0, length); - } else { - // check whether this block at least contains some comment in it - if (!containsComment(initializer.block.sourceStart, initializer.block.sourceEnd)) { - initializer.block.bits |= ASTNode.UndocumentedEmptyBlock; - } - } - - // mark initializer with local type if one was found during parsing - if ((type.bits & ASTNode.HasLocalType) != 0) { - initializer.bits |= ASTNode.HasLocalType; - } -} -// A P I -public void parse(MethodDeclaration md, CompilationUnitDeclaration unit) { - //only parse the method body of md - //fill out method statements - - //convert bugs into parse error - - if (md.isAbstract()) - return; - if ((md.modifiers & ExtraCompilerModifiers.AccSemicolonBody) != 0) - return; - - boolean oldMethodRecoveryActivated = this.methodRecoveryActivated; - if(this.options.performMethodsFullRecovery) { - this.methodRecoveryActivated = true; - this.rParenPos = md.sourceEnd; - } - initialize(); - goForBlockStatementsopt(); - this.nestedMethod[this.nestedType]++; - pushOnRealBlockStack(0); - - this.referenceContext = md; - this.compilationUnit = unit; - - this.scanner.resetTo(md.bodyStart, md.bodyEnd); - // reset the scanner to parser from { down to } - try { - parse(); - } catch (AbortCompilation ex) { - this.lastAct = ERROR_ACTION; - } finally { - this.nestedMethod[this.nestedType]--; - if(this.options.performStatementsRecovery) { - this.methodRecoveryActivated = oldMethodRecoveryActivated; - } - } - - checkNonNLSAfterBodyEnd(md.declarationSourceEnd); - - if (this.lastAct == ERROR_ACTION) { - return; - } - - //refill statements - md.explicitDeclarations = this.realBlockStack[this.realBlockPtr--]; - int length; - if (astLengthPtr > -1 && (length = this.astLengthStack[this.astLengthPtr--]) != 0) { - System.arraycopy( - this.astStack, - (this.astPtr -= length) + 1, - md.statements = new Statement[length], - 0, - length); - } else { - if (!containsComment(md.bodyStart, md.bodyEnd)) { - md.bits |= ASTNode.UndocumentedEmptyBlock; - } - } -} -public ASTNode[] parseClassBodyDeclarations(char[] source, int offset, int length, CompilationUnitDeclaration unit) { - /* automaton initialization */ - initialize(); - goForClassBodyDeclarations(); - /* scanner initialization */ - this.scanner.setSource(source); - this.scanner.resetTo(offset, offset + length - 1); - if (this.javadocParser != null && this.javadocParser.checkDocComment) { - this.javadocParser.scanner.setSource(source); - this.javadocParser.scanner.resetTo(offset, offset + length - 1); - } - - /* type declaration should be parsed as member type declaration */ - this.nestedType = 1; - - /* unit creation */ - this.referenceContext = unit; - this.compilationUnit = unit; - - /* run automaton */ - try { - parse(); - } catch (AbortCompilation ex) { - this.lastAct = ERROR_ACTION; - } - - if (this.lastAct == ERROR_ACTION || this.hasError) { - return null; - } - int astLength; - if (astLengthPtr > -1 && (astLength = this.astLengthStack[this.astLengthPtr--]) != 0) { - ASTNode[] result = new ASTNode[astLength]; - this.astPtr -= astLength; - System.arraycopy(this.astStack, this.astPtr + 1, result, 0, astLength); - return result; - } - return null; -} -public Expression parseExpression(char[] source, int offset, int length, CompilationUnitDeclaration unit) { - - initialize(); - goForExpression(); - this.nestedMethod[this.nestedType]++; - - this.referenceContext = unit; - this.compilationUnit = unit; - - this.scanner.setSource(source); - this.scanner.resetTo(offset, offset + length - 1); - try { - parse(); - } catch (AbortCompilation ex) { - this.lastAct = ERROR_ACTION; - } finally { - this.nestedMethod[this.nestedType]--; - } - - if (this.lastAct == ERROR_ACTION) { - return null; - } - - return this.expressionStack[this.expressionPtr]; -} -public Expression parseMemberValue(char[] source, int offset, int length, CompilationUnitDeclaration unit) { - - initialize(); - goForMemberValue(); - this.nestedMethod[this.nestedType]++; - - this.referenceContext = unit; - this.compilationUnit = unit; - - this.scanner.setSource(source); - this.scanner.resetTo(offset, offset + length - 1); - try { - parse(); - } catch (AbortCompilation ex) { - this.lastAct = ERROR_ACTION; - } finally { - this.nestedMethod[this.nestedType]--; - } - - if (this.lastAct == ERROR_ACTION) { - return null; - } - - return this.expressionStack[this.expressionPtr]; -} -public void parseStatements(ReferenceContext rc, int start, int end, TypeDeclaration[] types, CompilationUnitDeclaration unit) { - boolean oldStatementRecoveryEnabled = this.statementRecoveryActivated; - this.statementRecoveryActivated = true; - - initialize(); - - if (rc instanceof CompilationUnitDeclaration) - goForCompilationUnit(); - else - goForBlockStatementsopt(); - this.nestedMethod[this.nestedType]++; - pushOnRealBlockStack(0); - - //pushOnAstLengthStack(0); - - this.referenceContext = rc; - this.compilationUnit = unit; - - this.pendingRecoveredType = null; - - if(types != null && types.length > 0) { - this.recoveredTypes = types; - this.recoveredTypePtr = 0; - this.nextTypeStart = - this.recoveredTypes[0].allocation == null - ? this.recoveredTypes[0].declarationSourceStart - : this.recoveredTypes[0].allocation.sourceStart; - } else { - this.recoveredTypes = null; - this.recoveredTypePtr = -1; - this.nextTypeStart = -1; - } - - this.scanner.resetTo(start, end); - // reset the scanner to parser from { down to } - - this.lastCheckPoint = this.scanner.initialPosition; - - - this.stateStackTop = -1; - - try { - parse(); - } catch (AbortCompilation ex) { - this.lastAct = ERROR_ACTION; - } finally { - this.nestedMethod[this.nestedType]--; - this.recoveredTypes = null; - this.statementRecoveryActivated = oldStatementRecoveryEnabled; - } - - checkNonNLSAfterBodyEnd(end); -} -public void persistLineSeparatorPositions() { - if (this.scanner.recordLineSeparator) { - this.compilationUnit.compilationResult.lineSeparatorPositions = this.scanner.getLineEnds(); - } -} -/* - * Prepares the state of the parser to go for BlockStatements. - */ -protected void prepareForBlockStatements() { - this.nestedMethod[this.nestedType = 0] = 1; - this.variablesCounter[this.nestedType] = 0; - this.realBlockStack[this.realBlockPtr = 1] = 0; -} -/** - * Returns this parser's problem reporter initialized with its reference context. - * Also it is assumed that a problem is going to be reported, so initializes - * the compilation result's line positions. - * - * @return ProblemReporter - */ -public ProblemReporter problemReporter(){ - if (this.scanner.recordLineSeparator) { - if (this.compilationUnit!=null) - this.compilationUnit.compilationResult.lineSeparatorPositions = this.scanner.getLineEnds(); - } - this.problemReporter.referenceContext = this.referenceContext; - return this.problemReporter; -} -protected void pushIdentifier() { - /*push the consumeToken on the identifier stack. - Increase the total number of identifier in the stack. - identifierPtr points on the next top */ - - int stackLength = this.identifierStack.length; - if (++this.identifierPtr >= stackLength) { - System.arraycopy( - this.identifierStack, 0, - this.identifierStack = new char[stackLength + 20][], 0, - stackLength); - System.arraycopy( - this.identifierPositionStack, 0, - this.identifierPositionStack = new long[stackLength + 20], 0, - stackLength); - } - this.identifierStack[this.identifierPtr] = this.scanner.getCurrentIdentifierSource(); - this.identifierPositionStack[this.identifierPtr] = - (((long) this.scanner.startPosition) << 32) + (this.scanner.currentPosition - 1); - - stackLength = this.identifierLengthStack.length; - if (++this.identifierLengthPtr >= stackLength) { - System.arraycopy( - this.identifierLengthStack, 0, - this.identifierLengthStack = new int[stackLength + 10], 0, - stackLength); - } - this.identifierLengthStack[this.identifierLengthPtr] = 1; -} -protected void pushIdentifier(int flag) { - /*push a special flag on the stack : - -zero stands for optional Name - -negative number for direct ref to base types. - identifierLengthPtr points on the top */ - - int stackLength = this.identifierLengthStack.length; - if (++this.identifierLengthPtr >= stackLength) { - System.arraycopy( - this.identifierLengthStack, 0, - this.identifierLengthStack = new int[stackLength + 10], 0, - stackLength); - } - this.identifierLengthStack[this.identifierLengthPtr] = flag; -} -protected void pushOnAstLengthStack(int pos) { - - int stackLength = this.astLengthStack.length; - if (++this.astLengthPtr >= stackLength) { - System.arraycopy( - this.astLengthStack, 0, - this.astLengthStack = new int[stackLength + StackIncrement], 0, - stackLength); - } - this.astLengthStack[this.astLengthPtr] = pos; -} -protected void pushOnAstStack(ASTNode node) { - /*add a new obj on top of the ast stack - astPtr points on the top*/ - - int stackLength = this.astStack.length; - if (++this.astPtr >= stackLength) { - System.arraycopy( - this.astStack, 0, - this.astStack = new ASTNode[stackLength + AstStackIncrement], 0, - stackLength); - this.astPtr = stackLength; - } - this.astStack[this.astPtr] = node; - - stackLength = this.astLengthStack.length; - if (++this.astLengthPtr >= stackLength) { - System.arraycopy( - this.astLengthStack, 0, - this.astLengthStack = new int[stackLength + AstStackIncrement], 0, - stackLength); - } - this.astLengthStack[this.astLengthPtr] = 1; -} -protected void pushOnExpressionStack(Expression expr) { - - int stackLength = this.expressionStack.length; - if (++this.expressionPtr >= stackLength) { - System.arraycopy( - this.expressionStack, 0, - this.expressionStack = new Expression[stackLength + ExpressionStackIncrement], 0, - stackLength); - } - this.expressionStack[this.expressionPtr] = expr; - - stackLength = this.expressionLengthStack.length; - if (++this.expressionLengthPtr >= stackLength) { - System.arraycopy( - this.expressionLengthStack, 0, - this.expressionLengthStack = new int[stackLength + ExpressionStackIncrement], 0, - stackLength); - } - this.expressionLengthStack[this.expressionLengthPtr] = 1; -} -protected void pushOnExpressionStackLengthStack(int pos) { - - int stackLength = this.expressionLengthStack.length; - if (++this.expressionLengthPtr >= stackLength) { - System.arraycopy( - this.expressionLengthStack, 0, - this.expressionLengthStack = new int[stackLength + StackIncrement], 0, - stackLength); - } - this.expressionLengthStack[this.expressionLengthPtr] = pos; -} -protected void pushOnGenericsStack(ASTNode node) { - /*add a new obj on top of the generics stack - genericsPtr points on the top*/ - - int stackLength = this.genericsStack.length; - if (++this.genericsPtr >= stackLength) { - System.arraycopy( - this.genericsStack, 0, - this.genericsStack = new ASTNode[stackLength + GenericsStackIncrement], 0, - stackLength); - } - this.genericsStack[this.genericsPtr] = node; - - stackLength = this.genericsLengthStack.length; - if (++this.genericsLengthPtr >= stackLength) { - System.arraycopy( - this.genericsLengthStack, 0, - this.genericsLengthStack = new int[stackLength + GenericsStackIncrement], 0, - stackLength); - } - this.genericsLengthStack[this.genericsLengthPtr] = 1; -} -protected void pushOnGenericsIdentifiersLengthStack(int pos) { - int stackLength = this.genericsIdentifiersLengthStack.length; - if (++this.genericsIdentifiersLengthPtr >= stackLength) { - System.arraycopy( - this.genericsIdentifiersLengthStack, 0, - this.genericsIdentifiersLengthStack = new int[stackLength + GenericsStackIncrement], 0, - stackLength); - } - this.genericsIdentifiersLengthStack[this.genericsIdentifiersLengthPtr] = pos; -} -protected void pushOnGenericsLengthStack(int pos) { - int stackLength = this.genericsLengthStack.length; - if (++this.genericsLengthPtr >= stackLength) { - System.arraycopy( - this.genericsLengthStack, 0, - this.genericsLengthStack = new int[stackLength + GenericsStackIncrement], 0, - stackLength); - } - this.genericsLengthStack[this.genericsLengthPtr] = pos; -} -protected void pushOnIntStack(int pos) { - - int stackLength = this.intStack.length; - if (++this.intPtr >= stackLength) { - System.arraycopy( - this.intStack, 0, - this.intStack = new int[stackLength + StackIncrement], 0, - stackLength); - } - this.intStack[this.intPtr] = pos; -} -protected void pushOnRealBlockStack(int i){ - - int stackLength = this.realBlockStack.length; - if (++this.realBlockPtr >= stackLength) { - System.arraycopy( - this.realBlockStack, 0, - this.realBlockStack = new int[stackLength + StackIncrement], 0, - stackLength); - } - this.realBlockStack[this.realBlockPtr] = i; -} -protected void recoverStatements() { - class MethodVisitor extends ASTVisitor { - public ASTVisitor typeVisitor; - - TypeDeclaration enclosingType; // used only for initializer - - TypeDeclaration[] types = new TypeDeclaration[0]; - int typePtr = -1; - public boolean visit(ConstructorDeclaration constructorDeclaration, ClassScope scope) { - typePtr = -1; - return true; - } - public boolean visit(Initializer initializer, MethodScope scope) { - typePtr = -1; - return true; - } - public boolean visit(MethodDeclaration methodDeclaration,Scope scope) { - typePtr = -1; - return true; - } - public boolean visit(TypeDeclaration typeDeclaration, BlockScope scope) { - return this.visit(typeDeclaration); - } - public boolean visit(TypeDeclaration typeDeclaration, Scope scope) { - return this.visit(typeDeclaration); - } - private boolean visit(TypeDeclaration typeDeclaration) { - if(this.types.length <= ++this.typePtr) { - int length = this.typePtr; - System.arraycopy(this.types, 0, this.types = new TypeDeclaration[length * 2 + 1], 0, length); - } - this.types[this.typePtr] = typeDeclaration; - return false; - } - public void endVisit(ConstructorDeclaration constructorDeclaration, ClassScope scope) { - this.endVisitMethod(constructorDeclaration, scope); - } - public void endVisit(MethodDeclaration methodDeclaration, Scope scope) { - this.endVisitMethod(methodDeclaration, scope); - } - private void endVisitMethod(AbstractMethodDeclaration methodDeclaration, Scope scope) { - TypeDeclaration[] foundTypes = null; -// int length = 0; -// if(this.typePtr > -1) { -// length = this.typePtr + 1; -// foundTypes = new TypeDeclaration[length]; -// System.arraycopy(this.types, 0, foundTypes, 0, length); -// } - ReferenceContext oldContext = Parser.this.referenceContext; - Parser.this.recoveryScanner.resetTo(methodDeclaration.bodyStart, methodDeclaration.bodyEnd); - Scanner oldScanner = Parser.this.scanner; - Parser.this.scanner = Parser.this.recoveryScanner; - Parser.this.parseStatements( - methodDeclaration, - methodDeclaration.bodyStart, - methodDeclaration.bodyEnd, - foundTypes, - compilationUnit); - Parser.this.scanner = oldScanner; - Parser.this.referenceContext = oldContext; - -// for (int i = 0; i < length; i++) { -// foundTypes[i].traverse(typeVisitor, scope); -// } - } - public void endVisit(Initializer initializer, MethodScope scope) { - TypeDeclaration[] foundTypes = null; - int length = 0; - if(this.typePtr > -1) { - length = this.typePtr + 1; - foundTypes = new TypeDeclaration[length]; - System.arraycopy(this.types, 0, foundTypes, 0, length); - } - ReferenceContext oldContext = Parser.this.referenceContext; - Parser.this.recoveryScanner.resetTo(initializer.bodyStart, initializer.bodyEnd); - Scanner oldScanner = Parser.this.scanner; - Parser.this.scanner = Parser.this.recoveryScanner; - Parser.this.parseStatements( - this.enclosingType, - initializer.bodyStart, - initializer.bodyEnd, - foundTypes, - compilationUnit); - Parser.this.scanner = oldScanner; - Parser.this.referenceContext = oldContext; - - for (int i = 0; i < length; i++) { - foundTypes[i].traverse(typeVisitor, scope); - } - } - } - class TypeVisitor extends ASTVisitor { - public MethodVisitor methodVisitor; - - TypeDeclaration[] types = new TypeDeclaration[0]; - int typePtr = -1; - - public void endVisit(TypeDeclaration typeDeclaration, BlockScope scope) { - endVisitType(); - } - public void endVisit(TypeDeclaration typeDeclaration, ClassScope scope) { - endVisitType(); - } - private void endVisitType() { - this.typePtr--; - } - public boolean visit(TypeDeclaration typeDeclaration, BlockScope scope) { - return this.visit(typeDeclaration); - } - public boolean visit(TypeDeclaration typeDeclaration, ClassScope scope) { - return this.visit(typeDeclaration); - } - private boolean visit(TypeDeclaration typeDeclaration) { - if(this.types.length <= ++this.typePtr) { - int length = this.typePtr; - System.arraycopy(this.types, 0, this.types = new TypeDeclaration[length * 2 + 1], 0, length); - } - this.types[this.typePtr] = typeDeclaration; - return true; - } - public boolean visit(ConstructorDeclaration constructorDeclaration, ClassScope scope) { - if(constructorDeclaration.isDefaultConstructor()) return false; - - constructorDeclaration.traverse(methodVisitor, scope); - return false; - } - public boolean visit(Initializer initializer, MethodScope scope) { - methodVisitor.enclosingType = this.types[typePtr]; - initializer.traverse(methodVisitor, scope); - return false; - } - public boolean visit(MethodDeclaration methodDeclaration, Scope scope) { - methodDeclaration.traverse(methodVisitor, scope); - return false; - } - } - - if (false) - { - MethodVisitor methodVisitor = new MethodVisitor(); - TypeVisitor typeVisitor = new TypeVisitor(); - methodVisitor.typeVisitor = typeVisitor; - typeVisitor.methodVisitor = methodVisitor; - - if(this.referenceContext instanceof AbstractMethodDeclaration) { - ((AbstractMethodDeclaration)this.referenceContext).traverse(methodVisitor, (Scope)null); - }else if(this.referenceContext instanceof CompilationUnitDeclaration) { - CompilationUnitDeclaration compilationUnitDeclaration=(CompilationUnitDeclaration)this.referenceContext; - if (compilationUnitDeclaration.statements!=null) - for (int i = 0; i < compilationUnitDeclaration.statements.length; i++) { - if( compilationUnitDeclaration.statements[i] instanceof AbstractMethodDeclaration) - ((AbstractMethodDeclaration)compilationUnitDeclaration.statements[i] ).traverse(methodVisitor, (Scope)null); - } - } else if(this.referenceContext instanceof TypeDeclaration) { - TypeDeclaration typeContext = (TypeDeclaration)this.referenceContext; - - int length = typeContext.fields.length; - for (int i = 0; i < length; i++) { - final FieldDeclaration fieldDeclaration = typeContext.fields[i]; - switch(fieldDeclaration.getKind()) { - case AbstractVariableDeclaration.INITIALIZER: - methodVisitor.enclosingType = typeContext; - ((Initializer) fieldDeclaration).traverse(methodVisitor, (MethodScope)null); - break; - } - } - } - } - else - { - CompilationUnitDeclaration compilationUnitDeclaration=(CompilationUnitDeclaration)this.referenceContext; - - ReferenceContext oldContext = Parser.this.referenceContext; - int start = compilationUnitDeclaration.sourceStart; - int end = compilationUnitDeclaration.sourceEnd; - Parser.this.recoveryScanner.resetTo(start, end); - Scanner oldScanner = Parser.this.scanner; - Parser.this.scanner = Parser.this.recoveryScanner; - /* unit creation */ - this.referenceContext = - this.compilationUnit = compilationUnitDeclaration= - new CompilationUnitDeclaration( - this.problemReporter, - compilationUnitDeclaration.compilationResult, - end); - - Parser.this.parseStatements( - compilationUnitDeclaration, - start, - end, - null, - compilationUnit); - Parser.this.scanner = oldScanner; - Parser.this.referenceContext = oldContext; - } - - -} - -public void recoveryExitFromVariable() { - if(this.currentElement != null && this.currentElement.parent != null) { - if(this.currentElement instanceof RecoveredLocalVariable) { - - int end = ((RecoveredLocalVariable)this.currentElement).localDeclaration.sourceEnd; - this.currentElement.updateSourceEndIfNecessary(end); - this.currentElement = this.currentElement.parent; - } else if(this.currentElement instanceof RecoveredField - && !(this.currentElement instanceof RecoveredInitializer)) { - - int end = ((RecoveredField)this.currentElement).fieldDeclaration.sourceEnd; - this.currentElement.updateSourceEndIfNecessary(end); - this.currentElement = this.currentElement.parent; - } - } -} -/* Token check performed on every token shift once having entered - * recovery mode. - */ -public void recoveryTokenCheck() { - switch (this.currentToken) { - case TokenNameLBRACE : - RecoveredElement newElement = null; - if(!this.ignoreNextOpeningBrace) { - newElement = this.currentElement.updateOnOpeningBrace(this.scanner.startPosition - 1, this.scanner.currentPosition - 1); - } - this.lastCheckPoint = this.scanner.currentPosition; - if (newElement != null){ // null means nothing happened - this.restartRecovery = true; // opening brace detected - this.currentElement = newElement; - } - break; - - case TokenNameRBRACE : - this.rBraceStart = this.scanner.startPosition - 1; - this.rBraceEnd = this.scanner.currentPosition - 1; - this.endPosition = this.flushCommentsDefinedPriorTo(this.rBraceEnd); - newElement = - this.currentElement.updateOnClosingBrace(this.scanner.startPosition, this.rBraceEnd); - this.lastCheckPoint = this.scanner.currentPosition; - if (newElement != this.currentElement){ - this.currentElement = newElement; -// if (newElement instanceof RecoveredField && this.dietInt <= 0) { -// if (((RecoveredField)newElement).fieldDeclaration.type == null) { // enum constant -// this.isInsideEnumConstantPart = true; // restore status -// } -// } - } - break; - case TokenNameSEMICOLON : - this.endStatementPosition = this.scanner.currentPosition - 1; - this.endPosition = this.scanner.startPosition - 1; - this.lastCheckPoint=this.scanner.currentPosition; -// RecoveredType currentType = this.currentRecoveryType(); -// if(currentType != null) { -// currentType.insideEnumConstantPart = false; -// } - // fall through - default : { - if (this.rBraceEnd > this.rBraceSuccessorStart && this.scanner.currentPosition != this.scanner.startPosition){ - this.rBraceSuccessorStart = this.scanner.startPosition; - } - break; - } - } - this.ignoreNextOpeningBrace = false; -} - -protected boolean shouldInsertSemicolon(int prevpos, int prevtoken) { - Integer position = new Integer(prevpos); - if (this.errorAction.contains(position)) { - // should not insert a semi-colon at a location that has already be tried - return false; - } - this.errorAction.add(position); - return this.currentToken == TokenNameRBRACE - || scanner.getLineNumber(scanner.currentPosition) > scanner.getLineNumber(prevpos) - || this.currentToken==TokenNameEOF; -} - -// A P I -protected void reportSyntaxErrors(boolean isDietParse, int oldFirstToken) { - if(this.referenceContext instanceof MethodDeclaration) { - MethodDeclaration methodDeclaration = (MethodDeclaration) this.referenceContext; - if(methodDeclaration.errorInSignature){ - return; - } - } - this.compilationUnit.compilationResult.lineSeparatorPositions = this.scanner.getLineEnds(); - this.scanner.recordLineSeparator = false; - - int start = this.scanner.initialPosition; - int end = this.scanner.eofPosition == Integer.MAX_VALUE ? this.scanner.eofPosition : this.scanner.eofPosition - 1; - if(isDietParse) { - ProgramElement[] statements = this.compilationUnit.statements; -// TypeDeclaration[] types = this.compilationUnit.types; - int[][] intervalToSkip = org.eclipse.wst.jsdt.internal.compiler.parser.diagnose.RangeUtil.computeDietRange(statements); -// int[][] intervalToSkip = org.eclipse.wst.jsdt.internal.compiler.parser.diagnose.RangeUtil.computeDietRange(types); - DiagnoseParser diagnoseParser = new DiagnoseParser(this, oldFirstToken, start, end, intervalToSkip[0], intervalToSkip[1], intervalToSkip[2], this.options); - diagnoseParser.diagnoseParse(false); - - reportSyntaxErrorsForSkippedMethod(statements); -// reportSyntaxErrorsForSkippedMethod(types); - this.scanner.resetTo(start, end); - } else { - DiagnoseParser diagnoseParser = new DiagnoseParser(this, oldFirstToken, start, end, this.options); - diagnoseParser.diagnoseParse(this.options.performStatementsRecovery); - } -} -private void reportSyntaxErrorsForSkippedMethod(ProgramElement[] statements){ - if(statements != null) { - for (int i = 0; i < statements.length; i++) { -// TypeDeclaration[] memberTypes = types[i].memberTypes; -// if(memberTypes != null) { -// reportSyntaxErrorsForSkippedMethod(memberTypes); -// } -// -// AbstractMethodDeclaration[] methods = types[i].methods; -// if(methods != null) { -// for (int j = 0; j < methods.length; j++) { - if (statements[i] instanceof AbstractMethodDeclaration ) - { - AbstractMethodDeclaration method = (AbstractMethodDeclaration)statements[i] ; - if(method.errorInSignature) { - DiagnoseParser diagnoseParser = new DiagnoseParser(this, TokenNameDIVIDE, method.declarationSourceStart, method.declarationSourceEnd, this.options); - diagnoseParser.diagnoseParse(this.options.performStatementsRecovery); - } -// } - } - else if (statements[i] instanceof FieldDeclaration ) - { -// FieldDeclaration field =(FieldDeclaration) statements[i] ; -// if (fields != null) { -// int length = fields.length; -// for (int j = 0; j < length; j++) { -// if (fields[j] instanceof Initializer) { -// Initializer initializer = (Initializer)fields[j]; -// if(initializer.errorInSignature){ -// DiagnoseParser diagnoseParser = new DiagnoseParser(this, TokenNameRIGHT_SHIFT, initializer.declarationSourceStart, initializer.declarationSourceEnd, this.options); -// diagnoseParser.diagnoseParse(this.options.performStatementsRecovery); -// } -// } -// } - } - } - } -} -protected void resetModifiers() { - this.modifiers = ClassFileConstants.AccDefault; - this.modifiersSourceStart = -1; // <-- see comment into modifiersFlag(int) - this.scanner.commentPtr = -1; -} -/* - * Reset context so as to resume to regular parse loop - */ -protected void resetStacks() { - - this.astPtr = -1; - this.astLengthPtr = -1; - this.expressionPtr = -1; - this.expressionLengthPtr = -1; - this.identifierPtr = -1; - this.identifierLengthPtr = -1; - this.intPtr = -1; - this.nestedMethod[this.nestedType = 0] = 0; // need to reset for further reuse - this.variablesCounter[this.nestedType] = 0; - this.dimensions = 0 ; - this.realBlockStack[this.realBlockPtr = 0] = 0; - this.recoveredStaticInitializerStart = 0; - this.listLength = 0; - this.listTypeParameterLength = 0; - - this.genericsIdentifiersLengthPtr = -1; - this.genericsLengthPtr = -1; - this.genericsPtr = -1; - this.errorAction = new HashSet(); -} -/* - * Reset context so as to resume to regular parse loop - * If unable to reset for resuming, answers false. - * - * Move checkpoint location, reset internal stacks and - * decide which grammar goal is activated. - */ -protected boolean resumeAfterRecovery() { - if(!this.methodRecoveryActivated && !this.statementRecoveryActivated) { - - // reset internal stacks - this.resetStacks(); - this.resetModifiers(); - - /* attempt to move checkpoint location */ - if (!this.moveRecoveryCheckpoint()) { - return false; - } - - // only look for headers - if (this.referenceContext instanceof CompilationUnitDeclaration){ - if (DO_DIET_PARSE) - { - goForHeaders(); - this.diet = true; // passed this point, will not consider method bodies - } - else - goForProgramElements(); - return true; - } - - // does not know how to restart - return false; - } else if(!this.statementRecoveryActivated || !DO_DIET_PARSE) { - - // reset internal stacks - this.resetStacks(); - this.resetModifiers(); - - /* attempt to move checkpoint location */ - if (!this.moveRecoveryCheckpoint()) { - return false; - } - - // only look for headers - if (DO_DIET_PARSE) - goForHeaders(); - else - goForProgramElements(); - return true; - } else { - return false; - } -} -protected boolean resumeOnSyntaxError() { - this.checkExternalizeStrings = false; - this.scanner.checkNonExternalizedStringLiterals = false; - /* request recovery initialization */ - if (this.currentElement == null){ - // Reset javadoc before restart parsing after recovery - this.javadoc = null; - - // do not investigate deeper in statement recovery - if (this.statementRecoveryActivated) return false; - - // build some recovered elements - this.currentElement = buildInitialRecoveryState(); - } - /* do not investigate deeper in recovery when no recovered element */ - if (this.currentElement == null) return false; - - /* manual forced recovery restart - after headers */ - if (this.restartRecovery){ - this.restartRecovery = false; - } - /* update recovery state with current error state of the parser */ - this.updateRecoveryState(); - - /* attempt to reset state in order to resume to parse loop */ - return this.resumeAfterRecovery(); -} -public void setMethodsFullRecovery(boolean enabled) { - this.options.performMethodsFullRecovery = enabled; -} -public void setStatementsRecovery(boolean enabled) { - if(enabled) this.options.performMethodsFullRecovery = true; - this.options.performStatementsRecovery = enabled; -} -public String toString() { - - - String s = "lastCheckpoint : int = " + String.valueOf(this.lastCheckPoint) + "\n"; //$NON-NLS-1$ //$NON-NLS-2$ - s = s + "identifierStack : char["+(this.identifierPtr + 1)+"][] = {"; //$NON-NLS-1$ //$NON-NLS-2$ - for (int i = 0; i <= this.identifierPtr; i++) { - s = s + "\"" + String.valueOf(this.identifierStack[i]) + "\","; //$NON-NLS-1$ //$NON-NLS-2$ - } - s = s + "}\n"; //$NON-NLS-1$ - - s = s + "identifierLengthStack : int["+(this.identifierLengthPtr + 1)+"] = {"; //$NON-NLS-1$ //$NON-NLS-2$ - for (int i = 0; i <= this.identifierLengthPtr; i++) { - s = s + this.identifierLengthStack[i] + ","; //$NON-NLS-1$ - } - s = s + "}\n"; //$NON-NLS-1$ - - s = s + "astLengthStack : int["+(this.astLengthPtr + 1)+"] = {"; //$NON-NLS-1$ //$NON-NLS-2$ - for (int i = 0; i <= this.astLengthPtr; i++) { - s = s + this.astLengthStack[i] + ","; //$NON-NLS-1$ - } - s = s + "}\n"; //$NON-NLS-1$ - s = s + "astPtr : int = " + String.valueOf(this.astPtr) + "\n"; //$NON-NLS-1$ //$NON-NLS-2$ - - s = s + "intStack : int["+(this.intPtr + 1)+"] = {"; //$NON-NLS-1$ //$NON-NLS-2$ - for (int i = 0; i <= this.intPtr; i++) { - s = s + this.intStack[i] + ","; //$NON-NLS-1$ - } - s = s + "}\n"; //$NON-NLS-1$ - s = s + "intPtr : int = " + String.valueOf(this.intPtr) + "\n"; //$NON-NLS-1$ //$NON-NLS-2$ - - s = s + "expressionLengthStack : int["+(this.expressionLengthPtr + 1)+"] = {"; //$NON-NLS-1$ //$NON-NLS-2$ - for (int i = 0; i <= this.expressionLengthPtr; i++) { - s = s + this.expressionLengthStack[i] + ","; //$NON-NLS-1$ - } - s = s + "}\n"; //$NON-NLS-1$ - - s = s + "expressionPtr : int = " + String.valueOf(this.expressionPtr) + "\n"; //$NON-NLS-1$ //$NON-NLS-2$ - - s = s + "genericsIdentifiersLengthStack : int["+(this.genericsIdentifiersLengthPtr + 1)+"] = {"; //$NON-NLS-1$ //$NON-NLS-2$ - for (int i = 0; i <= this.genericsIdentifiersLengthPtr; i++) { - s = s + this.genericsIdentifiersLengthStack[i] + ","; //$NON-NLS-1$ - } - s = s + "}\n"; //$NON-NLS-1$ - - s = s + "genericsLengthStack : int["+(this.genericsLengthPtr + 1)+"] = {"; //$NON-NLS-1$ //$NON-NLS-2$ - for (int i = 0; i <= this.genericsLengthPtr; i++) { - s = s + this.genericsLengthStack[i] + ","; //$NON-NLS-1$ - } - s = s + "}\n"; //$NON-NLS-1$ - - s = s + "genericsPtr : int = " + String.valueOf(this.genericsPtr) + "\n"; //$NON-NLS-1$ //$NON-NLS-2$ - - s = s + "\n\n\n----------------Scanner--------------\n" + this.scanner.toString(); //$NON-NLS-1$ - return s; - -} -/* - * Update recovery state based on current parser/scanner state - */ -protected void updateRecoveryState() { - - /* expose parser state to recovery state */ - this.currentElement.updateFromParserState(); - - /* check and update recovered state based on current token, - this action is also performed when shifting token after recovery - got activated once. - */ - this.recoveryTokenCheck(); -} -protected void updateSourceDeclarationParts(int variableDeclaratorsCounter) { - //fields is a definition of fields that are grouped together like in - //public int[] a, b[], c - //which results into 3 fields. - - FieldDeclaration field; - int endTypeDeclarationPosition = - -1 + this.astStack[this.astPtr - variableDeclaratorsCounter + 1].sourceStart; - for (int i = 0; i < variableDeclaratorsCounter - 1; i++) { - //last one is special(see below) - field = (FieldDeclaration) this.astStack[this.astPtr - i - 1]; - field.endPart1Position = endTypeDeclarationPosition; - field.endPart2Position = -1 + this.astStack[this.astPtr - i].sourceStart; - } - //last one - (field = (FieldDeclaration) this.astStack[this.astPtr]).endPart1Position = - endTypeDeclarationPosition; - field.endPart2Position = field.declarationSourceEnd; - -} -protected void updateSourcePosition(Expression exp) { - //update the source Position of the expression - - //this.intStack : int int - //--> - //this.intStack : - - exp.sourceEnd = this.intStack[this.intPtr--]; - exp.sourceStart = this.intStack[this.intPtr--]; -} - -public void inferTypes(CompilationUnitDeclaration parsedUnit, CompilerOptions compileOptions) { - if (parsedUnit.typesHaveBeenInferred) - return; - if (compileOptions==null) - compileOptions=this.options; - - if (this.inferenceEngines==null) - initializeInferenceEngine(parsedUnit); -// InferEngine inferEngine=compileOptions.inferOptions.createEngine(); - for (int i=0;i bug 224333 + *******************************************************************************/ +package org.eclipse.wst.jsdt.internal.compiler.parser; + +import java.io.BufferedInputStream; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.MissingResourceException; +import java.util.ResourceBundle; +import java.util.Set; + +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.PerformanceStats; +import org.eclipse.core.runtime.Platform; +import org.eclipse.core.runtime.Status; +import org.eclipse.wst.jsdt.core.JavaScriptCore; +import org.eclipse.wst.jsdt.core.ast.IDoStatement; +import org.eclipse.wst.jsdt.core.compiler.CharOperation; +import org.eclipse.wst.jsdt.core.compiler.InvalidInputException; +import org.eclipse.wst.jsdt.core.infer.IInferEngine; +import org.eclipse.wst.jsdt.core.infer.IInferEngineExtension; +import org.eclipse.wst.jsdt.core.infer.InferOptions; +import org.eclipse.wst.jsdt.core.infer.InferrenceManager; +import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor; +import org.eclipse.wst.jsdt.internal.compiler.CompilationResult; +import org.eclipse.wst.jsdt.internal.compiler.ast.AND_AND_Expression; +import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode; +import org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration; +import org.eclipse.wst.jsdt.internal.compiler.ast.AbstractVariableDeclaration; +import org.eclipse.wst.jsdt.internal.compiler.ast.AllocationExpression; +import org.eclipse.wst.jsdt.internal.compiler.ast.Argument; +import org.eclipse.wst.jsdt.internal.compiler.ast.ArrayInitializer; +import org.eclipse.wst.jsdt.internal.compiler.ast.ArrayQualifiedTypeReference; +import org.eclipse.wst.jsdt.internal.compiler.ast.ArrayReference; +import org.eclipse.wst.jsdt.internal.compiler.ast.ArrayTypeReference; +import org.eclipse.wst.jsdt.internal.compiler.ast.Assignment; +import org.eclipse.wst.jsdt.internal.compiler.ast.BinaryExpression; +import org.eclipse.wst.jsdt.internal.compiler.ast.Block; +import org.eclipse.wst.jsdt.internal.compiler.ast.BreakStatement; +import org.eclipse.wst.jsdt.internal.compiler.ast.CaseStatement; +import org.eclipse.wst.jsdt.internal.compiler.ast.CombinedBinaryExpression; +import org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration; +import org.eclipse.wst.jsdt.internal.compiler.ast.CompoundAssignment; +import org.eclipse.wst.jsdt.internal.compiler.ast.ConditionalExpression; +import org.eclipse.wst.jsdt.internal.compiler.ast.ConstructorDeclaration; +import org.eclipse.wst.jsdt.internal.compiler.ast.ContinueStatement; +import org.eclipse.wst.jsdt.internal.compiler.ast.DebuggerStatement; +import org.eclipse.wst.jsdt.internal.compiler.ast.DoStatement; +import org.eclipse.wst.jsdt.internal.compiler.ast.DoubleLiteral; +import org.eclipse.wst.jsdt.internal.compiler.ast.EmptyExpression; +import org.eclipse.wst.jsdt.internal.compiler.ast.EmptyStatement; +import org.eclipse.wst.jsdt.internal.compiler.ast.EqualExpression; +import org.eclipse.wst.jsdt.internal.compiler.ast.ExplicitConstructorCall; +import org.eclipse.wst.jsdt.internal.compiler.ast.Expression; +import org.eclipse.wst.jsdt.internal.compiler.ast.FalseLiteral; +import org.eclipse.wst.jsdt.internal.compiler.ast.FieldDeclaration; +import org.eclipse.wst.jsdt.internal.compiler.ast.FieldReference; +import org.eclipse.wst.jsdt.internal.compiler.ast.ForInStatement; +import org.eclipse.wst.jsdt.internal.compiler.ast.ForStatement; +import org.eclipse.wst.jsdt.internal.compiler.ast.FunctionExpression; +import org.eclipse.wst.jsdt.internal.compiler.ast.IfStatement; +import org.eclipse.wst.jsdt.internal.compiler.ast.ImportReference; +import org.eclipse.wst.jsdt.internal.compiler.ast.Initializer; +import org.eclipse.wst.jsdt.internal.compiler.ast.IntLiteral; +import org.eclipse.wst.jsdt.internal.compiler.ast.IntLiteralMinValue; +import org.eclipse.wst.jsdt.internal.compiler.ast.Javadoc; +import org.eclipse.wst.jsdt.internal.compiler.ast.LabeledStatement; +import org.eclipse.wst.jsdt.internal.compiler.ast.ListExpression; +import org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration; +import org.eclipse.wst.jsdt.internal.compiler.ast.MessageSend; +import org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration; +import org.eclipse.wst.jsdt.internal.compiler.ast.NameReference; +import org.eclipse.wst.jsdt.internal.compiler.ast.NullLiteral; +import org.eclipse.wst.jsdt.internal.compiler.ast.OR_OR_Expression; +import org.eclipse.wst.jsdt.internal.compiler.ast.ObjectGetterSetterField; +import org.eclipse.wst.jsdt.internal.compiler.ast.ObjectLiteral; +import org.eclipse.wst.jsdt.internal.compiler.ast.ObjectLiteralField; +import org.eclipse.wst.jsdt.internal.compiler.ast.OperatorIds; +import org.eclipse.wst.jsdt.internal.compiler.ast.PostfixExpression; +import org.eclipse.wst.jsdt.internal.compiler.ast.PrefixExpression; +import org.eclipse.wst.jsdt.internal.compiler.ast.ProgramElement; +import org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedNameReference; +import org.eclipse.wst.jsdt.internal.compiler.ast.QualifiedTypeReference; +import org.eclipse.wst.jsdt.internal.compiler.ast.Reference; +import org.eclipse.wst.jsdt.internal.compiler.ast.RegExLiteral; +import org.eclipse.wst.jsdt.internal.compiler.ast.ReturnStatement; +import org.eclipse.wst.jsdt.internal.compiler.ast.SingleNameReference; +import org.eclipse.wst.jsdt.internal.compiler.ast.SingleTypeReference; +import org.eclipse.wst.jsdt.internal.compiler.ast.Statement; +import org.eclipse.wst.jsdt.internal.compiler.ast.StringLiteral; +import org.eclipse.wst.jsdt.internal.compiler.ast.SuperReference; +import org.eclipse.wst.jsdt.internal.compiler.ast.SwitchStatement; +import org.eclipse.wst.jsdt.internal.compiler.ast.ThisReference; +import org.eclipse.wst.jsdt.internal.compiler.ast.ThrowStatement; +import org.eclipse.wst.jsdt.internal.compiler.ast.TrueLiteral; +import org.eclipse.wst.jsdt.internal.compiler.ast.TryStatement; +import org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration; +import org.eclipse.wst.jsdt.internal.compiler.ast.TypeReference; +import org.eclipse.wst.jsdt.internal.compiler.ast.UnaryExpression; +import org.eclipse.wst.jsdt.internal.compiler.ast.UndefinedLiteral; +import org.eclipse.wst.jsdt.internal.compiler.ast.WhileStatement; +import org.eclipse.wst.jsdt.internal.compiler.ast.WithStatement; +import org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants; +import org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit; +import org.eclipse.wst.jsdt.internal.compiler.impl.CompilerOptions; +import org.eclipse.wst.jsdt.internal.compiler.impl.ReferenceContext; +import org.eclipse.wst.jsdt.internal.compiler.lookup.Binding; +import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope; +import org.eclipse.wst.jsdt.internal.compiler.lookup.ClassScope; +import org.eclipse.wst.jsdt.internal.compiler.lookup.ExtraCompilerModifiers; +import org.eclipse.wst.jsdt.internal.compiler.lookup.MethodScope; +import org.eclipse.wst.jsdt.internal.compiler.lookup.Scope; +import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeConstants; +import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeIds; +import org.eclipse.wst.jsdt.internal.compiler.parser.diagnose.DiagnoseParser; +import org.eclipse.wst.jsdt.internal.compiler.problem.AbortCompilation; +import org.eclipse.wst.jsdt.internal.compiler.problem.AbortCompilationUnit; +import org.eclipse.wst.jsdt.internal.compiler.problem.ProblemReporter; +import org.eclipse.wst.jsdt.internal.compiler.problem.ProblemSeverities; +import org.eclipse.wst.jsdt.internal.compiler.util.Messages; +import org.eclipse.wst.jsdt.internal.compiler.util.Util; + +public class Parser implements ParserBasicInformation, TerminalTokens, OperatorIds, TypeIds { + + private static final String PERFORMANCE__INFER_TYPES = "org.eclipse.wst.jsdt.core/perf/Parser/inferTypes"; //$NON-NLS-1$ + private static final boolean REPORT_PERFORMANCE__INFER_TYPES = Boolean.valueOf(Platform.getDebugOption("org.eclipse.wst.jsdt.core/perfReport/Parser/inferTypes")).booleanValue(); //$NON-NLS-1$ + + public static final boolean DO_DIET_PARSE=false; + + protected static final int THIS_CALL = ExplicitConstructorCall.This; + + public static char asb[] = null; + public static char asr[] = null; + //ast stack + protected final static int AstStackIncrement = 100; + public static char base_action[] = null; + public static final int BracketKinds = 3; + + public static short check_table[] = null; + public static final int CurlyBracket = 2; + private static final boolean DEBUG = false; + private static final boolean DEBUG_AUTOMATON = false; + private static final String EOF_TOKEN = "$eof" ; //$NON-NLS-1$ + private static final String ERROR_TOKEN = "$error" ; //$NON-NLS-1$ + //expression stack + protected final static int ExpressionStackIncrement = 100; + + protected final static int GenericsStackIncrement = 10; + + private final static String FILEPREFIX = "parser"; //$NON-NLS-1$ + public static char in_symb[] = null; + private static final String INVALID_CHARACTER = "Invalid Character" ; //$NON-NLS-1$ + public static char lhs[] = null; + + public static String name[] = null; + public static char nasb[] = null; + public static char nasr[] = null; + public static char non_terminal_index[] = null; + private final static String READABLE_NAMES_FILE = "readableNames"; //$NON-NLS-1$ + private final static String READABLE_NAMES_FILE_NAME = + "org.eclipse.wst.jsdt.internal.compiler.parser." + READABLE_NAMES_FILE; //$NON-NLS-1$ + public static String readableName[] = null; + + public static byte rhs[] = null; + + public static int[] reverse_index = null; + public static char[] recovery_templates_index = null; + public static char[] recovery_templates = null; + public static char[] statements_recovery_filter = null; + public static byte[] state_flags = null; + + public static long rules_compliance[] = null; + + public static final int RoundBracket = 0; + + public static byte scope_la[] = null; + public static char scope_lhs[] = null; + + public static char scope_prefix[] = null; + public static char scope_rhs[] = null; + public static char scope_state[] = null; + + public static char scope_state_set[] = null; + public static char scope_suffix[] = null; + public static final int SquareBracket = 1; + + //internal data for the automat + protected final static int StackIncrement = 255; + + public static char term_action[] = null; + public static byte term_check[] = null; + + public static char terminal_index[] = null; + + private static final String UNEXPECTED_EOF = "Unexpected End Of File" ; //$NON-NLS-1$ + public static boolean VERBOSE_RECOVERY = false; + + + static boolean optionalSemicolonState[] =null; + + + protected int astLengthPtr; + protected int[] astLengthStack; + protected int astPtr; + protected ASTNode[] astStack = new ASTNode[AstStackIncrement]; + public CompilationUnitDeclaration compilationUnit; /*the result from parse()*/ + protected RecoveredElement currentElement; + public int currentToken; + protected boolean diet = false; //tells the scanner to jump over some parts of the code/expressions like method bodies + protected int dietInt = 0; // if > 0 force the none-diet-parsing mode (even if diet if requested) [field parsing with anonymous inner classes...] + protected int endPosition; //accurate only when used ! (the start position is pushed into intStack while the end the current one) + protected int endStatementPosition; + protected int expressionLengthPtr; + protected int[] expressionLengthStack; + protected int expressionPtr; + protected Expression[] expressionStack = new Expression[ExpressionStackIncrement]; + public int firstToken ; // handle for multiple parsing goals + + // generics management + protected int genericsIdentifiersLengthPtr; + protected int[] genericsIdentifiersLengthStack = new int[GenericsStackIncrement]; + protected int genericsLengthPtr; + protected int[] genericsLengthStack = new int[GenericsStackIncrement]; + protected int genericsPtr; + protected ASTNode[] genericsStack = new ASTNode[GenericsStackIncrement]; + + protected boolean hasError; + protected boolean hasReportedError; + + //identifiers stacks + protected int identifierLengthPtr; + protected int[] identifierLengthStack; + protected long[] identifierPositionStack; + protected int identifierPtr; + protected char[][] identifierStack; + + protected boolean ignoreNextOpeningBrace; + //positions , dimensions , .... (int stacks) + protected int intPtr; + protected int[] intStack; + public int lastAct ; //handle for multiple parsing goals + + //error recovery management + protected int lastCheckPoint; + protected int lastErrorEndPosition; + protected int lastErrorEndPositionBeforeRecovery = -1; + protected int lastIgnoredToken, nextIgnoredToken; + protected int listLength; // for recovering some incomplete list (interfaces, throws or parameters) + protected int listTypeParameterLength; // for recovering some incomplete list (type parameters) + protected int lParenPos,rParenPos; //accurate only when used ! + protected int modifiers; + protected int modifiersSourceStart; + protected int[] nestedMethod; //the ptr is nestedType + protected int nestedType, dimensions; + ASTNode [] noAstNodes = new ASTNode[AstStackIncrement]; + Expression [] noExpressions = new Expression[ExpressionStackIncrement]; + //modifiers dimensions nestedType etc....... + protected boolean optimizeStringLiterals =true; + protected CompilerOptions options; + protected ProblemReporter problemReporter; + protected int rBraceStart, rBraceEnd, rBraceSuccessorStart; //accurate only when used ! + protected int realBlockPtr; + protected int[] realBlockStack; + protected int recoveredStaticInitializerStart; + public ReferenceContext referenceContext; + public boolean reportOnlyOneSyntaxError = false; + public boolean reportSyntaxErrorIsRequired = true; + protected boolean restartRecovery; + + // statement recovery +// public boolean statementRecoveryEnabled = true; + public boolean methodRecoveryActivated = false; + protected boolean statementRecoveryActivated = false; + protected TypeDeclaration[] recoveredTypes; + protected int recoveredTypePtr; + protected int nextTypeStart; + protected TypeDeclaration pendingRecoveredType; + + public RecoveryScanner recoveryScanner; + + //scanner token + public Scanner scanner; + protected int[] stack = new int[StackIncrement]; + protected int stateStackTop; +// protected int synchronizedBlockSourceStart; + protected int[] variablesCounter; + + protected boolean checkExternalizeStrings; + protected boolean recordStringLiterals; + + // javadoc + public Javadoc javadoc; + public JavadocParser javadocParser; + // used for recovery + protected int lastJavadocEnd; + + private boolean enteredRecoverStatements; + + private int insertedSemicolonPosition=-1; + + private Set errorAction = new HashSet(); + + private static final int UNCONSUMED_LIT_ELEMENT=0x4; + private static final int UNCONSUMED_ELISION=0x2; + private static final int WAS_ARRAY_LIT_ELEMENT=0x1; + + public static final byte FLAG_EMPTY_STATEMENT = 1; + + public IInferEngine[] inferenceEngines; + + static { + try{ + initTables(); + } catch(java.io.IOException ex){ + throw new ExceptionInInitializerError(ex.getMessage()); + } + } +public static int asi(int state) { + + return asb[original_state(state)]; +} +public final static short base_check(int i) { + return check_table[i - (NUM_RULES + 1)]; +} +private final static void buildFile(String filename, List listToDump) { + BufferedWriter writer = null; + try { + writer = new BufferedWriter(new FileWriter(filename)); + for (Iterator iterator = listToDump.iterator(); iterator.hasNext(); ) { + writer.write(String.valueOf(iterator.next())); + } + writer.flush(); + } catch(IOException e) { + // ignore + } finally { + if (writer != null) { + try { + writer.close(); + } catch (IOException e1) { + // ignore + } + } + } + System.out.println(filename + " creation complete"); //$NON-NLS-1$ +} +private final static String[] buildFileForName(String filename, String contents) { + String[] result = new String[contents.length()]; + result[0] = null; + int resultCount = 1; + + StringBuffer buffer = new StringBuffer(); + + int start = contents.indexOf("name[]"); //$NON-NLS-1$ + start = contents.indexOf('\"', start); + int end = contents.indexOf("};", start); //$NON-NLS-1$ + + contents = contents.substring(start, end); + + boolean addLineSeparator = false; + int tokenStart = -1; + StringBuffer currentToken = new StringBuffer(); + for (int i = 0; i < contents.length(); i++) { + char c = contents.charAt(i); + if(c == '\"') { + if(tokenStart == -1) { + tokenStart = i + 1; + } else { + if(addLineSeparator) { + buffer.append('\n'); + result[resultCount++] = currentToken.toString(); + currentToken = new StringBuffer(); + } + String token = contents.substring(tokenStart, i); + if(token.equals(ERROR_TOKEN)){ + token = INVALID_CHARACTER; + } else if(token.equals(EOF_TOKEN)) { + token = UNEXPECTED_EOF; + } + buffer.append(token); + currentToken.append(token); + addLineSeparator = true; + tokenStart = -1; + } + } + if(tokenStart == -1 && c == '+'){ + addLineSeparator = false; + } + } + if(currentToken.length() > 0) { + result[resultCount++] = currentToken.toString(); + } + + buildFileForTable(filename, buffer.toString().toCharArray()); + + System.arraycopy(result, 0, result = new String[resultCount], 0, resultCount); + return result; +} +private static void buildFileForReadableName( + String file, + char[] newLhs, + char[] newNonTerminalIndex, + String[] newName, + String[] tokens) { + + ArrayList entries = new ArrayList(); + + boolean[] alreadyAdded = new boolean[newName.length]; + + for (int i = 0; i < tokens.length; i = i + 3) { + if("1".equals(tokens[i])) { //$NON-NLS-1$ + int index = newNonTerminalIndex[newLhs[Integer.parseInt(tokens[i + 1])]]; + StringBuffer buffer = new StringBuffer(); + if(!alreadyAdded[index]) { + alreadyAdded[index] = true; + buffer.append(newName[index]); + buffer.append('='); + buffer.append(tokens[i+2].trim()); + buffer.append('\n'); + entries.add(String.valueOf(buffer)); + } + } + } + int i = 1; + while(!INVALID_CHARACTER.equals(newName[i])) i++; + i++; + for (; i < alreadyAdded.length; i++) { + if(!alreadyAdded[i]) { + System.out.println(newName[i] + " has no readable name"); //$NON-NLS-1$ + } + } + Collections.sort(entries); + buildFile(file, entries); +} +private static void buildFilesForRecoveryTemplates( + String indexFilename, + String templatesFilename, + char[] newTerminalIndex, + char[] newNonTerminalIndex, + String[] newName, + char[] newLhs, + String[] tokens) { + + int[] newReverse = computeReverseTable(newTerminalIndex, newNonTerminalIndex, newName); + + char[] newRecoveyTemplatesIndex = new char[newNonTerminalIndex.length]; + char[] newRecoveyTemplates = new char[newNonTerminalIndex.length]; + int newRecoveyTemplatesPtr = 0; + + for (int i = 0; i < tokens.length; i = i + 3) { + if("3".equals(tokens[i])) { //$NON-NLS-1$ + int length = newRecoveyTemplates.length; + if(length == newRecoveyTemplatesPtr + 1) { + System.arraycopy(newRecoveyTemplates, 0, newRecoveyTemplates = new char[length * 2], 0, length); + } + newRecoveyTemplates[newRecoveyTemplatesPtr++] = 0; + + int index = newLhs[Integer.parseInt(tokens[i + 1])]; + + newRecoveyTemplatesIndex[index] = (char)newRecoveyTemplatesPtr; + + String token = tokens[i + 2].trim(); + java.util.StringTokenizer st = new java.util.StringTokenizer(new String(token), " "); //$NON-NLS-1$ + String[] terminalNames = new String[st.countTokens()]; + int t = 0; + while (st.hasMoreTokens()) { + terminalNames[t++] = st.nextToken(); + } + + for (int j = 0; j < terminalNames.length; j++) { + int symbol = getSymbol(terminalNames[j], newName, newReverse); + if(symbol > -1) { + length = newRecoveyTemplates.length; + if(length == newRecoveyTemplatesPtr + 1) { + System.arraycopy(newRecoveyTemplates, 0, newRecoveyTemplates = new char[length * 2], 0, length); + } + newRecoveyTemplates[newRecoveyTemplatesPtr++] = (char)symbol; + } + } + } + } + newRecoveyTemplates[newRecoveyTemplatesPtr++] = 0; + System.arraycopy(newRecoveyTemplates, 0, newRecoveyTemplates = new char[newRecoveyTemplatesPtr], 0, newRecoveyTemplatesPtr); + + buildFileForTable(indexFilename, newRecoveyTemplatesIndex); + buildFileForTable(templatesFilename, newRecoveyTemplates); +} +private static void buildFilesForStatementsRecoveryFilter( + String filename, + char[] newNonTerminalIndex, + char[] newLhs, + String[] tokens) { + + char[] newStatementsRecoveryFilter = new char[newNonTerminalIndex.length]; + + for (int i = 0; i < tokens.length; i = i + 3) { + if("4".equals(tokens[i])) { //$NON-NLS-1$ + int index = newLhs[Integer.parseInt(tokens[i + 1])]; + + newStatementsRecoveryFilter[index] = 1; + } + } + buildFileForTable(filename, newStatementsRecoveryFilter); + } + +private static void buildFilesForFlags( + String filename, + int size, + String[] tokens) { + + byte[] flags = new byte[size]; + + for (int i = 0; i < tokens.length; i = i + 3) { + if("5".equals(tokens[i])) { //$NON-NLS-1$ + int index = Integer.parseInt(tokens[i + 1]); + byte value =(byte) Integer.parseInt(tokens[i + 2].trim()); + flags[index]=value; + } + } + buildFileForTable(filename, flags); + } + +private static void buildFileForCompliance( + String file, + int length, + String[] tokens) { + + byte[] result = new byte[length * 8]; + + for (int i = 0; i < tokens.length; i = i + 3) { + if("2".equals(tokens[i])) { //$NON-NLS-1$ + int index = Integer.parseInt(tokens[i + 1]); + String token = tokens[i + 2].trim(); + long compliance = 0; + if("1.4".equals(token)) { //$NON-NLS-1$ + compliance = ClassFileConstants.JDK1_4; + } else if("1.5".equals(token)) { //$NON-NLS-1$ + compliance = ClassFileConstants.JDK1_5; + } else if("recovery".equals(token)) { //$NON-NLS-1$ + compliance = ClassFileConstants.JDK_DEFERRED; + } + + int j = index * 8; + result[j] = (byte)(compliance >>> 56); + result[j + 1] = (byte)(compliance >>> 48); + result[j + 2] = (byte)(compliance >>> 40); + result[j + 3] = (byte)(compliance >>> 32); + result[j + 4] = (byte)(compliance >>> 24); + result[j + 5] = (byte)(compliance >>> 16); + result[j + 6] = (byte)(compliance >>> 8); + result[j + 7] = (byte)(compliance); + } + } + + buildFileForTable(file, result); + } +private final static void buildFileForTable(String filename, byte[] bytes) { + java.io.FileOutputStream stream = null; + try { + stream = new java.io.FileOutputStream(filename); + stream.write(bytes); + } catch(IOException e) { + // ignore + } finally { + if (stream != null) { + try { + stream.close(); + } catch (IOException e1) { + // ignore + } + } + } + System.out.println(filename + " creation complete"); //$NON-NLS-1$ + } + private final static void buildFileForTable(String filename, char[] chars) { + byte[] bytes = new byte[chars.length * 2]; + for (int i = 0; i < chars.length; i++) { + bytes[2 * i] = (byte) (chars[i] >>> 8); + bytes[2 * i + 1] = (byte) (chars[i] & 0xFF); + } + + java.io.FileOutputStream stream = null; + try { + stream = new java.io.FileOutputStream(filename); + stream.write(bytes); + } catch(IOException e) { + // ignore + } finally { + if (stream != null) { + try { + stream.close(); + } catch (IOException e1) { + // ignore + } + } + } + System.out.println(filename + " creation complete"); //$NON-NLS-1$ + } + private final static byte[] buildFileOfByteFor(String filename, String tag, String[] tokens) { + + //transform the String tokens into chars before dumping then into file + + int i = 0; + //read upto the tag + while (!tokens[i++].equals(tag)){/*empty*/} + //read upto the } + + byte[] bytes = new byte[tokens.length]; //can't be bigger + int ic = 0; + String token; + while (!(token = tokens[i++]).equals("}")) { //$NON-NLS-1$ + int c = Integer.parseInt(token); + bytes[ic++] = (byte) c; + } + + //resize + System.arraycopy(bytes, 0, bytes = new byte[ic], 0, ic); + + buildFileForTable(filename, bytes); + return bytes; + } + private final static char[] buildFileOfIntFor(String filename, String tag, String[] tokens) { + + //transform the String tokens into chars before dumping then into file + + int i = 0; + //read upto the tag + while (!tokens[i++].equals(tag)){/*empty*/} + //read upto the } + + char[] chars = new char[tokens.length]; //can't be bigger + int ic = 0; + String token; + while (!(token = tokens[i++]).equals("}")) { //$NON-NLS-1$ + int c = Integer.parseInt(token); + chars[ic++] = (char) c; + } + + //resize + System.arraycopy(chars, 0, chars = new char[ic], 0, ic); + + buildFileForTable(filename, chars); + return chars; + } + private final static void buildFileOfShortFor(String filename, String tag, String[] tokens) { + + //transform the String tokens into chars before dumping then into file + + int i = 0; + //read upto the tag + while (!tokens[i++].equals(tag)){/*empty*/} + //read upto the } + + char[] chars = new char[tokens.length]; //can't be bigger + int ic = 0; + String token; + while (!(token = tokens[i++]).equals("}")) { //$NON-NLS-1$ + int c = Integer.parseInt(token); + chars[ic++] = (char) (c + 32768); + } + + //resize + System.arraycopy(chars, 0, chars = new char[ic], 0, ic); + + buildFileForTable(filename, chars); + } +public final static void buildFilesFromLPG(String dataFilename, String dataFilename2) { + + //RUN THIS METHOD TO GENERATE PARSER*.RSC FILES + + //build from the lpg javadcl.java files that represents the parser tables + //lhs check_table asb asr symbol_index + + //[org.eclipse.wst.jsdt.internal.compiler.parser.Parser.buildFilesFromLPG("d:/leapfrog/grammar/javadcl.java")] + char[] contents = CharOperation.NO_CHAR; + try { + contents = Util.getFileCharContent(new File(dataFilename), null); + } catch (IOException ex) { + System.out.println(Messages.parser_incorrectPath); + return; + } + java.util.StringTokenizer st = + new java.util.StringTokenizer(new String(contents), " \t\n\r[]={,;"); //$NON-NLS-1$ + String[] tokens = new String[st.countTokens()]; + int j = 0; + while (st.hasMoreTokens()) { + tokens[j++] = st.nextToken(); + } + final String prefix = FILEPREFIX; + int i = 0; + + char[] newLhs = buildFileOfIntFor(prefix + (++i) + ".rsc", "lhs", tokens); //$NON-NLS-1$ //$NON-NLS-2$ + buildFileOfShortFor(prefix + (++i) + ".rsc", "check_table", tokens); //$NON-NLS-2$ //$NON-NLS-1$ + buildFileOfIntFor(prefix + (++i) + ".rsc", "asb", tokens); //$NON-NLS-2$ //$NON-NLS-1$ + buildFileOfIntFor(prefix + (++i) + ".rsc", "asr", tokens); //$NON-NLS-2$ //$NON-NLS-1$ + buildFileOfIntFor(prefix + (++i) + ".rsc", "nasb", tokens); //$NON-NLS-2$ //$NON-NLS-1$ + buildFileOfIntFor(prefix + (++i) + ".rsc", "nasr", tokens); //$NON-NLS-2$ //$NON-NLS-1$ + char[] newTerminalIndex = buildFileOfIntFor(prefix + (++i) + ".rsc", "terminal_index", tokens); //$NON-NLS-2$ //$NON-NLS-1$ + char[] newNonTerminalIndex = buildFileOfIntFor(prefix + (++i) + ".rsc", "non_terminal_index", tokens); //$NON-NLS-1$ //$NON-NLS-2$ + buildFileOfIntFor(prefix + (++i) + ".rsc", "term_action", tokens); //$NON-NLS-2$ //$NON-NLS-1$ + + buildFileOfIntFor(prefix + (++i) + ".rsc", "scope_prefix", tokens); //$NON-NLS-2$ //$NON-NLS-1$ + buildFileOfIntFor(prefix + (++i) + ".rsc", "scope_suffix", tokens); //$NON-NLS-2$ //$NON-NLS-1$ + buildFileOfIntFor(prefix + (++i) + ".rsc", "scope_lhs", tokens); //$NON-NLS-2$ //$NON-NLS-1$ + buildFileOfIntFor(prefix + (++i) + ".rsc", "scope_state_set", tokens); //$NON-NLS-2$ //$NON-NLS-1$ + buildFileOfIntFor(prefix + (++i) + ".rsc", "scope_rhs", tokens); //$NON-NLS-2$ //$NON-NLS-1$ + buildFileOfIntFor(prefix + (++i) + ".rsc", "scope_state", tokens); //$NON-NLS-2$ //$NON-NLS-1$ + buildFileOfIntFor(prefix + (++i) + ".rsc", "in_symb", tokens); //$NON-NLS-2$ //$NON-NLS-1$ + + byte[] newRhs = buildFileOfByteFor(prefix + (++i) + ".rsc", "rhs", tokens); //$NON-NLS-2$ //$NON-NLS-1$ + buildFileOfByteFor(prefix + (++i) + ".rsc", "term_check", tokens); //$NON-NLS-2$ //$NON-NLS-1$ + buildFileOfByteFor(prefix + (++i) + ".rsc", "scope_la", tokens); //$NON-NLS-2$ //$NON-NLS-1$ + + String[] newName = buildFileForName(prefix + (++i) + ".rsc", new String(contents)); //$NON-NLS-1$ + + contents = CharOperation.NO_CHAR; + try { + contents = Util.getFileCharContent(new File(dataFilename2), null); + } catch (IOException ex) { + System.out.println(Messages.parser_incorrectPath); + return; + } + st = new java.util.StringTokenizer(new String(contents), "\t\n\r#"); //$NON-NLS-1$ + tokens = new String[st.countTokens()]; + j = 0; + while (st.hasMoreTokens()) { + tokens[j++] = st.nextToken(); + } + + buildFileForCompliance(prefix + (++i) + ".rsc", newRhs.length, tokens);//$NON-NLS-1$ + buildFileForReadableName(READABLE_NAMES_FILE+".properties", newLhs, newNonTerminalIndex, newName, tokens);//$NON-NLS-1$ + + buildFilesForRecoveryTemplates( + prefix + (++i) + ".rsc", //$NON-NLS-1$ + prefix + (++i) + ".rsc", //$NON-NLS-1$ + newTerminalIndex, + newNonTerminalIndex, + newName, + newLhs, + tokens); + + buildFilesForStatementsRecoveryFilter( + prefix + (++i) + ".rsc", //$NON-NLS-1$ + newNonTerminalIndex, + newLhs, + tokens); + + buildFilesForFlags( + prefix + (++i) + ".rsc", //$NON-NLS-1$ + rhs.length, + tokens); + + + System.out.println(Messages.parser_moveFiles); +} +public static int in_symbol(int state) { + return in_symb[original_state(state)]; +} +public final static void initTables() throws java.io.IOException { + + final String prefix = FILEPREFIX; + int i = 0; + lhs = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ + char[] chars = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ + check_table = new short[chars.length]; + for (int c = chars.length; c-- > 0;) { + check_table[c] = (short) (chars[c] - 32768); + } + asb = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ + asr = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ + nasb = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ + nasr = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ + terminal_index = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ + non_terminal_index = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ + term_action = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ + + scope_prefix = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ + scope_suffix = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ + scope_lhs = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ + scope_state_set = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ + scope_rhs = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ + scope_state = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ + in_symb = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ + + rhs = readByteTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ + term_check = readByteTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ + scope_la = readByteTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ + + name = readNameTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ + + rules_compliance = readLongTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ + + readableName = readReadableNameTable(READABLE_NAMES_FILE_NAME); + + reverse_index = computeReverseTable(terminal_index, non_terminal_index, name); + + recovery_templates_index = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ + recovery_templates = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ + + statements_recovery_filter = readTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ + state_flags = readByteTable(prefix + (++i) + ".rsc"); //$NON-NLS-1$ + + base_action = lhs; + + optionalSemicolonState =new boolean[base_action.length]; + for ( i = 0; i < optionalSemicolonState.length; i++) { + if (base_action[i]+TokenNameSEMICOLONERROR_ACTION) + act-=ERROR_ACTION; + boolean isEmptyStatementsState = false; + if (act0; + if (!isEmptyStatementsState) + optionalSemicolonState[i]=true; + } + } + +} +public static int nasi(int state) { + return nasb[original_state(state)]; +} +public static int ntAction(int state, int sym) { + return base_action[state + sym]; +} +protected static int original_state(int state) { + return -base_check(state); +} +protected static int[] computeReverseTable(char[] newTerminalIndex, char[] newNonTerminalIndex, String[] newName) { + int[] newReverseTable = new int[newName.length]; + for (int j = 0; j < newName.length; j++) { + found : { + for (int k = 0; k < newTerminalIndex.length; k++) { + if(newTerminalIndex[k] == j) { + newReverseTable[j] = k; + break found; + } + } + for (int k = 0; k < newNonTerminalIndex.length; k++) { + if(newNonTerminalIndex[k] == j) { + newReverseTable[j] = -k; + break found; + } + } + } + } + return newReverseTable; +} + +private static int getSymbol(String terminalName, String[] newName, int[] newReverse) { + for (int j = 0; j < newName.length; j++) { + if(terminalName.equals(newName[j])) { + return newReverse[j]; + } + } + return -1; +} + +protected static byte[] readByteTable(String filename) throws java.io.IOException { + + //files are located at Parser.class directory + + InputStream stream = Parser.class.getResourceAsStream(filename); + if (stream == null) { + throw new java.io.IOException(Messages.bind(Messages.parser_missingFile, filename)); + } + byte[] bytes = null; + try { + stream = new BufferedInputStream(stream); + bytes = Util.getInputStreamAsByteArray(stream, -1); + } finally { + try { + stream.close(); + } catch (IOException e) { + // ignore + } + } + return bytes; +} + +protected static String[] readNameTable(String filename) throws java.io.IOException { + char[] contents = readTable(filename); + char[][] nameAsChar = CharOperation.splitOn('\n', contents); + + String[] result = new String[nameAsChar.length + 1]; + result[0] = null; + for (int i = 0; i < nameAsChar.length; i++) { + result[i + 1] = new String(nameAsChar[i]); + } + + return result; +} +protected static String[] readReadableNameTable(String filename) { + String[] result = new String[name.length]; + + ResourceBundle bundle; + try { + bundle = ResourceBundle.getBundle(filename, Locale.getDefault()); + } catch(MissingResourceException e) { + System.out.println("Missing resource : " + filename.replace('.', '/') + ".properties for locale " + Locale.getDefault()); //$NON-NLS-1$//$NON-NLS-2$ + throw e; + } + for (int i = 0; i < NT_OFFSET + 1; i++) { + result[i] = name[i]; + } + for (int i = NT_OFFSET; i < name.length; i++) { + try { + String n = bundle.getString(name[i]); + if(n != null && n.length() > 0) { + result[i] = n; + } else { + result[i] = name[i]; + } + } catch(MissingResourceException e) { + result[i] = name[i]; + } + } + return result; +} +protected static char[] readTable(String filename) throws java.io.IOException { + + //files are located at Parser.class directory + + InputStream stream = Parser.class.getResourceAsStream(filename); + if (stream == null) { + throw new java.io.IOException(Messages.bind(Messages.parser_missingFile, filename)); + } + byte[] bytes = null; + try { + stream = new BufferedInputStream(stream); + bytes = Util.getInputStreamAsByteArray(stream, -1); + } finally { + try { + stream.close(); + } catch (IOException e) { + // ignore + } + } + + //minimal integrity check (even size expected) + int length = bytes.length; + if ((length & 1) != 0) + throw new java.io.IOException(Messages.bind(Messages.parser_corruptedFile, filename)); + + // convert bytes into chars + char[] chars = new char[length / 2]; + int i = 0; + int charIndex = 0; + + while (true) { + chars[charIndex++] = (char) (((bytes[i++] & 0xFF) << 8) + (bytes[i++] & 0xFF)); + if (i == length) + break; + } + return chars; +} +protected static long[] readLongTable(String filename) throws java.io.IOException { + + //files are located at Parser.class directory + + InputStream stream = Parser.class.getResourceAsStream(filename); + if (stream == null) { + throw new java.io.IOException(Messages.bind(Messages.parser_missingFile, filename)); + } + byte[] bytes = null; + try { + stream = new BufferedInputStream(stream); + bytes = Util.getInputStreamAsByteArray(stream, -1); + } finally { + try { + stream.close(); + } catch (IOException e) { + // ignore + } + } + + //minimal integrity check (even size expected) + int length = bytes.length; + if (length % 8 != 0) + throw new java.io.IOException(Messages.bind(Messages.parser_corruptedFile, filename)); + + // convert bytes into longs + long[] longs = new long[length / 8]; + int i = 0; + int longIndex = 0; + + while (true) { + longs[longIndex++] = + (((long) (bytes[i++] & 0xFF)) << 56) + + (((long) (bytes[i++] & 0xFF)) << 48) + + (((long) (bytes[i++] & 0xFF)) << 40) + + (((long) (bytes[i++] & 0xFF)) << 32) + + (((long) (bytes[i++] & 0xFF)) << 24) + + (((long) (bytes[i++] & 0xFF)) << 16) + + (((long) (bytes[i++] & 0xFF)) << 8) + + (bytes[i++] & 0xFF); + + if (i == length) + break; + } + return longs; +} +public static int tAction(int state, int sym) { + return term_action[term_check[base_action[state]+sym] == sym ? base_action[state] + sym : base_action[state]]; +} + +public Parser(ProblemReporter problemReporter, boolean optimizeStringLiterals) { + + this.problemReporter = problemReporter; + this.options = problemReporter.options; + this.optimizeStringLiterals = optimizeStringLiterals; + this.initializeScanner(); + this.astLengthStack = new int[50]; + this.expressionLengthStack = new int[30]; + this.intStack = new int[50]; + this.identifierStack = new char[30][]; + this.identifierLengthStack = new int[30]; + this.nestedMethod = new int[30]; + this.realBlockStack = new int[30]; + this.identifierPositionStack = new long[30]; + this.variablesCounter = new int[30]; + + // javadoc support + this.javadocParser = createJavadocParser(); + +} +protected void annotationRecoveryCheckPoint(int start, int end) { + if(this.lastCheckPoint > start && this.lastCheckPoint < end) { + this.lastCheckPoint = end + 1; + } +} +public void arrayInitializer(int length) { + //length is the size of the array Initializer + //expressionPtr points on the last elt of the arrayInitializer, + // in other words, it has not been decremented yet. + + ArrayInitializer ai = new ArrayInitializer(); + if (length != 0) { + this.expressionPtr -= length; + System.arraycopy(this.expressionStack, this.expressionPtr + 1, ai.expressions = new Expression[length], 0, length); + } + pushOnExpressionStack(ai); + //positionning + ai.sourceEnd = this.endStatementPosition; + ai.sourceStart = this.intStack[this.intPtr--]; +} +protected void blockReal() { + // See consumeLocalVariableDeclarationStatement in case of change: duplicated code + // increment the amount of declared variables for this block + this.realBlockStack[this.realBlockPtr]++; +} +/* + * Build initial recovery state. + * Recovery state is inferred from the current state of the parser (reduced node stack). + */ +public RecoveredElement buildInitialRecoveryState(){ + + /* initialize recovery by retrieving available reduced nodes + * also rebuild bracket balance + */ + this.lastCheckPoint = 0; + this.lastErrorEndPositionBeforeRecovery = this.scanner.currentPosition; + + RecoveredElement element = null; + if (this.referenceContext instanceof CompilationUnitDeclaration){ + if (!DO_DIET_PARSE) + { + this.methodRecoveryActivated=true; +// this.statementRecoveryActivated=true; + } + element = new RecoveredUnit(this.compilationUnit, 0, this); + + /* ignore current stack state, since restarting from the beginnning + since could not trust simple brace count */ + if (false){ // experimenting restart recovery from scratch + this.compilationUnit.currentPackage = null; + this.compilationUnit.imports = null; + this.compilationUnit.types = null; + this.compilationUnit.statements = null; + this.currentToken = 0; + this.listLength = 0; + this.listTypeParameterLength = 0; + this.endPosition = 0; + this.endStatementPosition = 0; + return element; + } + else + { + this.currentToken = 0; +// if (this.astPtr<0&&this.compilationUnit.sourceEnd>0) +// this.lastCheckPoint = this.compilationUnit.sourceEnd; + + } + + if (this.compilationUnit.currentPackage != null){ + this.lastCheckPoint = this.compilationUnit.currentPackage.declarationSourceEnd+1; + } + if (this.compilationUnit.imports != null){ + this.lastCheckPoint = this.compilationUnit.imports[this.compilationUnit.imports.length -1].declarationSourceEnd+1; + } + } else { + if (this.referenceContext instanceof AbstractMethodDeclaration){ + element = new RecoveredMethod((AbstractMethodDeclaration) this.referenceContext, null, 0, this); + this.lastCheckPoint = ((AbstractMethodDeclaration) this.referenceContext).bodyStart; + if(this.statementRecoveryActivated) { + element = element.add(new Block(0), 0); + } + } else { + /* Initializer bodies are parsed in the context of the type declaration, we must thus search it inside */ + if (this.referenceContext instanceof TypeDeclaration){ + TypeDeclaration type = (TypeDeclaration) this.referenceContext; + for (int i = 0; i < type.fields.length; i++){ + FieldDeclaration field = type.fields[i]; + if (field != null + && field.getKind() == AbstractVariableDeclaration.INITIALIZER + && field.declarationSourceStart <= this.scanner.initialPosition + && this.scanner.initialPosition <= field.declarationSourceEnd + && this.scanner.eofPosition <= field.declarationSourceEnd+1){ + element = new RecoveredInitializer(field, null, 1, this); + this.lastCheckPoint = field.declarationSourceStart; + break; + } + } + } + } + } + + if (element == null) return element; + + element = recoverAST(element); + if (this.statementRecoveryActivated) { + if (this.pendingRecoveredType != null && + this.scanner.startPosition - 1 <= this.pendingRecoveredType.declarationSourceEnd) { + // Add the pending type to the AST if this type isn't already added in the AST. + element = element.add(this.pendingRecoveredType, 0); + this.lastCheckPoint = this.pendingRecoveredType.declarationSourceEnd + 1; + this.pendingRecoveredType = null; + } + } + ProgramElement[] compUnitStatments = this.compilationUnit.statements; + if (compUnitStatments!=null && compUnitStatments.length>0 && + this.lastCheckPoint=0) + { + expression=new Assignment(this.expressionStack[start],funcExpr,method.sourceEnd); + } + if (expression!=null) + { + element = element.add(expression, 1); + if (method.declarationSourceEnd == 0){ + element = element.add(method, 0); + this.lastCheckPoint = method.bodyStart; + } else { + element = element.add(method, 0); + this.lastCheckPoint = method.declarationSourceEnd + 1; + } + if (element instanceof RecoveredMethod) + element.add(new Block(0), 0); + } + + return element; +} +protected void checkAndSetModifiers(int flag){ + /*modify the current modifiers buffer. + When the startPosition of the modifiers is 0 + it means that the modifier being parsed is the first + of a list of several modifiers. The startPosition + is zeroed when a copy of modifiers-buffer is push + onto the this.astStack. */ + + if ((this.modifiers & flag) != 0){ // duplicate modifier + this.modifiers |= ExtraCompilerModifiers.AccAlternateModifierProblem; + } + this.modifiers |= flag; + + if (this.modifiersSourceStart < 0) this.modifiersSourceStart = this.scanner.startPosition; +} +public void checkComment() { + + // discard obsolete comments while inside methods or fields initializer (see bug 74369) + // don't discard if the expression being worked on is an ObjectLiteral (see bug 322412 ) + if (!(this.diet && this.dietInt == 0) && this.scanner.commentPtr >= 0 && !(expressionPtr >= 0 && expressionStack[expressionPtr] instanceof ObjectLiteral)) { + flushCommentsDefinedPriorTo(this.endStatementPosition); + } + + int lastComment = this.scanner.commentPtr; + +// if (this.modifiersSourceStart >= 0) { +// // eliminate comments located after modifierSourceStart if positionned +// while (lastComment >= 0 && this.scanner.commentStarts[lastComment] > this.modifiersSourceStart) lastComment--; +// } + if (lastComment >= 0) { + // consider all remaining leading comments to be part of current declaration + this.modifiersSourceStart = this.scanner.commentStarts[0]; + + // check deprecation in last comment if javadoc (can be followed by non-javadoc comments which are simply ignored) + while (lastComment >= 0 && this.scanner.commentStops[lastComment] < 0) lastComment--; // non javadoc comment have negative end positions + if (lastComment >= 0 && this.javadocParser != null) { + int commentEnd = this.scanner.commentStops[lastComment] - 1; //stop is one over, + // do not report problem before last parsed comment while recovering code... + this.javadocParser.reportProblems = this.currentElement == null || commentEnd > this.lastJavadocEnd; + if (this.javadocParser.checkDeprecation(lastComment)) { + checkAndSetModifiers(ClassFileConstants.AccDeprecated); + } + this.javadoc = this.javadocParser.docComment; // null if check javadoc is not activated + if (currentElement == null) this.lastJavadocEnd = commentEnd; + } + } +} +protected void checkNonNLSAfterBodyEnd(int declarationEnd){ + if(this.scanner.currentPosition - 1 <= declarationEnd) { + this.scanner.eofPosition = declarationEnd < Integer.MAX_VALUE ? declarationEnd + 1 : declarationEnd; + try { + while(this.scanner.getNextToken() != TokenNameEOF){/*empty*/} + } catch (InvalidInputException e) { + // Nothing to do + } + } +} +protected void classInstanceCreation(boolean isQualified, boolean isShort) { + // ClassInstanceCreationExpression ::= 'new' ClassType '(' ArgumentListopt ')' ClassBodyopt + + // ClassBodyopt produces a null item on the astStak if it produces NO class body + // An empty class body produces a 0 on the length stack..... + + AllocationExpression alloc = new AllocationExpression(); + int length; +// if (((length = this.astLengthStack[this.astLengthPtr--]) == 1) +// && (this.astStack[this.astPtr] == null)) { +// //NO ClassBody +// this.astPtr--; +// if (isQualified) { +// alloc = new QualifiedAllocationExpression(); +// } else { + alloc = new AllocationExpression(); +// } + + alloc.isShort=isShort; + if (!isShort) + { + alloc.sourceEnd = this.intStack[this.intPtr--]; //the position has been stored explicitly + if ((length = this.expressionLengthStack[this.expressionLengthPtr--]) != 0) { + this.expressionPtr -= length; + System.arraycopy( + this.expressionStack, + this.expressionPtr + 1, + alloc.arguments = new Expression[length], + 0, + length); + } + + } + + alloc.member = this.expressionStack[this.expressionPtr--]; + this.expressionLengthPtr--; + + //the default constructor with the correct number of argument + //will be created and added by the TC (see createsInternalConstructorWithBinding) + alloc.sourceStart = this.intStack[this.intPtr--]; + if (isShort) + alloc.sourceEnd=alloc.member.sourceEnd; + pushOnExpressionStack(alloc); +// } else { +// dispatchDeclarationInto(length); +// TypeDeclaration anonymousTypeDeclaration = (TypeDeclaration)this.astStack[this.astPtr]; +// anonymousTypeDeclaration.declarationSourceEnd = this.endStatementPosition; +// anonymousTypeDeclaration.bodyEnd = this.endStatementPosition; +// if (anonymousTypeDeclaration.allocation != null) { +// anonymousTypeDeclaration.allocation.sourceEnd = this.endStatementPosition; +// } +// if (length == 0 && !containsComment(anonymousTypeDeclaration.bodyStart, anonymousTypeDeclaration.bodyEnd)) { +// anonymousTypeDeclaration.bits |= ASTNode.UndocumentedEmptyBlock; +// } +// this.astPtr--; +// this.astLengthPtr--; +// +// // mark initializers with local type mark if needed +// markInitializersWithLocalType(anonymousTypeDeclaration); +// } +} +protected void concatExpressionLists() { + this.expressionLengthStack[--this.expressionLengthPtr]++; +} +protected void concatNodeLists() { + /* + * This is a case where you have two sublists into the this.astStack that you want + * to merge in one list. There is no action required on the this.astStack. The only + * thing you need to do is merge the two lengths specified on the astStackLength. + * The top two length are for example: + * ... p n + * and you want to result in a list like: + * ... n+p + * This means that the p could be equals to 0 in case there is no astNode pushed + * on the this.astStack. + * Look at the InterfaceMemberDeclarations for an example. + */ + + this.astLengthStack[this.astLengthPtr - 1] += this.astLengthStack[this.astLengthPtr--]; +} +protected void consumeAnnotationAsModifier() { + Expression expression = this.expressionStack[this.expressionPtr]; + int sourceStart = expression.sourceStart; + if (this.modifiersSourceStart < 0) { + this.modifiersSourceStart = sourceStart; + } +} +protected void consumeArgumentList() { + // ArgumentList ::= ArgumentList ',' Expression + concatExpressionLists(); +} +protected void consumeArguments() { + // Arguments ::= '(' ArgumentListopt ')' + // nothing to do, the expression stack is already updated + pushOnIntStack(rParenPos); +} +protected void consumeAssignment() { + // Assignment ::= LeftHandSide AssignmentOperator AssignmentExpression + //optimize the push/pop + + int op = this.intStack[this.intPtr--] ; //<--the encoded operator + + this.expressionPtr -- ; this.expressionLengthPtr -- ; + checkComment(); + + if(op != EQUAL) { + CompoundAssignment compoundAssignment = new CompoundAssignment( + this.expressionStack[this.expressionPtr] , + this.expressionStack[this.expressionPtr+1], + op, + this.scanner.startPosition - 1); + if (this.javadoc != null) { + compoundAssignment.javadoc = this.javadoc; + this.javadoc = null; + } + this.expressionStack[this.expressionPtr] = compoundAssignment; + } + else { + Assignment assignment = new Assignment( + this.expressionStack[this.expressionPtr] , + this.expressionStack[this.expressionPtr+1], + this.scanner.startPosition - 1); + if (this.javadoc != null) { + assignment.javadoc = this.javadoc; + this.javadoc = null; + } + this.expressionStack[this.expressionPtr] = assignment; + } + + if (this.pendingRecoveredType != null) { + // Used only in statements recovery. + // This is not a real assignment but a placeholder for an existing anonymous type. + // The assignment must be replace by the anonymous type. + if (this.pendingRecoveredType.allocation != null && + this.scanner.startPosition - 1 <= this.pendingRecoveredType.declarationSourceEnd) { + this.expressionStack[this.expressionPtr] = this.pendingRecoveredType.allocation; + this.pendingRecoveredType = null; + return; + } + this.pendingRecoveredType = null; + } +} +protected void consumeAssignmentOperator(int pos) { + // AssignmentOperator ::= '=' + // AssignmentOperator ::= '*=' + // AssignmentOperator ::= '/=' + // AssignmentOperator ::= '%=' + // AssignmentOperator ::= '+=' + // AssignmentOperator ::= '-=' + // AssignmentOperator ::= '<<=' + // AssignmentOperator ::= '>>=' + // AssignmentOperator ::= '>>>=' + // AssignmentOperator ::= '&=' + // AssignmentOperator ::= '^=' + // AssignmentOperator ::= '|=' + + pushOnIntStack(pos); +} +protected void consumeBinaryExpression(int op) { + // MultiplicativeExpression ::= MultiplicativeExpression '*' UnaryExpression + // MultiplicativeExpression ::= MultiplicativeExpression '/' UnaryExpression + // MultiplicativeExpression ::= MultiplicativeExpression '%' UnaryExpression + // AdditiveExpression ::= AdditiveExpression '+' MultiplicativeExpression + // AdditiveExpression ::= AdditiveExpression '-' MultiplicativeExpression + // ShiftExpression ::= ShiftExpression '<<' AdditiveExpression + // ShiftExpression ::= ShiftExpression '>>' AdditiveExpression + // ShiftExpression ::= ShiftExpression '>>>' AdditiveExpression + // RelationalExpression ::= RelationalExpression '<' ShiftExpression + // RelationalExpression ::= RelationalExpression '>' ShiftExpression + // RelationalExpression ::= RelationalExpression '<=' ShiftExpression + // RelationalExpression ::= RelationalExpression '>=' ShiftExpression + // AndExpression ::= AndExpression '&' EqualityExpression + // ExclusiveOrExpression ::= ExclusiveOrExpression '^' AndExpression + // InclusiveOrExpression ::= InclusiveOrExpression '|' ExclusiveOrExpression + // ConditionalAndExpression ::= ConditionalAndExpression '&&' InclusiveOrExpression + // ConditionalOrExpression ::= ConditionalOrExpression '||' ConditionalAndExpression + + //optimize the push/pop + + this.expressionPtr--; + this.expressionLengthPtr--; + Expression expr1 = this.expressionStack[this.expressionPtr]; + Expression expr2 = this.expressionStack[this.expressionPtr + 1]; + switch(op) { + case OR_OR : + this.expressionStack[this.expressionPtr] = + new OR_OR_Expression( + expr1, + expr2, + op); + break; + case AND_AND : + this.expressionStack[this.expressionPtr] = + new AND_AND_Expression( + expr1, + expr2, + op); + break; + case PLUS : + // look for "string1" + "string2" + // look for "string1" + "string2" + if (this.optimizeStringLiterals) { + if (expr1 instanceof StringLiteral) { + if (expr2 instanceof StringLiteral) { //string+string + this.expressionStack[this.expressionPtr] = + ((StringLiteral) expr1).extendWith((StringLiteral) expr2); + } else { + this.expressionStack[this.expressionPtr] = new BinaryExpression(expr1, expr2, PLUS); + } + } else if (expr1 instanceof CombinedBinaryExpression) { + CombinedBinaryExpression cursor; + // left branch is comprised of PLUS BEs + // cursor is shifted upwards, while needed BEs are added + // on demand; past the arityMax-th + // consecutive BE, a CBE is inserted that holds a + // full-fledged references table + if ((cursor = (CombinedBinaryExpression)expr1).arity < + cursor.arityMax) { + cursor.left = new BinaryExpression(cursor.left, + cursor.right, PLUS); + cursor.arity++; + } else { + cursor.left = new CombinedBinaryExpression(cursor.left, + cursor.right, PLUS, cursor.arity); + cursor.arity = 0; + cursor.tuneArityMax(); + } + cursor.right = expr2; + cursor.sourceEnd = expr2.sourceEnd; + this.expressionStack[this.expressionPtr] = cursor; + // BE_INSTRUMENTATION: neutralized in the released code +// cursor.depthTracker = ((BinaryExpression)cursor.left). +// depthTracker + 1; + } else if (expr1 instanceof BinaryExpression && + // single out the a + b case, which is a BE + // instead of a CBE (slightly more than a half of + // strings concatenation are one-deep binary + // expressions) + ((expr1.bits & ASTNode.OperatorMASK) >> + ASTNode.OperatorSHIFT) == OperatorIds.PLUS) { + this.expressionStack[this.expressionPtr] = + new CombinedBinaryExpression(expr1, expr2, PLUS, 1); + } else { + this.expressionStack[this.expressionPtr] = + new BinaryExpression(expr1, expr2, PLUS); + } + } else if (expr1 instanceof StringLiteral) { + if (expr2 instanceof StringLiteral) { + // string + string + this.expressionStack[this.expressionPtr] = + ((StringLiteral) expr1).extendsWith((StringLiteral) expr2); + } else { + // single out the a + b case + this.expressionStack[this.expressionPtr] = + new BinaryExpression(expr1, expr2, PLUS); + } + } else if (expr1 instanceof CombinedBinaryExpression) { + CombinedBinaryExpression cursor; + // shift cursor; create BE/CBE as needed + if ((cursor = (CombinedBinaryExpression)expr1).arity < + cursor.arityMax) { + cursor.left = new BinaryExpression(cursor.left, + cursor.right, PLUS); + cursor.arity++; + } else { + cursor.left = new CombinedBinaryExpression(cursor.left, + cursor.right, PLUS, cursor.arity); + cursor.arity = 0; + cursor.tuneArityMax(); + } + cursor.right = expr2; + cursor.sourceEnd = expr2.sourceEnd; + // BE_INSTRUMENTATION: neutralized in the released code +// cursor.depthTracker = ((BinaryExpression)cursor.left). +// depthTracker + 1; + this.expressionStack[this.expressionPtr] = cursor; + } else if (expr1 instanceof BinaryExpression && + // single out the a + b case + ((expr1.bits & ASTNode.OperatorMASK) >> + ASTNode.OperatorSHIFT) == OperatorIds.PLUS) { + this.expressionStack[this.expressionPtr] = + new CombinedBinaryExpression(expr1, expr2, PLUS, 1); + } else { + this.expressionStack[this.expressionPtr] = + new BinaryExpression(expr1, expr2, PLUS); + } + break; + case LESS : + this.intPtr--; + this.expressionStack[this.expressionPtr] = + new BinaryExpression( + expr1, + expr2, + op); + break; + default : + this.expressionStack[this.expressionPtr] = + new BinaryExpression( + expr1, + expr2, + op); + } +} +protected void consumeBlock() { + // Block ::= OpenBlock '{' BlockStatementsopt '}' + // simpler action for empty blocks + + int statementsLength = this.astLengthStack[this.astLengthPtr--]; + Block block; + if (statementsLength == 0) { // empty block + block = new Block(0); + block.sourceStart = this.intStack[this.intPtr--]; + block.sourceEnd = this.endStatementPosition; + // check whether this block at least contains some comment in it + if (!containsComment(block.sourceStart, block.sourceEnd)) { + block.bits |= ASTNode.UndocumentedEmptyBlock; + } + this.realBlockPtr--; // still need to pop the block variable counter + } else { + block = new Block(this.realBlockStack[this.realBlockPtr--]); + this.astPtr -= statementsLength; + System.arraycopy( + this.astStack, + this.astPtr + 1, + block.statements = new Statement[statementsLength], + 0, + statementsLength); + block.sourceStart = this.intStack[this.intPtr--]; + block.sourceEnd = this.endStatementPosition; + } + pushOnAstStack(block); +} +protected void consumeBlockStatements() { + // BlockStatements ::= BlockStatements BlockStatement + concatNodeLists(); +} +protected void consumeProgramElements() { + // BlockStatements ::= BlockStatements BlockStatement + concatNodeLists(); +} +protected void consumeCallExpressionWithArguments() { + //optimize the push/pop + //FunctionInvocation ::= Primary '.' 'Identifier' '(' ArgumentListopt ')' + + MessageSend m = newMessageSend(); +// m.sourceStart = +// (int) ((m.nameSourcePosition = this.identifierPositionStack[this.identifierPtr]) >>> 32); +// m.selector = this.identifierStack[this.identifierPtr--]; +// this.identifierLengthPtr--; + + Expression receiver = this.expressionStack[this.expressionPtr]; + m.sourceStart = receiver.sourceStart; + if (receiver instanceof SingleNameReference) + { + SingleNameReference singleNameReference = (SingleNameReference)receiver; + m.selector=singleNameReference.token; + m.nameSourcePosition = (((long) singleNameReference.sourceStart) << 32)+(singleNameReference.sourceStart+m.selector.length-1); + receiver=null; + + } else if (receiver instanceof FieldReference) { + FieldReference fieldReference = (FieldReference) receiver; + m.selector=fieldReference.token; + m.nameSourcePosition= (((long) (fieldReference.sourceEnd-(m.selector.length-1))) << 32)+(fieldReference.sourceEnd); + receiver=fieldReference.receiver; + } + + + m.receiver = receiver; + m.sourceEnd = this.intStack[this.intPtr--]; + this.expressionStack[this.expressionPtr] = m; +} +protected void consumeCallExpressionWithArrayReference() { + this.expressionPtr--; + this.expressionLengthPtr--; + Expression exp = + this.expressionStack[this.expressionPtr] = + new ArrayReference( + this.expressionStack[this.expressionPtr], + this.expressionStack[this.expressionPtr + 1]); + exp.sourceEnd = this.endPosition; +} +protected void consumeCallExpressionWithSimpleName() { + FieldReference fr = + new FieldReference( + this.identifierStack[this.identifierPtr], + this.identifierPositionStack[this.identifierPtr--]); + this.identifierLengthPtr--; + //optimize push/pop + fr.receiver = this.expressionStack[this.expressionPtr]; + //fieldreference begins at the receiver + fr.sourceStart = fr.receiver.sourceStart; + this.expressionStack[this.expressionPtr] = fr; +} +protected void consumeCaseLabel() { + // SwitchLabel ::= 'case' ConstantExpression ':' + this.expressionLengthPtr--; + Expression expression = this.expressionStack[this.expressionPtr--]; + pushOnAstStack(new CaseStatement(expression, expression.sourceEnd, this.intStack[this.intPtr--])); +} +protected void consumeCatches() { + // Catches ::= Catches CatchClause + optimizedConcatNodeLists(); +} +protected void consumeCatchHeader() { + // CatchDeclaration ::= 'catch' '(' FormalParameter ')' '{' + + if (this.currentElement == null){ + return; // should never occur, this consumeRule is only used in recovery mode + } + // current element should be a block due to the presence of the opening brace + if (!(this.currentElement instanceof RecoveredBlock)){ + if(!(this.currentElement instanceof RecoveredMethod)) { + return; + } + RecoveredMethod rMethod = (RecoveredMethod) this.currentElement; + if(!(rMethod.methodBody == null && rMethod.bracketBalance > 0)) { + return; + } + } + + Argument arg = (Argument)this.astStack[this.astPtr--]; + // convert argument to local variable + LocalDeclaration localDeclaration = new LocalDeclaration(arg.name, arg.sourceStart, arg.sourceEnd); + localDeclaration.type = arg.type; + localDeclaration.declarationSourceStart = arg.declarationSourceStart; + localDeclaration.declarationSourceEnd = arg.declarationSourceEnd; + + this.currentElement = this.currentElement.add(localDeclaration, 0); + this.lastCheckPoint = this.scanner.startPosition; // force to restart at this exact position + this.restartRecovery = true; // request to restart from here on + this.lastIgnoredToken = -1; +} +protected void consumeClassOrInterfaceName() { + pushOnGenericsIdentifiersLengthStack(this.identifierLengthStack[this.identifierLengthPtr]); + pushOnGenericsLengthStack(0); // handle type arguments +} +protected void consumeCompilationUnit() { + // JavaScriptUnit ::= EnterCompilationUnit InternalCompilationUnit + // do nothing by default +} +protected void consumeConditionalExpression(int op) { + // ConditionalExpression ::= ConditionalOrExpression '?' Expression ':' ConditionalExpression + //optimize the push/pop + this.intPtr -= 2;//consume position of the question mark + this.expressionPtr -= 2; + this.expressionLengthPtr -= 2; + this.expressionStack[this.expressionPtr] = + new ConditionalExpression( + this.expressionStack[this.expressionPtr], + this.expressionStack[this.expressionPtr + 1], + this.expressionStack[this.expressionPtr + 2]); +} +protected void consumeDefaultLabel() { + // SwitchLabel ::= 'default' ':' + pushOnAstStack(new CaseStatement(null, this.intStack[this.intPtr--], this.intStack[this.intPtr--])); +} +protected void consumeDefaultModifiers() { + checkComment(); // might update modifiers with AccDeprecated + pushOnIntStack(this.modifiers); // modifiers + pushOnIntStack( + this.modifiersSourceStart >= 0 ? this.modifiersSourceStart : this.scanner.startPosition); + resetModifiers(); +// pushOnExpressionStackLengthStack(0); // no annotation +} +protected void consumeDiet() { + // Diet ::= $empty + checkComment(); + pushOnIntStack(this.modifiersSourceStart); // push the start position of a javadoc comment if there is one + resetModifiers(); + jumpOverMethodBody(); +} +protected void consumeDebuggerStatement() { + pushOnAstStack(new DebuggerStatement(this.intStack[this.intPtr--], this.endStatementPosition)); +} +protected void consumeEmptyArgumentListopt() { + // ArgumentListopt ::= $empty + pushOnExpressionStackLengthStack(0); +} +protected void consumeEmptyArguments() { + // Argumentsopt ::= $empty + final FieldDeclaration fieldDeclaration = (FieldDeclaration) this.astStack[this.astPtr]; + pushOnIntStack(fieldDeclaration.sourceEnd); + pushOnExpressionStackLengthStack(0); +} +protected void consumeEmptyBlockStatementsopt() { + // BlockStatementsopt ::= $empty + pushOnAstLengthStack(0); +} +protected void consumeEmptyCatchesopt() { + // Catchesopt ::= $empty + pushOnAstLengthStack(0); +} +protected void consumeEmptyExpression() { + // Expressionopt ::= $empty + pushOnExpressionStackLengthStack(0); +} +protected void consumeEmptyForInitopt() { + // ForInitopt ::= $empty + pushOnAstLengthStack(0); +} +protected void consumeEmptyForUpdateopt() { + // ForUpdateopt ::= $empty + pushOnExpressionStackLengthStack(0); +} +protected void consumeEmptyInternalCompilationUnit() { + // InternalCompilationUnit ::= $empty + // nothing to do by default + if (this.compilationUnit.isPackageInfo()) { + this.compilationUnit.types = new TypeDeclaration[1]; + // create a fake interface declaration + TypeDeclaration declaration = new TypeDeclaration(compilationUnit.compilationResult); + declaration.name = TypeConstants.PACKAGE_INFO_NAME; + declaration.modifiers = ClassFileConstants.AccDefault; + this.compilationUnit.types[0] = declaration; + declaration.javadoc = this.compilationUnit.javadoc; + } +} +protected void consumeEmptyProgramElements() { + pushOnAstLengthStack(0); +} +protected void consumeEmptyObjectLiteral() { + ObjectLiteral objectLiteral = new ObjectLiteral(); + objectLiteral.sourceEnd = this.endStatementPosition; + objectLiteral.sourceStart = this.intStack[this.intPtr--]; + + pushOnExpressionStack(objectLiteral); +} +protected void consumeEmptyPropertySetParameterList() { + pushOnExpressionStackLengthStack(0); +} +protected void consumeEmptyStatement() { + this.intPtr--; + // EmptyStatement ::= ';' + char[] source = this.scanner.source; + if (this.endStatementPosition >= source.length) { + // this would be inserted as a fake empty statement + pushOnAstStack(new EmptyStatement(this.endStatementPosition, this.endStatementPosition)); + return; + } + int sourceStart = this.endStatementPosition; + + if (source[this.endStatementPosition] != ';') { + if(source.length > 5 && this.endStatementPosition >= 4) { + int c1 = 0, c2 = 0, c3 = 0, c4 = 0; + int pos = this.endStatementPosition - 4; + while (source[pos] == 'u') { + pos--; + } + if (source[pos] == '\\' && + !((c1 = ScannerHelper.getNumericValue(source[this.endStatementPosition - 3])) > 15 + || c1 < 0 + || (c2 = ScannerHelper.getNumericValue(source[this.endStatementPosition - 2])) > 15 + || c2 < 0 + || (c3 = ScannerHelper.getNumericValue(source[this.endStatementPosition - 1])) > 15 + || c3 < 0 + || (c4 = ScannerHelper.getNumericValue(source[this.endStatementPosition])) > 15 + || c4 < 0) && + ((char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4)) == ';'){ + // we have a Unicode for the ';' (/u003B) + sourceStart = pos; + } + } + } + if (this.astPtr > -1) { + if (this.astStack[this.astPtr] instanceof IDoStatement) { + ASTNode node = this.astStack[this.astPtr]; + node.setSourceEnd(this.endStatementPosition); + pushOnAstLengthStack(0); + return; + } + } + pushOnAstStack(new EmptyStatement(sourceStart, this.endStatementPosition)); +} +protected void consumeEmptySwitchBlock() { + // SwitchBlock ::= '{' '}' + pushOnAstLengthStack(0); +} +protected void consumeEnterCompilationUnit() { + // EnterCompilationUnit ::= $empty + // do nothing by default +} +protected void consumeEnterVariable() { + // EnterVariable ::= $empty + // do nothing by default + checkComment(); + resetModifiers(); + + char[] identifierName = this.identifierStack[this.identifierPtr]; + long namePosition = this.identifierPositionStack[this.identifierPtr]; +// int extendedDimension = this.intStack[this.intPtr--]; + AbstractVariableDeclaration declaration; + // create the ast node +// boolean isLocalDeclaration = this.nestedMethod[this.nestedType] != 0; +// if (isLocalDeclaration) { +// // create the local variable declarations + declaration = + this.createLocalDeclaration(identifierName, (int) (namePosition >>> 32), (int) namePosition); +// } else { + // create the field declaration +// declaration = +// this.createFieldDeclaration(identifierName, (int) (namePosition >>> 32), (int) namePosition); +// } + + this.identifierPtr--; + this.identifierLengthPtr--; +// TypeReference type; + int variableIndex = this.variablesCounter[this.nestedType]; +// int typeDim = 0; + if (variableIndex == 0) { + // first variable of the declaration (FieldDeclaration or LocalDeclaration) +// if (isLocalDeclaration) { +// declaration.declarationSourceStart = this.intStack[this.intPtr--]; +// declaration.modifiers = this.intStack[this.intPtr--]; +// // consume annotations +// int length; +// if ((length = this.expressionLengthStack[this.expressionLengthPtr--]) != 0) { +// System.arraycopy( +// this.expressionStack, +// (this.expressionPtr -= length) + 1, +// declaration.annotations = new Annotation[length], +// 0, +// length); +// } +// type = getTypeReference(typeDim = this.intStack[this.intPtr--]); // type dimension +// if (declaration.declarationSourceStart == -1) { +// // this is true if there is no modifiers for the local variable declaration +// declaration.declarationSourceStart = type.sourceStart; +// } +// pushOnAstStack(type); +// } else { +// type = getTypeReference(typeDim = this.intStack[this.intPtr--]); // type dimension +// pushOnAstStack(type); + int modifiersStart = this.intStack[this.intPtr--]; + declaration.modifiers = this.intStack[this.intPtr--]; + int varPosition = this.intStack[this.intPtr--]; + declaration.declarationSourceStart=(modifiersStart>=0)?modifiersStart:varPosition; + this.expressionLengthPtr--; + + // Store javadoc only on first declaration as it is the same for all ones + LocalDeclaration fieldDeclaration = (LocalDeclaration) declaration; + fieldDeclaration.javadoc = this.javadoc; + this.javadoc = null; +// } + } else { +// type = (TypeReference) this.astStack[this.astPtr - variableIndex]; +// typeDim = type.dimensions(); + AbstractVariableDeclaration previousVariable = + (AbstractVariableDeclaration) this.astStack[this.astPtr]; + declaration.declarationSourceStart = previousVariable.declarationSourceStart; + declaration.modifiers = previousVariable.modifiers; +// final Annotation[] annotations = previousVariable.annotations; +// if (annotations != null) { +// final int annotationsLength = annotations.length; +// System.arraycopy(annotations, 0, declaration.annotations = new Annotation[annotationsLength], 0, annotationsLength); +// } + } + +// if (extendedDimension == 0) { +// declaration.type = type; +// } else { +// int dimension = typeDim + extendedDimension; +// declaration.type = this.copyDims(type, dimension); +// } + this.variablesCounter[this.nestedType]++; + pushOnAstStack(declaration); + // recovery + if (this.currentElement != null) { + if (!(this.currentElement instanceof RecoveredUnit) + && (this.currentToken == TokenNameDOT + //|| declaration.modifiers != 0 + || (Util.getLineNumber(declaration.sourceStart, this.scanner.lineEnds, 0, this.scanner.linePtr) + != Util.getLineNumber((int) (namePosition >>> 32), this.scanner.lineEnds, 0, this.scanner.linePtr)))){ + this.lastCheckPoint = (int) (namePosition >>> 32); + this.restartRecovery = true; + return; + } +// if (isLocalDeclaration){ +// LocalDeclaration localDecl = (LocalDeclaration) this.astStack[this.astPtr]; +// this.lastCheckPoint = localDecl.sourceEnd + 1; +// this.currentElement = this.currentElement.add(localDecl, 0); +// } else { + LocalDeclaration fieldDecl = (LocalDeclaration) this.astStack[this.astPtr]; + this.lastCheckPoint = fieldDecl.sourceEnd + 1; + this.currentElement = this.currentElement.add(fieldDecl, 0); +// } + this.lastIgnoredToken = -1; + } +} +protected void consumeEqualityExpression(int op) { + // EqualityExpression ::= EqualityExpression '==' RelationalExpression + // EqualityExpression ::= EqualityExpression '!=' RelationalExpression + + //optimize the push/pop + + this.expressionPtr--; + this.expressionLengthPtr--; + this.expressionStack[this.expressionPtr] = + new EqualExpression( + this.expressionStack[this.expressionPtr], + this.expressionStack[this.expressionPtr + 1], + op); +} +protected void consumeExitTryBlock() { + //ExitTryBlock ::= $empty + if(this.currentElement != null) { + this.restartRecovery = true; + } +} +protected void consumeExitVariableWithInitialization() { + // ExitVariableWithInitialization ::= $empty + // do nothing by default + this.expressionLengthPtr--; + AbstractVariableDeclaration variableDecl = (AbstractVariableDeclaration) this.astStack[this.astPtr]; + variableDecl.initialization = this.expressionStack[this.expressionPtr--]; + // we need to update the declarationSourceEnd of the local variable declaration to the + // source end position of the initialization expression + variableDecl.declarationSourceEnd = variableDecl.initialization.sourceEnd; + variableDecl.declarationEnd = variableDecl.initialization.sourceEnd; + + this.recoveryExitFromVariable(); +} +protected void consumeExitVariableWithoutInitialization() { + // ExitVariableWithoutInitialization ::= $empty + // do nothing by default + + AbstractVariableDeclaration variableDecl = (AbstractVariableDeclaration) this.astStack[this.astPtr]; + variableDecl.declarationSourceEnd = variableDecl.declarationEnd; + if(this.currentElement != null && this.currentElement instanceof RecoveredField) { + if(this.endStatementPosition > variableDecl.sourceEnd) { + this.currentElement.updateSourceEndIfNecessary(this.endStatementPosition); + } + } + this.recoveryExitFromVariable(); +} +protected void consumeExpressionStatement() { + // ExpressionStatement ::= StatementExpression ';' + this.expressionLengthPtr--; + Expression expression = this.expressionStack[this.expressionPtr--]; + expression.statementEnd = this.endStatementPosition; + pushOnAstStack(expression); +} +protected void consumeForceNoDiet() { + // ForceNoDiet ::= $empty + this.dietInt++; +} +protected void consumeForInit() { + // ForInit ::= StatementExpressionList + pushOnAstLengthStack(-1); +} +protected void consumeFormalParameter(boolean isVarArgs) { + // FormalParameter ::= Type VariableDeclaratorId ==> false + // FormalParameter ::= Modifiers Type VariableDeclaratorId ==> true + /* + this.astStack : + this.identifierStack : type identifier + this.intStack : dim dim + ==> + this.astStack : Argument + this.identifierStack : + this.intStack : + */ + + this.identifierLengthPtr--; + char[] identifierName = this.identifierStack[this.identifierPtr]; + long namePositions = this.identifierPositionStack[this.identifierPtr--]; +// int extendedDimensions = this.intStack[this.intPtr--]; +// int endOfEllipsis = 0; +// if (isVarArgs) { +// endOfEllipsis = this.intStack[this.intPtr--]; +// } +// int firstDimensions = this.intStack[this.intPtr--]; +// final int typeDimensions = firstDimensions + extendedDimensions; +// TypeReference type = getTypeReference(typeDimensions); +// if (isVarArgs) { +// type = copyDims(type, typeDimensions + 1); +// if (extendedDimensions == 0) { +// type.sourceEnd = endOfEllipsis; +// } +// type.bits |= ASTNode.IsVarArgs; // set isVarArgs +// } +// int modifierPositions = this.intStack[this.intPtr--]; +// this.intPtr--; + int modifierPositions=(int) (namePositions >>> 32); + Argument arg = + new Argument( + identifierName, + namePositions, + null, + ClassFileConstants.AccDefault); +// this.intStack[this.intPtr + 1] & ~ClassFileConstants.AccDeprecated); // modifiers + arg.declarationSourceStart = modifierPositions; + // consume annotations +// int length; +// if ((length = this.expressionLengthStack[this.expressionLengthPtr--]) != 0) { +// System.arraycopy( +// this.expressionStack, +// (this.expressionPtr -= length) + 1, +// arg.annotations = new Annotation[length], +// 0, +// length); +// } + if (this.options.inferOptions.saveArgumentComments) + { + handleArgumentComment(arg); + } + + + pushOnAstStack(arg); + + /* if incomplete method header, this.listLength counter will not have been reset, + indicating that some arguments are available on the stack */ + this.listLength++; +} + +protected void handleArgumentComment(Argument arg) +{ + int lastComment = this.scanner.commentPtr; + +// if (this.modifiersSourceStart >= 0) { +// // eliminate comments located after modifierSourceStart if positionned +// while (lastComment >= 0 && this.scanner.commentStarts[lastComment] > this.modifiersSourceStart) lastComment--; +// } + if (lastComment >= 0 && this.scanner.commentStops[0]<0) { + // consider all remaining leading comments to be part of current declaration + int start=this.scanner.commentStarts[0]; + int end=this.scanner.commentStops[0]; + arg.comment=CharOperation.subarray(this.scanner.source, start+2, (-end)-2); + this.scanner.commentPtr=-1; + } +} +protected void consumeFormalParameterList() { + // FormalParameterList ::= FormalParameterList ',' FormalParameter + optimizedConcatNodeLists(); +} +protected void consumeFormalParameterListopt() { + // FormalParameterListopt ::= $empty + pushOnAstLengthStack(0); +} +protected void consumeGetSetPropertyAssignment(boolean isSetter) { + // remove two expressions property name/remove an optional property set parameter list + // remove all statement from function body + this.intPtr -= 2; // int pushed by consumeNestedMethod() and consumeOpenBlock() (called inside consumeMethodBody()) + int length = this.astLengthStack[this.astLengthPtr--]; + Statement[] statements = new Statement[length]; + this.astPtr -= length; + System.arraycopy( + this.astStack, + this.astPtr + 1, + statements, + 0, + length); + Expression varName = null; + if (isSetter) { + this.expressionLengthPtr--; + varName = this.expressionStack[this.expressionPtr--]; + } + // property name + this.expressionLengthPtr--; + Expression propertyName = this.expressionStack[this.expressionPtr--]; + // set or get + this.expressionLengthPtr--; + Expression expression = this.expressionStack[this.expressionPtr--]; + int end = this.endStatementPosition; + int start = expression.sourceStart; + + if (expression instanceof SingleNameReference) { + SingleNameReference reference = (SingleNameReference) expression; + if (isSetter) { + if (!CharOperation.equals(reference.token, "set".toCharArray())) { + // report error + //this.problemReporter().invalidValueForGetterSetter(expression, true); + } + } else { + if (!CharOperation.equals(reference.token, "get".toCharArray())) { + // report error + //this.problemReporter().invalidValueForGetterSetter(expression, false); + } + } + } + ObjectGetterSetterField getterSetterField = new ObjectGetterSetterField(propertyName, statements, varName, start, end); + pushOnExpressionStack(getterSetterField); +} +protected void consumeInternalCompilationUnitWithTypes() { + // InternalCompilationUnit ::= PackageDeclaration ImportDeclarations ReduceImports TypeDeclarations + // InternalCompilationUnit ::= PackageDeclaration TypeDeclarations + // InternalCompilationUnit ::= TypeDeclarations + // InternalCompilationUnit ::= ImportDeclarations ReduceImports TypeDeclarations + // consume type declarations + int length; + if ((length = this.astLengthStack[this.astLengthPtr--]) != 0) { + this.compilationUnit.statements = new ProgramElement[length]; + this.astPtr -= length; + System.arraycopy(this.astStack, this.astPtr + 1, this.compilationUnit.statements, 0, length); + } +} +protected void consumeLabel() { + // Do nothing +} +protected void consumeLeftParen() { + // PushLPAREN ::= '(' + pushOnIntStack(this.lParenPos); +} +protected void consumeLocalVariableDeclaration() { + // LocalVariableDeclaration ::= Modifiers Type VariableDeclarators ';' + + /* + this.astStack : + this.expressionStack: Expression Expression ...... Expression + this.identifierStack : type identifier identifier ...... identifier + this.intStack : typeDim dim dim dim + ==> + this.astStack : FieldDeclaration FieldDeclaration ...... FieldDeclaration + this.expressionStack : + this.identifierStack : + this.intStack : + + */ +// int variableDeclaratorsCounter = this.astLengthStack[this.astLengthPtr]; +// +// // update the this.astStack, this.astPtr and this.astLengthStack +// int startIndex = this.astPtr - this.variablesCounter[this.nestedType] + 1; +// System.arraycopy( +// this.astStack, +// startIndex, +// this.astStack, +// startIndex - 1, +// variableDeclaratorsCounter); +// this.astPtr--; // remove the type reference +// this.astLengthStack[--this.astLengthPtr] = variableDeclaratorsCounter; + this.variablesCounter[this.nestedType] = 0; +} +protected void consumeLocalVariableDeclarationStatement() { + // LocalVariableDeclarationStatement ::= LocalVariableDeclaration ';' + // see blockReal in case of change: duplicated code + // increment the amount of declared variables for this block + this.realBlockStack[this.realBlockPtr]++; + + // update source end to include the semi-colon + int variableDeclaratorsCounter = this.astLengthStack[this.astLengthPtr]; + AbstractVariableDeclaration nextDeclaration =null; + for (int i = 0; i + this.astStack : FunctionDeclaration + this.identifierStack : + this.intStack : + */ + + + this.nestedType--; + int length; + if (isNotAbstract) { + // pop the position of the { (body of the method) pushed in block decl + this.intPtr--; + this.intPtr--; + } + + int explicitDeclarations = 0; + Statement[] statements = null; + if (isNotAbstract) { + //statements + explicitDeclarations = this.realBlockStack[this.realBlockPtr--]; + if ((length = this.astLengthStack[this.astLengthPtr--]) != 0) { + System.arraycopy( + this.astStack, + (this.astPtr -= length) + 1, + statements = new Statement[length], + 0, + length); + } + } + + // now we know that we have a method declaration at the top of the ast stack + MethodDeclaration md = (MethodDeclaration) this.astStack[this.astPtr]; + md.statements = statements; + md.explicitDeclarations = explicitDeclarations; + + // cannot be done in consumeMethodHeader because we have no idea whether or not there + // is a body when we reduce the method header + if (!isNotAbstract) { //remember the fact that the method has a semicolon body + md.modifiers |= ExtraCompilerModifiers.AccSemicolonBody; + } else if (!(this.diet && this.dietInt == 0) && statements == null && !containsComment(md.bodyStart, this.endPosition)) { + md.bits |= ASTNode.UndocumentedEmptyBlock; + } + // store the this.endPosition (position just before the '}') in case there is + // a trailing comment behind the end of the method + md.bodyEnd = this.endPosition; + md.sourceEnd = this.endPosition; + md.declarationSourceEnd = flushCommentsDefinedPriorTo(this.endStatementPosition); +} +protected void consumeMethodHeader() { + // MethodHeader ::= MethodHeaderName MethodHeaderParameters MethodHeaderExtendedDims ThrowsClauseopt + // AnnotationMethodHeader ::= AnnotationMethodHeaderName FormalParameterListopt MethodHeaderRightParen MethodHeaderExtendedDims AnnotationMethodHeaderDefaultValueopt + // RecoveryMethodHeader ::= RecoveryMethodHeaderName FormalParameterListopt MethodHeaderRightParen MethodHeaderExtendedDims AnnotationMethodHeaderDefaultValueopt + // RecoveryMethodHeader ::= RecoveryMethodHeaderName FormalParameterListopt MethodHeaderRightParen MethodHeaderExtendedDims MethodHeaderThrowsClause + + // retrieve end position of method declarator + AbstractMethodDeclaration method = (AbstractMethodDeclaration)this.astStack[this.astPtr]; + + if (this.currentToken == TokenNameLBRACE){ + method.bodyStart = this.scanner.currentPosition; + } + else if (currentToken != TokenNameSEMICOLON) { // insert semicolon + currentToken = TokenNameSEMICOLON; + scanner.pushBack(); + } + // recovery + if (this.currentElement != null){ +// if(method.isAnnotationMethod()) { +// method.modifiers |= AccSemicolonBody; +// method.declarationSourceEnd = this.scanner.currentPosition-1; +// method.bodyEnd = this.scanner.currentPosition-1; +// this.currentElement = this.currentElement.parent; +// } else + if (this.currentToken == TokenNameSEMICOLON /*&& !method.isAnnotationMethod()*/){ + method.modifiers |= ExtraCompilerModifiers.AccSemicolonBody; + method.declarationSourceEnd = this.scanner.currentPosition-1; + method.bodyEnd = this.scanner.currentPosition-1; +// if (this.currentElement.parseTree() == method && this.currentElement.parent != null) { +// this.currentElement = this.currentElement.parent; +// } + } else if(this.currentToken == TokenNameLBRACE) { + if (this.currentElement instanceof RecoveredMethod && + ((RecoveredMethod)this.currentElement).methodDeclaration != method) { + this.ignoreNextOpeningBrace = true; + this.currentElement.bracketBalance++; + } } + this.restartRecovery = true; // used to avoid branching back into the regular automaton + } +} +protected void consumeMethodHeaderName(boolean isAnonymous) { + // MethodHeaderName ::= Modifiersopt Type 'Identifier' '(' + // AnnotationMethodHeaderName ::= Modifiersopt Type 'Identifier' '(' + // RecoveryMethodHeaderName ::= Modifiersopt Type 'Identifier' '(' + MethodDeclaration md = null; +// if(isAnnotationMethod) { +// md = new AnnotationMethodDeclaration(this.compilationUnit.compilationResult); +// this.recordStringLiterals = false; +// } else { + md = new MethodDeclaration(this.compilationUnit.compilationResult); +// } + + md.exprStackPtr=this.expressionPtr; + //name + long selectorSource =-1; + if (!isAnonymous) + { + md.setSelector(this.identifierStack[this.identifierPtr]); + selectorSource = this.identifierPositionStack[this.identifierPtr--]; + this.identifierLengthPtr--; + } + + + if (this.nestedType>0) + markEnclosingMemberWithLocalType(); + + //type +// md.returnType = getTypeReference(this.intStack[this.intPtr--]); + //modifiers + int functionPos = this.intStack[this.intPtr--]; + int modifierPos = this.intStack[this.intPtr--]; + md.declarationSourceStart = (functionPos>modifierPos)? modifierPos:functionPos; + md.modifiers = this.intStack[this.intPtr--]; + // consume annotations +// int length; +// if ((length = this.expressionLengthStack[this.expressionLengthPtr--]) != 0) { +// System.arraycopy( +// this.expressionStack, +// (this.expressionPtr -= length) + 1, +// md.annotations = new Annotation[length], +// 0, +// length); +// } + // javadoc + md.javadoc = this.javadoc; + this.javadoc = null; + + //highlight starts at selector start + if (selectorSource>=0) + md.sourceStart = (int) (selectorSource >>> 32); + else + md.sourceStart=md.declarationSourceStart; + pushOnAstStack(md); + md.sourceEnd = this.lParenPos; + md.bodyStart = this.lParenPos+1; + this.listLength = 0; // initialize this.listLength before reading parameters/throws + + + + + incrementNestedType(); + + // recovery + if (this.currentElement != null){ + if (this.currentElement instanceof RecoveredType + //|| md.modifiers != 0 + || true/* (this.scanner.getLineNumber(md.returnType.sourceStart) + == this.scanner.getLineNumber(md.sourceStart))*/){ + this.lastCheckPoint = md.bodyStart; + this.currentElement = this.currentElement.add(md, 0); + this.lastIgnoredToken = -1; + } else { + this.lastCheckPoint = md.sourceStart; + this.restartRecovery = true; + } + } +} +protected void consumeMethodHeaderRightParen() { + // MethodHeaderParameters ::= FormalParameterListopt ')' + int length = this.astLengthStack[this.astLengthPtr--]; + this.astPtr -= length; + AbstractMethodDeclaration md = (AbstractMethodDeclaration) this.astStack[this.astPtr]; + md.sourceEnd = this.rParenPos; + //arguments + if (length != 0) { + System.arraycopy( + this.astStack, + this.astPtr + 1, + md.arguments = new Argument[length], + 0, + length); + } + md.bodyStart = this.rParenPos+1; + this.listLength = 0; // reset this.listLength after having read all parameters + // recovery + if (this.currentElement != null){ + this.lastCheckPoint = md.bodyStart; + if (this.currentElement.parseTree() == md) return; + + // might not have been attached yet - in some constructor scenarii + if (md.isConstructor()){ + if ((length != 0) + || (this.currentToken == TokenNameLBRACE) + || (this.currentToken == TokenNamethrows)){ + this.currentElement = this.currentElement.add(md, 0); + this.lastIgnoredToken = -1; + } + } + } +} +protected void consumeModifiers2() { + this.expressionLengthStack[this.expressionLengthPtr - 1] += this.expressionLengthStack[this.expressionLengthPtr--]; +} +protected void consumeNestedMethod() { + // NestedMethod ::= $empty + jumpOverMethodBody(); + this.nestedMethod[this.nestedType] ++; + pushOnIntStack(this.scanner.currentPosition); + consumeOpenBlock(); +} +protected void consumeNestedType() { + // NestedType ::= $empty + incrementNestedType(); +} +protected void incrementNestedType() { + int length = this.nestedMethod.length; + if (++this.nestedType >= length) { + System.arraycopy( + this.nestedMethod, 0, + this.nestedMethod = new int[length + 30], 0, + length); + // increase the size of the variablesCounter as well. It has to be consistent with the size of the nestedMethod collection + System.arraycopy( + this.variablesCounter, 0, + this.variablesCounter = new int[length + 30], 0, + length); + } + this.nestedMethod[this.nestedType] = 0; + this.variablesCounter[this.nestedType] = 0; +} +protected void consumeNewExpression() { + classInstanceCreation(false, true); +} +protected void consumeNewMemberExpressionWithArguments() { + classInstanceCreation(false, false); +} +protected void consumeOpenBlock() { + // OpenBlock ::= $empty + + pushOnIntStack(this.scanner.startPosition); + int stackLength = this.realBlockStack.length; + if (++this.realBlockPtr >= stackLength) { + System.arraycopy( + this.realBlockStack, 0, + this.realBlockStack = new int[stackLength + StackIncrement], 0, + stackLength); + } + this.realBlockStack[this.realBlockPtr] = 0; +} +protected void consumePostfixExpression() { + // PostfixExpression ::= Name + pushOnExpressionStack(getUnspecifiedReferenceOptimized()); +} +protected void consumePrimaryNoNewArray() { + // PrimaryNoNewArray ::= PushLPAREN Expression PushRPAREN + final Expression parenthesizedExpression = this.expressionStack[this.expressionPtr]; + updateSourcePosition(parenthesizedExpression); + int numberOfParenthesis = (parenthesizedExpression.bits & ASTNode.ParenthesizedMASK) >> ASTNode.ParenthesizedSHIFT; + parenthesizedExpression.bits &= ~ASTNode.ParenthesizedMASK; + parenthesizedExpression.bits |= (numberOfParenthesis + 1) << ASTNode.ParenthesizedSHIFT; +} +protected void consumePrimaryNoNewArrayThis() { + // PrimaryNoNewArray ::= 'this' + pushOnExpressionStack(new ThisReference(this.intStack[this.intPtr--], this.endPosition)); +} +protected void consumePrimarySimpleName() { + // PrimaryNoNewArray ::= SimpleName + pushOnExpressionStack(getUnspecifiedReferenceOptimized()); +} +protected void consumePropertyAssignment() { + // MemberValuePair ::= SimpleName '=' MemberValue + this.modifiersSourceStart=-1; + this.checkComment(); + this.resetModifiers(); + + Expression value = this.expressionStack[this.expressionPtr--]; + this.expressionLengthPtr--; + + Expression field = this.expressionStack[this.expressionPtr--]; + this.expressionLengthPtr--; + int end = value.sourceEnd; + int start = field.sourceStart; + + ObjectLiteralField literalField = new ObjectLiteralField(field, value, start, end); + pushOnExpressionStack(literalField); + + if (this.javadoc!=null) { + literalField.javaDoc = this.javadoc; + } + else if (value instanceof FunctionExpression) + { + MethodDeclaration methodDeclaration = ((FunctionExpression)value).methodDeclaration; + literalField.javaDoc=methodDeclaration.javadoc; + methodDeclaration.javadoc=null; + } + this.javadoc = null; + + // discard obsolete comments while inside methods or fields initializer (see bug 74369) + if (!(this.diet && this.dietInt==0) && this.scanner.commentPtr >= 0) { + flushCommentsDefinedPriorTo(literalField.sourceEnd); + } + resetModifiers(); +} +protected void consumePropertyName() { + pushOnExpressionStack(getUnspecifiedReferenceOptimized()); +} +protected void consumePropertyNameAndValueList() { + concatExpressionLists(); +} +protected void consumePropertySetParameterList() { + pushOnExpressionStack(getUnspecifiedReferenceOptimized()); +} +protected void consumePushLeftBrace() { + pushOnIntStack(this.endPosition); // modifiers +} + +protected void consumeArrayLiteralHeader() { + pushOnIntStack(this.endPosition); // modifiers + pushOnIntStack(0); // numExprs +} +protected void consumePushModifiers() { + checkComment(); // might update modifiers with AccDeprecated + pushOnIntStack(this.modifiers); // modifiers + pushOnIntStack(this.modifiersSourceStart); + resetModifiers(); + pushOnExpressionStackLengthStack(0); +} +protected void consumePushPosition() { + // for source managment purpose + // PushPosition ::= $empty + pushOnIntStack(this.endPosition); +} +protected void consumeQualifiedName() { + // QualifiedName ::= Name '.' SimpleName + /*back from the recursive loop of QualifiedName. + Updates identifier length into the length stack*/ + + this.identifierLengthStack[--this.identifierLengthPtr]++; +} +protected void consumeRecoveryMethodHeaderName() { + // this method is call only inside recovery +// boolean isAnnotationMethod = false; +// if(this.currentElement instanceof RecoveredType) { +// isAnnotationMethod = (((RecoveredType)this.currentElement).typeDeclaration.modifiers & ClassFileConstants.AccAnnotation) != 0; +// } else { +// RecoveredType recoveredType = this.currentElement.enclosingType(); +// if(recoveredType != null) { +// isAnnotationMethod = (recoveredType.typeDeclaration.modifiers & ClassFileConstants.AccAnnotation) != 0; +// } +// } + this.consumeMethodHeaderName(false); +} +protected void consumeRestoreDiet() { + // RestoreDiet ::= $empty + this.dietInt--; +} +protected void consumeRightParen() { + // PushRPAREN ::= ')' + pushOnIntStack(this.rParenPos); +} +private void consumeFunctionExpression() { + + consumeMethodDeclaration(true); + MethodDeclaration md = (MethodDeclaration) this.astStack[this.astPtr--]; + this.astLengthPtr--; + FunctionExpression funcExpr=new FunctionExpression(md); + funcExpr.sourceEnd=md.declarationSourceEnd; + funcExpr.sourceStart=md.declarationSourceStart; + pushOnExpressionStack(funcExpr); +} + +private void consumeStatementForIn() { +// int length; + Expression collection = null; + Statement iteratorVar; + boolean scope = true; + + //statements + this.astLengthPtr--; + Statement statement = (Statement) this.astStack[this.astPtr--]; + + if (this.expressionLengthStack[this.expressionLengthPtr--] != 0) + collection = this.expressionStack[this.expressionPtr--]; + + this.astLengthPtr--; + iteratorVar = (Statement) this.astStack[this.astPtr--]; + pushOnAstStack( + new ForInStatement( + iteratorVar, + collection, + statement, + scope, + this.intStack[this.intPtr--], + this.endStatementPosition)); + +} + +private void consumeArrayLiteralList() { + concatExpressionLists(); + this.intStack[this.intPtr]&= ~(UNCONSUMED_ELISION|UNCONSUMED_LIT_ELEMENT); +} +private void consumeArrayLiteralListOne() { + if ( (this.intStack[this.intPtr]&UNCONSUMED_ELISION)!=0) + { + concatExpressionLists(); + this.intStack[this.intPtr]&= ~(UNCONSUMED_ELISION|UNCONSUMED_LIT_ELEMENT); + } + + +} + +private void consumeListExpression() { + this.expressionPtr--; + this.expressionLengthPtr--; + Expression expr1 = this.expressionStack[this.expressionPtr]; + Expression expr2 = this.expressionStack[this.expressionPtr + 1]; + this.expressionStack[this.expressionPtr] = + new ListExpression( + expr1, + expr2); + +} + +protected void consumePostDoc() { + + if (this.options.inferOptions.docLocation==InferOptions.DOC_LOCATION_AFTER) + { + + } +} + +// This method is part of an automatic generation : do NOT edit-modify +protected void consumeRule(int act) { + switch ( act ) { + case 23 : if (DEBUG) { System.out.println("CompilationUnit ::= EnterCompilationUnit..."); } //$NON-NLS-1$ + consumeCompilationUnit(); + break; + + case 24 : if (DEBUG) { System.out.println("InternalCompilationUnit ::= ProgramElements"); } //$NON-NLS-1$ + consumeInternalCompilationUnitWithTypes(); + break; + + case 25 : if (DEBUG) { System.out.println("InternalCompilationUnit ::="); } //$NON-NLS-1$ + consumeEmptyInternalCompilationUnit(); + break; + + case 26 : if (DEBUG) { System.out.println("EnterCompilationUnit ::="); } //$NON-NLS-1$ + consumeEnterCompilationUnit(); + break; + + case 30 : if (DEBUG) { System.out.println("CatchHeader ::= catch LPAREN FormalParameter RPAREN..."); } //$NON-NLS-1$ + consumeCatchHeader(); + break; + + case 32 : if (DEBUG) { System.out.println("VariableDeclarators ::= VariableDeclarators COMMA..."); } //$NON-NLS-1$ + consumeVariableDeclarators(); + break; + + case 34 : if (DEBUG) { System.out.println("VariableDeclaratorsNoIn ::= VariableDeclaratorsNoIn COMMA"); } //$NON-NLS-1$ + consumeVariableDeclarators(); + break; + + case 39 : if (DEBUG) { System.out.println("EnterVariable ::="); } //$NON-NLS-1$ + consumeEnterVariable(); + break; + + case 40 : if (DEBUG) { System.out.println("ExitVariableWithInitialization ::="); } //$NON-NLS-1$ + consumeExitVariableWithInitialization(); + break; + + case 41 : if (DEBUG) { System.out.println("ExitVariableWithoutInitialization ::="); } //$NON-NLS-1$ + consumeExitVariableWithoutInitialization(); + break; + + case 42 : if (DEBUG) { System.out.println("ForceNoDiet ::="); } //$NON-NLS-1$ + consumeForceNoDiet(); + break; + + case 43 : if (DEBUG) { System.out.println("RestoreDiet ::="); } //$NON-NLS-1$ + consumeRestoreDiet(); + break; + + case 47 : if (DEBUG) { System.out.println("FunctionExpression ::= FunctionExpressionHeader..."); } //$NON-NLS-1$ + // set to true to consume a method with a body + consumeFunctionExpression(); + break; + + case 48 : if (DEBUG) { System.out.println("FunctionExpressionHeader ::= FunctionExpressionHeaderName"); } //$NON-NLS-1$ + consumeMethodHeader(); + break; + + case 49 : if (DEBUG) { System.out.println("FunctionExpressionHeaderName ::= Modifiersopt function..."); } //$NON-NLS-1$ + consumeMethodHeaderName(false); + break; + + case 50 : if (DEBUG) { System.out.println("FunctionExpressionHeaderName ::= Modifiersopt function..."); } //$NON-NLS-1$ + consumeMethodHeaderName(true); + break; + + case 52 : if (DEBUG) { System.out.println("MethodDeclaration ::= MethodHeader MethodBody"); } //$NON-NLS-1$ + // set to true to consume a method with a body + consumeMethodDeclaration(true); + break; + + case 53 : if (DEBUG) { System.out.println("AbstractMethodDeclaration ::= MethodHeader SEMICOLON"); } //$NON-NLS-1$ + // set to false to consume a method without body + consumeMethodDeclaration(false); + break; + + case 54 : if (DEBUG) { System.out.println("MethodHeader ::= MethodHeaderName FormalParameterListopt"); } //$NON-NLS-1$ + consumeMethodHeader(); + break; + + case 55 : if (DEBUG) { System.out.println("MethodHeaderName ::= Modifiersopt function Identifier..."); } //$NON-NLS-1$ + consumeMethodHeaderName(false); + break; + + case 56 : if (DEBUG) { System.out.println("MethodHeaderRightParen ::= RPAREN"); } //$NON-NLS-1$ + consumeMethodHeaderRightParen(); + break; + + case 58 : if (DEBUG) { System.out.println("FormalParameterList ::= FormalParameterList COMMA..."); } //$NON-NLS-1$ + consumeFormalParameterList(); + break; + + case 59 : if (DEBUG) { System.out.println("FormalParameter ::= VariableDeclaratorId"); } //$NON-NLS-1$ + consumeFormalParameter(false); + break; + + case 60 : if (DEBUG) { System.out.println("MethodBody ::= NestedMethod LBRACE PostDoc..."); } //$NON-NLS-1$ + consumeMethodBody(); + break; + + case 61 : if (DEBUG) { System.out.println("NestedMethod ::="); } //$NON-NLS-1$ + consumeNestedMethod(); + break; + + case 62 : if (DEBUG) { System.out.println("PostDoc ::="); } //$NON-NLS-1$ + consumePostDoc(); + break; + + case 63 : if (DEBUG) { System.out.println("PushLeftBraceObjectLiteral ::="); } //$NON-NLS-1$ + consumePushLeftBrace(); + break; + + case 64 : if (DEBUG) { System.out.println("Block ::= OpenBlock LBRACE BlockStatementsopt RBRACE"); } //$NON-NLS-1$ + consumeBlock(); + break; + + case 65 : if (DEBUG) { System.out.println("OpenBlock ::="); } //$NON-NLS-1$ + consumeOpenBlock() ; + break; + + case 67 : if (DEBUG) { System.out.println("ProgramElements ::= ProgramElements ProgramElement"); } //$NON-NLS-1$ + consumeProgramElements() ; + break; + + case 70 : if (DEBUG) { System.out.println("BlockStatements ::= BlockStatements BlockStatement"); } //$NON-NLS-1$ + consumeBlockStatements() ; + break; + + case 74 : if (DEBUG) { System.out.println("LocalVariableDeclarationStatement ::=..."); } //$NON-NLS-1$ + consumeLocalVariableDeclarationStatement(); + break; + + case 75 : if (DEBUG) { System.out.println("LocalVariableDeclaration ::= var PushModifiers..."); } //$NON-NLS-1$ + consumeLocalVariableDeclaration(); + break; + + case 76 : if (DEBUG) { System.out.println("LocalVariableDeclarationNoIn ::= var PushModifiers..."); } //$NON-NLS-1$ + consumeLocalVariableDeclaration(); + break; + + case 77 : if (DEBUG) { System.out.println("PushModifiers ::="); } //$NON-NLS-1$ + consumePushModifiers(); + break; + + case 102 : if (DEBUG) { System.out.println("EmptyStatement ::= PushPosition SEMICOLON"); } //$NON-NLS-1$ + consumeEmptyStatement(); + break; + + case 103 : if (DEBUG) { System.out.println("LabeledStatement ::= Label COLON Statement"); } //$NON-NLS-1$ + consumeStatementLabel() ; + break; + + case 104 : if (DEBUG) { System.out.println("LabeledStatementNoShortIf ::= Label COLON..."); } //$NON-NLS-1$ + consumeStatementLabel() ; + break; + + case 105 : if (DEBUG) { System.out.println("Label ::= Identifier"); } //$NON-NLS-1$ + consumeLabel() ; + break; + + case 106 : if (DEBUG) { System.out.println("ExpressionStatement ::= StatementExpression SEMICOLON"); } //$NON-NLS-1$ + consumeExpressionStatement(); + break; + + case 108 : if (DEBUG) { System.out.println("IfThenStatement ::= if LPAREN Expression RPAREN..."); } //$NON-NLS-1$ + consumeStatementIfNoElse(); + break; + + case 109 : if (DEBUG) { System.out.println("IfThenElseStatement ::= if LPAREN Expression RPAREN..."); } //$NON-NLS-1$ + consumeStatementIfWithElse(); + break; + + case 110 : if (DEBUG) { System.out.println("IfThenElseStatementNoShortIf ::= if LPAREN Expression..."); } //$NON-NLS-1$ + consumeStatementIfWithElse(); + break; + + case 111 : if (DEBUG) { System.out.println("IfThenElseStatement ::= if LPAREN Expression RPAREN..."); } //$NON-NLS-1$ + consumeStatementIfWithElse(); + break; + + case 112 : if (DEBUG) { System.out.println("IfThenElseStatementNoShortIf ::= if LPAREN Expression..."); } //$NON-NLS-1$ + consumeStatementIfWithElse(); + break; + + case 113 : if (DEBUG) { System.out.println("SwitchStatement ::= switch LPAREN Expression RPAREN..."); } //$NON-NLS-1$ + consumeStatementSwitch() ; + break; + + case 114 : if (DEBUG) { System.out.println("SwitchBlock ::= LBRACE RBRACE"); } //$NON-NLS-1$ + consumeEmptySwitchBlock() ; + break; + + case 117 : if (DEBUG) { System.out.println("SwitchBlock ::= LBRACE SwitchBlockStatements..."); } //$NON-NLS-1$ + consumeSwitchBlock() ; + break; + + case 119 : if (DEBUG) { System.out.println("SwitchBlockStatements ::= SwitchBlockStatements..."); } //$NON-NLS-1$ + consumeSwitchBlockStatements() ; + break; + + case 120 : if (DEBUG) { System.out.println("SwitchBlockStatement ::= SwitchLabels BlockStatements"); } //$NON-NLS-1$ + consumeSwitchBlockStatement() ; + break; + + case 122 : if (DEBUG) { System.out.println("SwitchLabels ::= SwitchLabels SwitchLabel"); } //$NON-NLS-1$ + consumeSwitchLabels() ; + break; + + case 123 : if (DEBUG) { System.out.println("SwitchLabel ::= case ConstantExpression COLON"); } //$NON-NLS-1$ + consumeCaseLabel(); + break; + + case 124 : if (DEBUG) { System.out.println("SwitchLabel ::= default COLON"); } //$NON-NLS-1$ + consumeDefaultLabel(); + break; + + case 125 : if (DEBUG) { System.out.println("WhileStatement ::= while LPAREN Expression RPAREN..."); } //$NON-NLS-1$ + consumeStatementWhile() ; + break; + + case 126 : if (DEBUG) { System.out.println("WhileStatementNoShortIf ::= while LPAREN Expression..."); } //$NON-NLS-1$ + consumeStatementWhile() ; + break; + + case 127 : if (DEBUG) { System.out.println("WithStatement ::= with LPAREN Expression RPAREN..."); } //$NON-NLS-1$ + consumeStatementWith() ; + break; + + case 128 : if (DEBUG) { System.out.println("WithStatementNoShortIf ::= with LPAREN Expression RPAREN"); } //$NON-NLS-1$ + consumeStatementWith() ; + break; + + case 129 : if (DEBUG) { System.out.println("DoStatement ::= do Statement while LPAREN Expression..."); } //$NON-NLS-1$ + consumeStatementDo() ; + break; + + case 130 : if (DEBUG) { System.out.println("ForStatement ::= for LPAREN ForInitopt SEMICOLON..."); } //$NON-NLS-1$ + consumeStatementFor() ; + break; + + case 131 : if (DEBUG) { System.out.println("ForStatement ::= for LPAREN ForInInit in Expression..."); } //$NON-NLS-1$ + consumeStatementForIn() ; + break; + + case 132 : if (DEBUG) { System.out.println("ForStatementNoShortIf ::= for LPAREN ForInitopt..."); } //$NON-NLS-1$ + consumeStatementFor() ; + break; + + case 133 : if (DEBUG) { System.out.println("ForStatementNoShortIf ::= for LPAREN ForInInit in..."); } //$NON-NLS-1$ + consumeStatementForIn() ; + break; + + case 134 : if (DEBUG) { System.out.println("ForInInit ::= LeftHandSideExpression"); } //$NON-NLS-1$ + consumeForInInit() ; + break; + + case 136 : if (DEBUG) { System.out.println("ForInit ::= ExpressionNoIn"); } //$NON-NLS-1$ + consumeForInit() ; + break; + + case 140 : if (DEBUG) { System.out.println("StatementExpressionList ::= StatementExpressionList..."); } //$NON-NLS-1$ + consumeStatementExpressionList() ; + break; + + case 141 : if (DEBUG) { System.out.println("BreakStatement ::= break SEMICOLON"); } //$NON-NLS-1$ + consumeStatementBreak() ; + break; + + case 142 : if (DEBUG) { System.out.println("BreakStatement ::= break Identifier SEMICOLON"); } //$NON-NLS-1$ + consumeStatementBreakWithLabel() ; + break; + + case 143 : if (DEBUG) { System.out.println("ContinueStatement ::= continue SEMICOLON"); } //$NON-NLS-1$ + consumeStatementContinue() ; + break; + + case 144 : if (DEBUG) { System.out.println("ContinueStatement ::= continue Identifier SEMICOLON"); } //$NON-NLS-1$ + consumeStatementContinueWithLabel() ; + break; + + case 145 : if (DEBUG) { System.out.println("ReturnStatement ::= return Expressionopt SEMICOLON"); } //$NON-NLS-1$ + consumeStatementReturn() ; + break; + + case 146 : if (DEBUG) { System.out.println("ThrowStatement ::= throw Expression SEMICOLON"); } //$NON-NLS-1$ + consumeStatementThrow(); + break; + + case 147 : if (DEBUG) { System.out.println("TryStatement ::= try TryBlock Catches"); } //$NON-NLS-1$ + consumeStatementTry(false); + break; + + case 148 : if (DEBUG) { System.out.println("TryStatement ::= try TryBlock Catchesopt Finally"); } //$NON-NLS-1$ + consumeStatementTry(true); + break; + + case 150 : if (DEBUG) { System.out.println("ExitTryBlock ::="); } //$NON-NLS-1$ + consumeExitTryBlock(); + break; + + case 152 : if (DEBUG) { System.out.println("Catches ::= Catches CatchClause"); } //$NON-NLS-1$ + consumeCatches(); + break; + + case 153 : if (DEBUG) { System.out.println("CatchClause ::= catch LPAREN FormalParameter RPAREN..."); } //$NON-NLS-1$ + consumeStatementCatch() ; + break; + + case 155 : if (DEBUG) { System.out.println("DebuggerStatement ::= debugger SEMICOLON"); } //$NON-NLS-1$ + consumeDebuggerStatement() ; + break; + + case 156 : if (DEBUG) { System.out.println("PushLPAREN ::= LPAREN"); } //$NON-NLS-1$ + consumeLeftParen(); + break; + + case 157 : if (DEBUG) { System.out.println("PushRPAREN ::= RPAREN"); } //$NON-NLS-1$ + consumeRightParen(); + break; + + case 162 : if (DEBUG) { System.out.println("PrimaryNoNewArray ::= SimpleName"); } //$NON-NLS-1$ + consumePrimarySimpleName(); + break; + + case 163 : if (DEBUG) { System.out.println("PrimaryNoNewArray ::= this"); } //$NON-NLS-1$ + consumePrimaryNoNewArrayThis(); + break; + + case 164 : if (DEBUG) { System.out.println("PrimaryNoNewArray ::= PushLPAREN Expression PushRPAREN"); } //$NON-NLS-1$ + consumePrimaryNoNewArray(); + break; + + case 165 : if (DEBUG) { System.out.println("ObjectLiteral ::= LBRACE PushLeftBraceObjectLiteral..."); } //$NON-NLS-1$ + consumeEmptyObjectLiteral(); + break; + + case 166 : if (DEBUG) { System.out.println("ObjectLiteral ::= LBRACE PushLeftBraceObjectLiteral..."); } //$NON-NLS-1$ + consumeObjectLiteral(); + break; + + case 167 : if (DEBUG) { System.out.println("ObjectLiteral ::= LBRACE PushLeftBraceObjectLiteral..."); } //$NON-NLS-1$ + consumeObjectLiteral(); + break; + + case 169 : if (DEBUG) { System.out.println("PropertyNameAndValueList ::= PropertyNameAndValueList..."); } //$NON-NLS-1$ + consumePropertyNameAndValueList(); + break; + + case 170 : if (DEBUG) { System.out.println("PropertyAssignment ::= PropertyName COLON..."); } //$NON-NLS-1$ + consumePropertyAssignment(); + break; + + case 171 : if (DEBUG) { System.out.println("PropertyAssignment ::= PropertyName PropertyName LPAREN"); } //$NON-NLS-1$ + consumeGetSetPropertyAssignment(false); + break; + + case 172 : if (DEBUG) { System.out.println("PropertyAssignment ::= PropertyName PropertyName LPAREN"); } //$NON-NLS-1$ + consumeGetSetPropertyAssignment(true); + break; + + case 173 : if (DEBUG) { System.out.println("PropertySetParameterList ::= SimpleName"); } //$NON-NLS-1$ + consumePropertySetParameterList(); + break; + + case 174 : if (DEBUG) { System.out.println("FunctionBody ::= NestedMethod LBRACE PostDoc..."); } //$NON-NLS-1$ + consumeMethodBody(); + break; + + case 175 : if (DEBUG) { System.out.println("ProgramElementsopt ::="); } //$NON-NLS-1$ + consumeEmptyProgramElements(); + break; + + case 177 : if (DEBUG) { System.out.println("PropertyName ::= SimpleName"); } //$NON-NLS-1$ + consumePropertyName(); + break; + + case 181 : if (DEBUG) { System.out.println("ArrayLiteral ::= ArrayLiteralHeader ElisionOpt RBRACKET"); } //$NON-NLS-1$ + consumeArrayLiteral(false); + break; + + case 182 : if (DEBUG) { System.out.println("ArrayLiteral ::= ArrayLiteralHeader..."); } //$NON-NLS-1$ + consumeArrayLiteral(false); + break; + + case 183 : if (DEBUG) { System.out.println("ArrayLiteral ::= ArrayLiteralHeader..."); } //$NON-NLS-1$ + consumeArrayLiteral(true); + break; + + case 184 : if (DEBUG) { System.out.println("ArrayLiteralHeader ::= LBRACKET"); } //$NON-NLS-1$ + consumeArrayLiteralHeader(); + break; + + case 185 : if (DEBUG) { System.out.println("ElisionOpt ::="); } //$NON-NLS-1$ + consumeElisionEmpty(); + break; + + case 187 : if (DEBUG) { System.out.println("Elision ::= COMMA"); } //$NON-NLS-1$ + consumeElisionOne(); + break; + + case 188 : if (DEBUG) { System.out.println("Elision ::= Elision COMMA"); } //$NON-NLS-1$ + consumeElisionList(); + break; + + case 189 : if (DEBUG) { System.out.println("ArrayLiteralElementList ::= ElisionOpt..."); } //$NON-NLS-1$ + consumeArrayLiteralListOne(); + break; + + case 190 : if (DEBUG) { System.out.println("ArrayLiteralElementList ::= ArrayLiteralElementList..."); } //$NON-NLS-1$ + consumeArrayLiteralList(); + break; + + case 191 : if (DEBUG) { System.out.println("ArrayLiteralElement ::= AssignmentExpression"); } //$NON-NLS-1$ + consumeArrayLiteralElement(); + break; + + case 194 : if (DEBUG) { System.out.println("MemberExpression ::= MemberExpression LBRACKET..."); } //$NON-NLS-1$ + consumeMemberExpressionWithArrayReference(); + break; + + case 195 : if (DEBUG) { System.out.println("MemberExpression ::= MemberExpression DOT SimpleName"); } //$NON-NLS-1$ + consumeMemberExpressionWithSimpleName(); + break; + + case 196 : if (DEBUG) { System.out.println("MemberExpression ::= new MemberExpression Arguments"); } //$NON-NLS-1$ + consumeNewMemberExpressionWithArguments(); + break; + + case 198 : if (DEBUG) { System.out.println("NewExpression ::= new NewExpression"); } //$NON-NLS-1$ + consumeNewExpression(); + break; + + case 199 : if (DEBUG) { System.out.println("CallExpression ::= MemberExpression Arguments"); } //$NON-NLS-1$ + consumeCallExpressionWithArguments(); + break; + + case 200 : if (DEBUG) { System.out.println("CallExpression ::= CallExpression Arguments"); } //$NON-NLS-1$ + consumeCallExpressionWithArguments(); + break; + + case 201 : if (DEBUG) { System.out.println("CallExpression ::= CallExpression LBRACKET Expression..."); } //$NON-NLS-1$ + consumeCallExpressionWithArrayReference(); + break; + + case 202 : if (DEBUG) { System.out.println("CallExpression ::= CallExpression DOT SimpleName"); } //$NON-NLS-1$ + consumeCallExpressionWithSimpleName(); + break; + + case 206 : if (DEBUG) { System.out.println("PostfixExpression ::= LeftHandSideExpression PLUS_PLUS"); } //$NON-NLS-1$ + consumeUnaryExpression(OperatorIds.PLUS, true); + break; + + case 207 : if (DEBUG) { System.out.println("PostfixExpression ::= LeftHandSideExpression MINUS_MINUS"); } //$NON-NLS-1$ + consumeUnaryExpression(OperatorIds.MINUS, true); + break; + + case 209 : if (DEBUG) { System.out.println("ListExpression ::= ListExpression COMMA..."); } //$NON-NLS-1$ + consumeListExpression(); + break; + + case 211 : if (DEBUG) { System.out.println("ListExpressionNoIn ::= ListExpressionNoIn COMMA..."); } //$NON-NLS-1$ + consumeListExpression(); + break; + + case 213 : if (DEBUG) { System.out.println("ListExpressionStmt ::= ListExpressionStmt COMMA..."); } //$NON-NLS-1$ + consumeListExpression(); + break; + + case 215 : if (DEBUG) { System.out.println("ArgumentList ::= ArgumentList COMMA AssignmentExpression"); } //$NON-NLS-1$ + consumeArgumentList(); + break; + + case 216 : if (DEBUG) { System.out.println("PushPosition ::="); } //$NON-NLS-1$ + consumePushPosition(); + break; + + case 219 : if (DEBUG) { System.out.println("UnaryExpression ::= PLUS PushPosition UnaryExpression"); } //$NON-NLS-1$ + consumeUnaryExpression(OperatorIds.PLUS); + break; + + case 220 : if (DEBUG) { System.out.println("UnaryExpression ::= MINUS PushPosition UnaryExpression"); } //$NON-NLS-1$ + consumeUnaryExpression(OperatorIds.MINUS); + break; + + case 222 : if (DEBUG) { System.out.println("PreIncrementExpression ::= PLUS_PLUS PushPosition..."); } //$NON-NLS-1$ + consumeUnaryExpression(OperatorIds.PLUS, false); + break; + + case 223 : if (DEBUG) { System.out.println("PreDecrementExpression ::= MINUS_MINUS PushPosition..."); } //$NON-NLS-1$ + consumeUnaryExpression(OperatorIds.MINUS, false); + break; + + case 225 : if (DEBUG) { System.out.println("UnaryExpressionNotPlusMinus ::= TWIDDLE PushPosition..."); } //$NON-NLS-1$ + consumeUnaryExpression(OperatorIds.TWIDDLE); + break; + + case 226 : if (DEBUG) { System.out.println("UnaryExpressionNotPlusMinus ::= NOT PushPosition..."); } //$NON-NLS-1$ + consumeUnaryExpression(OperatorIds.NOT); + break; + + case 227 : if (DEBUG) { System.out.println("UnaryExpressionNotPlusMinus ::= delete PushPosition..."); } //$NON-NLS-1$ + consumeUnaryExpression(OperatorIds.DELETE); + break; + + case 228 : if (DEBUG) { System.out.println("UnaryExpressionNotPlusMinus ::= void PushPosition..."); } //$NON-NLS-1$ + consumeUnaryExpression(OperatorIds.VOID); + break; + + case 229 : if (DEBUG) { System.out.println("UnaryExpressionNotPlusMinus ::= typeof PushPosition..."); } //$NON-NLS-1$ + consumeUnaryExpression(OperatorIds.TYPEOF); + break; + + case 231 : if (DEBUG) { System.out.println("MultiplicativeExpression ::= MultiplicativeExpression..."); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.MULTIPLY); + break; + + case 232 : if (DEBUG) { System.out.println("MultiplicativeExpression ::= MultiplicativeExpression..."); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.DIVIDE); + break; + + case 233 : if (DEBUG) { System.out.println("MultiplicativeExpression ::= MultiplicativeExpression..."); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.REMAINDER); + break; + + case 235 : if (DEBUG) { System.out.println("AdditiveExpression ::= AdditiveExpression PLUS..."); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.PLUS); + break; + + case 236 : if (DEBUG) { System.out.println("AdditiveExpression ::= AdditiveExpression MINUS..."); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.MINUS); + break; + + case 238 : if (DEBUG) { System.out.println("ShiftExpression ::= ShiftExpression LEFT_SHIFT..."); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.LEFT_SHIFT); + break; + + case 239 : if (DEBUG) { System.out.println("ShiftExpression ::= ShiftExpression RIGHT_SHIFT..."); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.RIGHT_SHIFT); + break; + + case 240 : if (DEBUG) { System.out.println("ShiftExpression ::= ShiftExpression UNSIGNED_RIGHT_SHIFT"); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.UNSIGNED_RIGHT_SHIFT); + break; + + case 242 : if (DEBUG) { System.out.println("RelationalExpression ::= RelationalExpression LESS..."); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.LESS); + break; + + case 243 : if (DEBUG) { System.out.println("RelationalExpression ::= RelationalExpression GREATER..."); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.GREATER); + break; + + case 244 : if (DEBUG) { System.out.println("RelationalExpression ::= RelationalExpression LESS_EQUAL"); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.LESS_EQUAL); + break; + + case 245 : if (DEBUG) { System.out.println("RelationalExpression ::= RelationalExpression..."); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.GREATER_EQUAL); + break; + + case 246 : if (DEBUG) { System.out.println("RelationalExpression ::= RelationalExpression instanceof"); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.INSTANCEOF); + break; + + case 247 : if (DEBUG) { System.out.println("RelationalExpression ::= RelationalExpression in..."); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.IN); + break; + + case 249 : if (DEBUG) { System.out.println("RelationalExpressionNoIn ::= RelationalExpressionNoIn..."); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.LESS); + break; + + case 250 : if (DEBUG) { System.out.println("RelationalExpressionNoIn ::= RelationalExpressionNoIn..."); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.GREATER); + break; + + case 251 : if (DEBUG) { System.out.println("RelationalExpressionNoIn ::= RelationalExpressionNoIn..."); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.LESS_EQUAL); + break; + + case 252 : if (DEBUG) { System.out.println("RelationalExpressionNoIn ::= RelationalExpressionNoIn..."); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.GREATER_EQUAL); + break; + + case 253 : if (DEBUG) { System.out.println("RelationalExpressionNoIn ::= RelationalExpressionNoIn..."); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.INSTANCEOF); + break; + + case 255 : if (DEBUG) { System.out.println("EqualityExpression ::= EqualityExpression EQUAL_EQUAL..."); } //$NON-NLS-1$ + consumeEqualityExpression(OperatorIds.EQUAL_EQUAL); + break; + + case 256 : if (DEBUG) { System.out.println("EqualityExpression ::= EqualityExpression NOT_EQUAL..."); } //$NON-NLS-1$ + consumeEqualityExpression(OperatorIds.NOT_EQUAL); + break; + + case 257 : if (DEBUG) { System.out.println("EqualityExpression ::= EqualityExpression..."); } //$NON-NLS-1$ + consumeEqualityExpression(OperatorIds.EQUAL_EQUAL_EQUAL); + break; + + case 258 : if (DEBUG) { System.out.println("EqualityExpression ::= EqualityExpression..."); } //$NON-NLS-1$ + consumeEqualityExpression(OperatorIds.NOT_EQUAL_EQUAL); + break; + + case 260 : if (DEBUG) { System.out.println("EqualityExpressionNoIn ::= EqualityExpressionNoIn..."); } //$NON-NLS-1$ + consumeEqualityExpression(OperatorIds.EQUAL_EQUAL); + break; + + case 261 : if (DEBUG) { System.out.println("EqualityExpressionNoIn ::= EqualityExpressionNoIn..."); } //$NON-NLS-1$ + consumeEqualityExpression(OperatorIds.NOT_EQUAL); + break; + + case 262 : if (DEBUG) { System.out.println("EqualityExpressionNoIn ::= EqualityExpressionNoIn..."); } //$NON-NLS-1$ + consumeEqualityExpression(OperatorIds.EQUAL_EQUAL_EQUAL); + break; + + case 263 : if (DEBUG) { System.out.println("EqualityExpressionNoIn ::= EqualityExpressionNoIn..."); } //$NON-NLS-1$ + consumeEqualityExpression(OperatorIds.NOT_EQUAL_EQUAL); + break; + + case 265 : if (DEBUG) { System.out.println("AndExpression ::= AndExpression AND EqualityExpression"); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.AND); + break; + + case 267 : if (DEBUG) { System.out.println("AndExpressionNoIn ::= AndExpressionNoIn AND..."); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.AND); + break; + + case 269 : if (DEBUG) { System.out.println("ExclusiveOrExpression ::= ExclusiveOrExpression XOR..."); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.XOR); + break; + + case 271 : if (DEBUG) { System.out.println("ExclusiveOrExpressionNoIn ::= ExclusiveOrExpressionNoIn"); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.XOR); + break; + + case 273 : if (DEBUG) { System.out.println("InclusiveOrExpression ::= InclusiveOrExpression OR..."); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.OR); + break; + + case 275 : if (DEBUG) { System.out.println("InclusiveOrExpressionNoIn ::= InclusiveOrExpressionNoIn"); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.OR); + break; + + case 277 : if (DEBUG) { System.out.println("ConditionalAndExpression ::= ConditionalAndExpression..."); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.AND_AND); + break; + + case 279 : if (DEBUG) { System.out.println("ConditionalAndExpressionNoIn ::=..."); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.AND_AND); + break; + + case 281 : if (DEBUG) { System.out.println("ConditionalOrExpression ::= ConditionalOrExpression..."); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.OR_OR); + break; + + case 283 : if (DEBUG) { System.out.println("ConditionalOrExpressionNoIn ::=..."); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.OR_OR); + break; + + case 285 : if (DEBUG) { System.out.println("ConditionalExpression ::= ConditionalOrExpression..."); } //$NON-NLS-1$ + consumeConditionalExpression(OperatorIds.QUESTIONCOLON); + break; + + case 287 : if (DEBUG) { System.out.println("ConditionalExpressionNoIn ::=..."); } //$NON-NLS-1$ + consumeConditionalExpression(OperatorIds.QUESTIONCOLON); + break; + + case 292 : if (DEBUG) { System.out.println("Assignment ::= PostfixExpression AssignmentOperator..."); } //$NON-NLS-1$ + consumeAssignment(); + break; + + case 293 : if (DEBUG) { System.out.println("AssignmentNoIn ::= PostfixExpression AssignmentOperator"); } //$NON-NLS-1$ + consumeAssignment(); + break; + + case 294 : if (DEBUG) { System.out.println("AssignmentOperator ::= EQUAL"); } //$NON-NLS-1$ + consumeAssignmentOperator(EQUAL); + break; + + case 295 : if (DEBUG) { System.out.println("AssignmentOperator ::= MULTIPLY_EQUAL"); } //$NON-NLS-1$ + consumeAssignmentOperator(MULTIPLY); + break; + + case 296 : if (DEBUG) { System.out.println("AssignmentOperator ::= DIVIDE_EQUAL"); } //$NON-NLS-1$ + consumeAssignmentOperator(DIVIDE); + break; + + case 297 : if (DEBUG) { System.out.println("AssignmentOperator ::= REMAINDER_EQUAL"); } //$NON-NLS-1$ + consumeAssignmentOperator(REMAINDER); + break; + + case 298 : if (DEBUG) { System.out.println("AssignmentOperator ::= PLUS_EQUAL"); } //$NON-NLS-1$ + consumeAssignmentOperator(PLUS); + break; + + case 299 : if (DEBUG) { System.out.println("AssignmentOperator ::= MINUS_EQUAL"); } //$NON-NLS-1$ + consumeAssignmentOperator(MINUS); + break; + + case 300 : if (DEBUG) { System.out.println("AssignmentOperator ::= LEFT_SHIFT_EQUAL"); } //$NON-NLS-1$ + consumeAssignmentOperator(LEFT_SHIFT); + break; + + case 301 : if (DEBUG) { System.out.println("AssignmentOperator ::= RIGHT_SHIFT_EQUAL"); } //$NON-NLS-1$ + consumeAssignmentOperator(RIGHT_SHIFT); + break; + + case 302 : if (DEBUG) { System.out.println("AssignmentOperator ::= UNSIGNED_RIGHT_SHIFT_EQUAL"); } //$NON-NLS-1$ + consumeAssignmentOperator(UNSIGNED_RIGHT_SHIFT); + break; + + case 303 : if (DEBUG) { System.out.println("AssignmentOperator ::= AND_EQUAL"); } //$NON-NLS-1$ + consumeAssignmentOperator(AND); + break; + + case 304 : if (DEBUG) { System.out.println("AssignmentOperator ::= XOR_EQUAL"); } //$NON-NLS-1$ + consumeAssignmentOperator(XOR); + break; + + case 305 : if (DEBUG) { System.out.println("AssignmentOperator ::= OR_EQUAL"); } //$NON-NLS-1$ + consumeAssignmentOperator(OR); + break; + + case 308 : if (DEBUG) { System.out.println("Expressionopt ::="); } //$NON-NLS-1$ + consumeEmptyExpression(); + break; + + case 314 : if (DEBUG) { System.out.println("PrimaryNoNewArrayStmt ::= SimpleName"); } //$NON-NLS-1$ + consumePrimarySimpleName(); + break; + + case 315 : if (DEBUG) { System.out.println("PrimaryNoNewArrayStmt ::= this"); } //$NON-NLS-1$ + consumePrimaryNoNewArrayThis(); + break; + + case 316 : if (DEBUG) { System.out.println("PrimaryNoNewArrayStmt ::= PushLPAREN Expression..."); } //$NON-NLS-1$ + consumePrimaryNoNewArray(); + break; + + case 318 : if (DEBUG) { System.out.println("MemberExpressionStmt ::= MemberExpressionStmt LBRACKET"); } //$NON-NLS-1$ + consumeMemberExpressionWithArrayReference(); + break; + + case 319 : if (DEBUG) { System.out.println("MemberExpressionStmt ::= MemberExpressionStmt DOT..."); } //$NON-NLS-1$ + consumeMemberExpressionWithSimpleName(); + break; + + case 320 : if (DEBUG) { System.out.println("MemberExpressionStmt ::= new MemberExpressionStmt..."); } //$NON-NLS-1$ + consumeNewMemberExpressionWithArguments(); + break; + + case 322 : if (DEBUG) { System.out.println("NewExpressionStmt ::= new NewExpressionStmt"); } //$NON-NLS-1$ + consumeNewExpression(); + break; + + case 323 : if (DEBUG) { System.out.println("CallExpressionStmt ::= MemberExpressionStmt Arguments"); } //$NON-NLS-1$ + consumeCallExpressionWithArguments(); + break; + + case 324 : if (DEBUG) { System.out.println("CallExpressionStmt ::= CallExpressionStmt Arguments"); } //$NON-NLS-1$ + consumeCallExpressionWithArguments(); + break; + + case 325 : if (DEBUG) { System.out.println("CallExpressionStmt ::= CallExpressionStmt LBRACKET..."); } //$NON-NLS-1$ + consumeCallExpressionWithArrayReference(); + break; + + case 326 : if (DEBUG) { System.out.println("CallExpressionStmt ::= CallExpressionStmt DOT SimpleName"); } //$NON-NLS-1$ + consumeCallExpressionWithSimpleName(); + break; + + case 327 : if (DEBUG) { System.out.println("Arguments ::= LPAREN ArgumentListopt RPAREN"); } //$NON-NLS-1$ + consumeArguments(); + break; + + case 331 : if (DEBUG) { System.out.println("PostfixExpressionStmt ::= LeftHandSideExpressionStmt..."); } //$NON-NLS-1$ + consumeUnaryExpression(OperatorIds.PLUS, true); + break; + + case 332 : if (DEBUG) { System.out.println("PostfixExpressionStmt ::= LeftHandSideExpressionStmt..."); } //$NON-NLS-1$ + consumeUnaryExpression(OperatorIds.MINUS, true); + break; + + case 333 : if (DEBUG) { System.out.println("PreIncrementExpressionStmt ::= PLUS_PLUS PushPosition..."); } //$NON-NLS-1$ + consumeUnaryExpression(OperatorIds.PLUS, false); + break; + + case 334 : if (DEBUG) { System.out.println("PreDecrementExpressionStmt ::= MINUS_MINUS PushPosition"); } //$NON-NLS-1$ + consumeUnaryExpression(OperatorIds.MINUS, false); + break; + + case 337 : if (DEBUG) { System.out.println("UnaryExpressionStmt ::= PLUS PushPosition..."); } //$NON-NLS-1$ + consumeUnaryExpression(OperatorIds.PLUS); + break; + + case 338 : if (DEBUG) { System.out.println("UnaryExpressionStmt ::= MINUS PushPosition..."); } //$NON-NLS-1$ + consumeUnaryExpression(OperatorIds.MINUS); + break; + + case 341 : if (DEBUG) { System.out.println("UnaryExpressionNotPlusMinusStmt ::= TWIDDLE PushPosition"); } //$NON-NLS-1$ + consumeUnaryExpression(OperatorIds.TWIDDLE); + break; + + case 342 : if (DEBUG) { System.out.println("UnaryExpressionNotPlusMinusStmt ::= NOT PushPosition..."); } //$NON-NLS-1$ + consumeUnaryExpression(OperatorIds.NOT); + break; + + case 343 : if (DEBUG) { System.out.println("UnaryExpressionNotPlusMinusStmt ::= delete PushPosition"); } //$NON-NLS-1$ + consumeUnaryExpression(OperatorIds.DELETE); + break; + + case 344 : if (DEBUG) { System.out.println("UnaryExpressionNotPlusMinusStmt ::= void PushPosition..."); } //$NON-NLS-1$ + consumeUnaryExpression(OperatorIds.VOID); + break; + + case 345 : if (DEBUG) { System.out.println("UnaryExpressionNotPlusMinusStmt ::= typeof PushPosition"); } //$NON-NLS-1$ + consumeUnaryExpression(OperatorIds.TYPEOF); + break; + + case 347 : if (DEBUG) { System.out.println("MultiplicativeExpressionStmt ::=..."); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.MULTIPLY); + break; + + case 348 : if (DEBUG) { System.out.println("MultiplicativeExpressionStmt ::=..."); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.DIVIDE); + break; + + case 349 : if (DEBUG) { System.out.println("MultiplicativeExpressionStmt ::=..."); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.REMAINDER); + break; + + case 351 : if (DEBUG) { System.out.println("AdditiveExpressionStmt ::= AdditiveExpressionStmt PLUS"); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.PLUS); + break; + + case 352 : if (DEBUG) { System.out.println("AdditiveExpressionStmt ::= AdditiveExpressionStmt MINUS"); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.MINUS); + break; + + case 354 : if (DEBUG) { System.out.println("ShiftExpressionStmt ::= ShiftExpressionStmt LEFT_SHIFT"); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.LEFT_SHIFT); + break; + + case 355 : if (DEBUG) { System.out.println("ShiftExpressionStmt ::= ShiftExpressionStmt RIGHT_SHIFT"); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.RIGHT_SHIFT); + break; + + case 356 : if (DEBUG) { System.out.println("ShiftExpressionStmt ::= ShiftExpressionStmt..."); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.UNSIGNED_RIGHT_SHIFT); + break; + + case 358 : if (DEBUG) { System.out.println("RelationalExpressionStmt ::= RelationalExpressionStmt..."); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.LESS); + break; + + case 359 : if (DEBUG) { System.out.println("RelationalExpressionStmt ::= RelationalExpressionStmt..."); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.GREATER); + break; + + case 360 : if (DEBUG) { System.out.println("RelationalExpressionStmt ::= RelationalExpressionStmt..."); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.LESS_EQUAL); + break; + + case 361 : if (DEBUG) { System.out.println("RelationalExpressionStmt ::= RelationalExpressionStmt..."); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.GREATER_EQUAL); + break; + + case 362 : if (DEBUG) { System.out.println("RelationalExpressionStmt ::= RelationalExpressionStmt..."); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.INSTANCEOF); + break; + + case 363 : if (DEBUG) { System.out.println("RelationalExpressionStmt ::= RelationalExpressionStmt in"); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.IN); + break; + + case 365 : if (DEBUG) { System.out.println("EqualityExpressionStmt ::= EqualityExpressionStmt..."); } //$NON-NLS-1$ + consumeEqualityExpression(OperatorIds.EQUAL_EQUAL); + break; + + case 366 : if (DEBUG) { System.out.println("EqualityExpressionStmt ::= EqualityExpressionStmt..."); } //$NON-NLS-1$ + consumeEqualityExpression(OperatorIds.NOT_EQUAL); + break; + + case 367 : if (DEBUG) { System.out.println("EqualityExpressionStmt ::= EqualityExpressionStmt..."); } //$NON-NLS-1$ + consumeEqualityExpression(OperatorIds.EQUAL_EQUAL_EQUAL); + break; + + case 368 : if (DEBUG) { System.out.println("EqualityExpressionStmt ::= EqualityExpressionStmt..."); } //$NON-NLS-1$ + consumeEqualityExpression(OperatorIds.NOT_EQUAL_EQUAL); + break; + + case 370 : if (DEBUG) { System.out.println("AndExpressionStmt ::= AndExpressionStmt AND..."); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.AND); + break; + + case 372 : if (DEBUG) { System.out.println("ExclusiveOrExpressionStmt ::= ExclusiveOrExpressionStmt"); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.XOR); + break; + + case 374 : if (DEBUG) { System.out.println("InclusiveOrExpressionStmt ::= InclusiveOrExpressionStmt"); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.OR); + break; + + case 376 : if (DEBUG) { System.out.println("ConditionalAndExpressionStmt ::=..."); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.AND_AND); + break; + + case 378 : if (DEBUG) { System.out.println("ConditionalOrExpressionStmt ::=..."); } //$NON-NLS-1$ + consumeBinaryExpression(OperatorIds.OR_OR); + break; + + case 380 : if (DEBUG) { System.out.println("ConditionalExpressionStmt ::=..."); } //$NON-NLS-1$ + consumeConditionalExpression(OperatorIds.QUESTIONCOLON) ; + break; + + case 383 : if (DEBUG) { System.out.println("AssignmentStmt ::= PostfixExpressionStmt..."); } //$NON-NLS-1$ + consumeAssignment(); + break; + + case 384 : if (DEBUG) { System.out.println("Modifiersopt ::="); } //$NON-NLS-1$ + consumeDefaultModifiers(); + break; + + case 385 : if (DEBUG) { System.out.println("BlockStatementsopt ::="); } //$NON-NLS-1$ + consumeEmptyBlockStatementsopt(); + break; + + case 387 : if (DEBUG) { System.out.println("ArgumentListopt ::="); } //$NON-NLS-1$ + consumeEmptyArgumentListopt(); + break; + + case 389 : if (DEBUG) { System.out.println("FormalParameterListopt ::="); } //$NON-NLS-1$ + consumeFormalParameterListopt(); + break; + + case 391 : if (DEBUG) { System.out.println("ForInitopt ::="); } //$NON-NLS-1$ + consumeEmptyForInitopt(); + break; + + case 393 : if (DEBUG) { System.out.println("ForUpdateopt ::="); } //$NON-NLS-1$ + consumeEmptyForUpdateopt(); + break; + + case 395 : if (DEBUG) { System.out.println("Catchesopt ::="); } //$NON-NLS-1$ + consumeEmptyCatchesopt(); + break; + + case 397 : if (DEBUG) { System.out.println("RecoveryMethodHeaderName ::= Modifiersopt function..."); } //$NON-NLS-1$ + consumeRecoveryMethodHeaderName(); + break; + + case 398 : if (DEBUG) { System.out.println("RecoveryMethodHeader ::= RecoveryMethodHeaderName..."); } //$NON-NLS-1$ + consumeMethodHeader(); + break; + + } +} + + +private void consumeElisionList() { + int flag=this.intStack[this.intPtr]; + if ((flag&UNCONSUMED_ELISION)!=0) + { + pushOnExpressionStack(new EmptyExpression(this.endPosition,this.endPosition)); + } + concatExpressionLists(); +// this.intStack[this.intPtr]&= ~(UNCONSUMED_ELISION|UNCONSUMED_LIT_ELEMENT); +} +private void consumeElisionOne() { + pushOnExpressionStack(new EmptyExpression(this.endPosition,this.endPosition)); + if ( (this.intStack[this.intPtr]&UNCONSUMED_LIT_ELEMENT)!=0 || (this.intStack[this.intPtr]&WAS_ARRAY_LIT_ELEMENT)!=0) + concatExpressionLists(); + this.intStack[this.intPtr]|=(WAS_ARRAY_LIT_ELEMENT|UNCONSUMED_ELISION) ; + +} +private void consumeArrayLiteralElement() { + this.intStack[this.intPtr]|= (WAS_ARRAY_LIT_ELEMENT|UNCONSUMED_LIT_ELEMENT); +} +private void consumeElisionEmpty() { +} +private void consumeForInInit() { + Expression expression = this.expressionStack[this.expressionPtr--]; + this.expressionLengthPtr--; + Statement var = expression; + pushOnAstStack(var); + +} +private void consumeStatementWith() { + this.expressionLengthPtr--; + Statement statement = (Statement) this.astStack[this.astPtr]; + this.astStack[this.astPtr] = + new WithStatement( + this.expressionStack[this.expressionPtr--], + statement, + this.intStack[this.intPtr--], + this.endStatementPosition); +} + +private void consumeArrayLiteral(boolean addElision) { + int flag=this.intStack[this.intPtr--]; + if (addElision || (flag&UNCONSUMED_ELISION)!=0) + { + pushOnExpressionStack(new EmptyExpression(this.endPosition,this.endPosition)); + concatExpressionLists(); + } + int length = ((flag&WAS_ARRAY_LIT_ELEMENT)>0)? this.expressionLengthStack[this.expressionLengthPtr--] : 0; + arrayInitializer(length); + +} +private void consumeObjectLiteral() { + ObjectLiteral objectLiteral = new ObjectLiteral(); + int length; + if ((length = this.expressionLengthStack[this.expressionLengthPtr--]) != 0) { + this.expressionPtr -= length; + System.arraycopy( + this.expressionStack, + this.expressionPtr + 1, + objectLiteral.fields = new ObjectLiteralField[length], + 0, + length); + } + objectLiteral.sourceEnd = this.endStatementPosition; + objectLiteral.sourceStart = this.intStack[this.intPtr--]; + + pushOnExpressionStack(objectLiteral); +} +protected void consumeStatementBreak() { + // BreakStatement ::= 'break' ';' + // break pushs a position on this.intStack in case there is no label + + pushOnAstStack(new BreakStatement(null, this.intStack[this.intPtr--], this.endStatementPosition)); + if (this.pendingRecoveredType != null) { + // Used only in statements recovery. + // This is not a real break statement but a placeholder for an existing local type. + // The break statement must be replace by the local type. + if (this.pendingRecoveredType.allocation == null && + this.endPosition <= this.pendingRecoveredType.declarationSourceEnd) { + this.astStack[this.astPtr] = this.pendingRecoveredType; + this.pendingRecoveredType = null; + return; + } + this.pendingRecoveredType = null; + } +} +protected void consumeStatementBreakWithLabel() { + // BreakStatement ::= 'break' Identifier ';' + // break pushs a position on this.intStack in case there is no label + + pushOnAstStack( + new BreakStatement( + this.identifierStack[this.identifierPtr--], + this.intStack[this.intPtr--], + this.endStatementPosition)); + this.identifierLengthPtr--; +} +protected void consumeStatementCatch() { + // CatchClause ::= 'catch' '(' FormalParameter ')' Block + + //catch are stored directly into the Try + //has they always comes two by two.... + //we remove one entry from the astlengthPtr. + //The construction of the try statement must + //then fetch the catches using 2*i and 2*i + 1 + + this.astLengthPtr--; + this.listLength = 0; // reset formalParameter counter (incremented for catch variable) +} +protected void consumeStatementContinue() { + // ContinueStatement ::= 'continue' ';' + // continue pushs a position on this.intStack in case there is no label + + pushOnAstStack( + new ContinueStatement( + null, + this.intStack[this.intPtr--], + this.endStatementPosition)); +} +protected void consumeStatementContinueWithLabel() { + // ContinueStatement ::= 'continue' Identifier ';' + // continue pushs a position on this.intStack in case there is no label + + pushOnAstStack( + new ContinueStatement( + this.identifierStack[this.identifierPtr--], + this.intStack[this.intPtr--], + this.endStatementPosition)); + this.identifierLengthPtr--; +} +protected void consumeStatementDo() { + // DoStatement ::= 'do' Statement 'while' '(' Expression ')' ';' + + //the 'while' pushes a value on this.intStack that we need to remove + this.intPtr--; + + Statement statement = (Statement) this.astStack[this.astPtr]; + this.expressionLengthPtr--; + this.astStack[this.astPtr] = + new DoStatement( + this.expressionStack[this.expressionPtr--], + statement, + this.intStack[this.intPtr--], + this.endStatementPosition); +} +protected void consumeStatementExpressionList() { + // StatementExpressionList ::= StatementExpressionList ',' StatementExpression + concatExpressionLists(); +} +protected void consumeStatementFor() { + // ForStatement ::= 'for' '(' ForInitopt ';' Expressionopt ';' ForUpdateopt ')' Statement + // ForStatementNoShortIf ::= 'for' '(' ForInitopt ';' Expressionopt ';' ForUpdateopt ')' StatementNoShortIf + + int length; + Expression cond = null; + Statement[] inits, updates; + boolean scope = true; + + //statements + this.astLengthPtr--; + Statement statement = (Statement) this.astStack[this.astPtr--]; + + //updates are on the expresion stack + if ((length = this.expressionLengthStack[this.expressionLengthPtr--]) == 0) { + updates = null; + } else { + this.expressionPtr -= length; + System.arraycopy( + this.expressionStack, + this.expressionPtr + 1, + updates = new Statement[length], + 0, + length); + } + + if (this.expressionLengthStack[this.expressionLengthPtr--] != 0) + cond = this.expressionStack[this.expressionPtr--]; + + //inits may be on two different stacks + if ((length = this.astLengthStack[this.astLengthPtr--]) == 0) { + inits = null; + scope = false; + } else { + if (length == -1) { //on this.expressionStack + scope = false; + length = this.expressionLengthStack[this.expressionLengthPtr--]; + this.expressionPtr -= length; + System.arraycopy( + this.expressionStack, + this.expressionPtr + 1, + inits = new Statement[length], + 0, + length); + } else { //on this.astStack + this.astPtr -= length; + System.arraycopy( + this.astStack, + this.astPtr + 1, + inits = new Statement[length], + 0, + length); + } + } + pushOnAstStack( + new ForStatement( + inits, + cond, + updates, + statement, + scope, + this.intStack[this.intPtr--], + this.endStatementPosition)); +} +protected void consumeStatementIfNoElse() { + // IfThenStatement ::= 'if' '(' Expression ')' Statement + + //optimize the push/pop + this.expressionLengthPtr--; + Statement thenStatement = (Statement) this.astStack[this.astPtr]; + this.astStack[this.astPtr] = + new IfStatement( + this.expressionStack[this.expressionPtr--], + thenStatement, + this.intStack[this.intPtr--], + this.endStatementPosition); +} +protected void consumeStatementIfWithElse() { + // IfThenElseStatement ::= 'if' '(' Expression ')' StatementNoShortIf 'else' Statement + // IfThenElseStatementNoShortIf ::= 'if' '(' Expression ')' StatementNoShortIf 'else' StatementNoShortIf + + this.expressionLengthPtr--; + + // optimized {..., Then, Else } ==> {..., If } + this.astLengthPtr--; + + //optimize the push/pop + this.astStack[--this.astPtr] = + new IfStatement( + this.expressionStack[this.expressionPtr--], + (Statement) this.astStack[this.astPtr], + (Statement) this.astStack[this.astPtr + 1], + this.intStack[this.intPtr--], + this.endStatementPosition); +} +protected void consumeStatementLabel() { + // LabeledStatement ::= 'Identifier' ':' Statement + // LabeledStatementNoShortIf ::= 'Identifier' ':' StatementNoShortIf + + //optimize push/pop + Statement statement = (Statement) this.astStack[this.astPtr]; + this.astStack[this.astPtr] = + new LabeledStatement( + this.identifierStack[this.identifierPtr], + statement, + this.identifierPositionStack[this.identifierPtr--], + this.endStatementPosition); + this.identifierLengthPtr--; +} +protected void consumeStatementReturn() { + // ReturnStatement ::= 'return' Expressionopt ';' + // return pushs a position on this.intStack in case there is no expression + + if (this.expressionLengthStack[this.expressionLengthPtr--] != 0) { + pushOnAstStack( + new ReturnStatement( + this.expressionStack[this.expressionPtr--], + this.intStack[this.intPtr--], + this.endStatementPosition) + ); + } else { + pushOnAstStack(new ReturnStatement(null, this.intStack[this.intPtr--], this.endStatementPosition)); + } +} +protected void consumeStatementSwitch() { + // SwitchStatement ::= 'switch' OpenBlock '(' Expression ')' SwitchBlock + + //OpenBlock just makes the semantic action blockStart() + //the block is inlined but a scope need to be created + //if some declaration occurs. + + int length; + SwitchStatement switchStatement = new SwitchStatement(); + this.expressionLengthPtr--; + switchStatement.expression = this.expressionStack[this.expressionPtr--]; + if ((length = this.astLengthStack[this.astLengthPtr--]) != 0) { + this.astPtr -= length; + System.arraycopy( + this.astStack, + this.astPtr + 1, + switchStatement.statements = new Statement[length], + 0, + length); + } + switchStatement.explicitDeclarations = this.realBlockStack[this.realBlockPtr--]; + pushOnAstStack(switchStatement); + switchStatement.blockStart = this.intStack[this.intPtr--]; + switchStatement.sourceStart = this.intStack[this.intPtr--]; + switchStatement.sourceEnd = this.endStatementPosition; + if (length == 0 && !containsComment(switchStatement.blockStart, switchStatement.sourceEnd)) { + switchStatement.bits |= ASTNode.UndocumentedEmptyBlock; + } +} + +protected void consumeStatementThrow() { + // ThrowStatement ::= 'throw' Expression ';' + this.expressionLengthPtr--; + pushOnAstStack(new ThrowStatement(this.expressionStack[this.expressionPtr--], this.intStack[this.intPtr--], this.endStatementPosition)); +} +protected void consumeStatementTry(boolean withFinally) { + //TryStatement ::= 'try' Block Catches + //TryStatement ::= 'try' Block Catchesopt Finally + + int length; + TryStatement tryStmt = new TryStatement(); + //finally + if (withFinally) { + this.astLengthPtr--; + tryStmt.finallyBlock = (Block) this.astStack[this.astPtr--]; + } + //catches are handle by two [see statementCatch] + if ((length = this.astLengthStack[this.astLengthPtr--]) != 0) { + if (length == 1) { + tryStmt.catchBlocks = new Block[] {(Block) this.astStack[this.astPtr--]}; + tryStmt.catchArguments = new Argument[] {(Argument) this.astStack[this.astPtr--]}; + } else { + Block[] bks = (tryStmt.catchBlocks = new Block[length]); + Argument[] args = (tryStmt.catchArguments = new Argument[length]); + while (length-- > 0) { + bks[length] = (Block) this.astStack[this.astPtr--]; + args[length] = (Argument) this.astStack[this.astPtr--]; + } + } + } + //try + this.astLengthPtr--; + tryStmt.tryBlock = (Block) this.astStack[this.astPtr--]; + + //positions + tryStmt.sourceEnd = this.endStatementPosition; + tryStmt.sourceStart = this.intStack[this.intPtr--]; + pushOnAstStack(tryStmt); +} +protected void consumeStatementWhile() { + // WhileStatement ::= 'while' '(' Expression ')' Statement + // WhileStatementNoShortIf ::= 'while' '(' Expression ')' StatementNoShortIf + + this.expressionLengthPtr--; + Statement statement = (Statement) this.astStack[this.astPtr]; + this.astStack[this.astPtr] = + new WhileStatement( + this.expressionStack[this.expressionPtr--], + statement, + this.intStack[this.intPtr--], + this.endStatementPosition); +} + +protected void consumeSwitchBlock() { + // SwitchBlock ::= '{' SwitchBlockStatements SwitchLabels '}' + concatNodeLists(); +} +protected void consumeSwitchBlockStatement() { + // SwitchBlockStatement ::= SwitchLabels BlockStatements + concatNodeLists(); +} +protected void consumeSwitchBlockStatements() { + // SwitchBlockStatements ::= SwitchBlockStatements SwitchBlockStatement + concatNodeLists(); +} +protected void consumeSwitchLabels() { + // SwitchLabels ::= SwitchLabels SwitchLabel + optimizedConcatNodeLists(); +} +protected void consumeToken(int type) { + /* remember the last consumed value */ + /* try to minimize the number of build values */ +// // clear the commentPtr of the scanner in case we read something different from a modifier +// switch(type) { +// case TokenNameabstract : +// case TokenNamestrictfp : +// case TokenNamefinal : +// case TokenNamenative : +// case TokenNameprivate : +// case TokenNameprotected : +// case TokenNamepublic : +// case TokenNametransient : +// case TokenNamevolatile : +// case TokenNamestatic : +// case TokenNamesynchronized : +// break; +// default: +// this.scanner.commentPtr = -1; +// } + //System.out.println(this.scanner.toStringAction(type)); + switch (type) { + case TokenNameIdentifier : + pushIdentifier(); + break; + case TokenNameinterface : + //'class' is pushing two int (positions) on the stack ==> 'interface' needs to do it too.... + pushOnIntStack(this.scanner.currentPosition - 1); + pushOnIntStack(this.scanner.startPosition); + break; + case TokenNameabstract : + checkAndSetModifiers(ClassFileConstants.AccAbstract); + pushOnExpressionStackLengthStack(0); + break; + case TokenNamefinal : + checkAndSetModifiers(ClassFileConstants.AccFinal); + pushOnExpressionStackLengthStack(0); + break; + case TokenNamenative : + checkAndSetModifiers(ClassFileConstants.AccNative); + pushOnExpressionStackLengthStack(0); + break; + case TokenNameprivate : + checkAndSetModifiers(ClassFileConstants.AccPrivate); + pushOnExpressionStackLengthStack(0); + break; + case TokenNameprotected : + checkAndSetModifiers(ClassFileConstants.AccProtected); + pushOnExpressionStackLengthStack(0); + break; + case TokenNamepublic : + checkAndSetModifiers(ClassFileConstants.AccPublic); + pushOnExpressionStackLengthStack(0); + break; + case TokenNametransient : + pushOnExpressionStackLengthStack(0); + break; + case TokenNamevolatile : + pushOnExpressionStackLengthStack(0); + break; + case TokenNamestatic : + checkAndSetModifiers(ClassFileConstants.AccStatic); + pushOnExpressionStackLengthStack(0); + break; +// case TokenNamesynchronized : +// this.synchronizedBlockSourceStart = this.scanner.startPosition; +// checkAndSetModifiers(ClassFileConstants.AccSynchronized); +// pushOnExpressionStackLengthStack(0); +// break; + //============================== +// case TokenNamevoid : +// pushIdentifier(-T_void); +// pushOnIntStack(this.scanner.currentPosition - 1); +// pushOnIntStack(this.scanner.startPosition); +// break; + //push a default dimension while void is not part of the primitive + //declaration baseType and so takes the place of a type without getting into + //regular type parsing that generates a dimension on this.intStack + case TokenNameboolean : + pushIdentifier(-T_boolean); + pushOnIntStack(this.scanner.currentPosition - 1); + pushOnIntStack(this.scanner.startPosition); + break; + case TokenNamechar : + pushIdentifier(-T_char); + pushOnIntStack(this.scanner.currentPosition - 1); + pushOnIntStack(this.scanner.startPosition); + break; + case TokenNamedouble : + pushIdentifier(-T_double); + pushOnIntStack(this.scanner.currentPosition - 1); + pushOnIntStack(this.scanner.startPosition); + break; + case TokenNamefloat : + pushIdentifier(-T_float); + pushOnIntStack(this.scanner.currentPosition - 1); + pushOnIntStack(this.scanner.startPosition); + break; + case TokenNameint : + pushIdentifier(-T_int); + pushOnIntStack(this.scanner.currentPosition - 1); + pushOnIntStack(this.scanner.startPosition); + break; + case TokenNamelong : + pushIdentifier(-T_long); + pushOnIntStack(this.scanner.currentPosition - 1); + pushOnIntStack(this.scanner.startPosition); + break; + case TokenNameshort : + pushIdentifier(-T_short); + pushOnIntStack(this.scanner.currentPosition - 1); + pushOnIntStack(this.scanner.startPosition); + break; + //============================== + case TokenNameIntegerLiteral : + pushOnExpressionStack( + new IntLiteral( + this.scanner.getCurrentTokenSource(), + this.scanner.startPosition, + this.scanner.currentPosition - 1)); + break; + case TokenNameLongLiteral : + case TokenNameFloatingPointLiteral : + case TokenNameDoubleLiteral : + pushOnExpressionStack( + new DoubleLiteral( + this.scanner.getCurrentTokenSource(), + this.scanner.startPosition, + this.scanner.currentPosition - 1)); + break; + case TokenNameCharacterLiteral : + StringLiteral stringLiteral; + if (this.recordStringLiterals && this.checkExternalizeStrings && !this.statementRecoveryActivated) { + stringLiteral = this.createStringLiteral( + this.scanner.getCurrentTokenSourceString(), + this.scanner.startPosition, + this.scanner.currentPosition - 1, + Util.getLineNumber(this.scanner.startPosition, this.scanner.lineEnds, 0, this.scanner.linePtr)); + this.compilationUnit.recordStringLiteral(stringLiteral); + } else { + stringLiteral = this.createStringLiteral( + this.scanner.getCurrentTokenSourceString(), + this.scanner.startPosition, + this.scanner.currentPosition - 1, + 0); + } + pushOnExpressionStack(stringLiteral); + break; + case TokenNameRegExLiteral : + pushOnExpressionStack( + new RegExLiteral( + this.scanner.getCurrentTokenSource(), + this.scanner.startPosition, + this.scanner.currentPosition - 1)); + break; + + case TokenNameStringLiteral : + if (this.recordStringLiterals && this.checkExternalizeStrings && !this.statementRecoveryActivated) { + stringLiteral = this.createStringLiteral( + this.scanner.getCurrentTokenSourceString(), + this.scanner.startPosition, + this.scanner.currentPosition - 1, + Util.getLineNumber(this.scanner.startPosition, this.scanner.lineEnds, 0, this.scanner.linePtr)); + this.compilationUnit.recordStringLiteral(stringLiteral); + } else { + stringLiteral = this.createStringLiteral( + this.scanner.getCurrentTokenSourceString(), + this.scanner.startPosition, + this.scanner.currentPosition - 1, + 0); + } + pushOnExpressionStack(stringLiteral); + break; + case TokenNamefalse : + pushOnExpressionStack( + new FalseLiteral(this.scanner.startPosition, this.scanner.currentPosition - 1)); + break; + case TokenNametrue : + pushOnExpressionStack( + new TrueLiteral(this.scanner.startPosition, this.scanner.currentPosition - 1)); + break; + case TokenNamenull : + pushOnExpressionStack( + new NullLiteral(this.scanner.startPosition, this.scanner.currentPosition - 1)); + break; + case TokenNameundefined : + pushOnExpressionStack( + new UndefinedLiteral(this.scanner.startPosition, this.scanner.currentPosition - 1)); + break; + //============================ + case TokenNamesuper : + case TokenNamethis : + this.endPosition = this.scanner.currentPosition - 1; + pushOnIntStack(this.scanner.startPosition); + break; +// case TokenNameassert : + case TokenNameimport : + case TokenNamepackage : + case TokenNamethrow : + case TokenNamedo : + case TokenNameif : + case TokenNamefor : + case TokenNameswitch : + case TokenNametry : + case TokenNamewhile : + case TokenNamebreak : + case TokenNamecontinue : + case TokenNamereturn : + case TokenNamecase : + case TokenNamedebugger : + case TokenNameexport : + case TokenNamefunction : + case TokenNamevar : +// case TokenNamein : +// case TokenNameinfinity : + case TokenNamewith : + pushOnIntStack(this.scanner.startPosition); + break; + case TokenNamenew : + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=40954 + resetModifiers(); + pushOnIntStack(this.scanner.startPosition); + break; + case TokenNameclass : + pushOnIntStack(this.scanner.currentPosition - 1); + pushOnIntStack(this.scanner.startPosition); + break; + case TokenNameenum : + pushOnIntStack(this.scanner.currentPosition - 1); + pushOnIntStack(this.scanner.startPosition); + break; + case TokenNamedefault : + pushOnIntStack(this.scanner.startPosition); + pushOnIntStack(this.scanner.currentPosition - 1); + break; + //let extra semantic action decide when to push + case TokenNameRBRACKET : + this.endPosition = this.scanner.startPosition; + this.endStatementPosition = this.scanner.currentPosition - 1; + break; + case TokenNameLBRACKET : + this.endPosition = this.scanner.startPosition; + break; + case TokenNameLBRACE : + this.endStatementPosition = this.scanner.currentPosition - 1; + case TokenNamePLUS : + case TokenNameMINUS : + case TokenNameNOT : + case TokenNameTWIDDLE : + case TokenNamedelete : + case TokenNamevoid : + case TokenNametypeof : + this.endPosition = this.scanner.startPosition; + break; + case TokenNamePLUS_PLUS : + case TokenNameMINUS_MINUS : + this.endPosition = this.scanner.startPosition; + this.endStatementPosition = this.scanner.currentPosition - 1; + break; + case TokenNameSEMICOLON : + if (this.insertedSemicolonPosition>0) + { + if (this.insertedSemicolonPosition>=this.scanner.source.length) + this.insertedSemicolonPosition--; + this.endStatementPosition = this.insertedSemicolonPosition; + this.endPosition = this.insertedSemicolonPosition; + this.insertedSemicolonPosition=-1; + this.problemReporter().missingSemiColon(null, this.endPosition-1,this.endPosition); + break; + }// else fallthru + case TokenNameRBRACE: + this.endStatementPosition = this.scanner.currentPosition - 1; + this.endPosition = this.scanner.startPosition - 1; + //the item is not part of the potential future expression/statement + break; + case TokenNameRPAREN : + // in order to handle ( expression) ////// (cast)expression///// foo(x) + this.rParenPos = this.scanner.currentPosition - 1; // position of the end of right parenthesis (in case of unicode \u0029) lex00101 + break; + case TokenNameLPAREN : + this.lParenPos = this.scanner.startPosition; + break; + case TokenNameQUESTION : + pushOnIntStack(this.scanner.startPosition); + pushOnIntStack(this.scanner.currentPosition - 1); + break; + case TokenNameLESS : + pushOnIntStack(this.scanner.startPosition); + break; +// case TokenNameELLIPSIS : +// pushOnIntStack(this.scanner.currentPosition - 1); +// break; + // case TokenNameCOMMA : + // case TokenNameCOLON : + // case TokenNameEQUAL : + // case TokenNameLBRACKET : + // case TokenNameDOT : + // case TokenNameERROR : + // case TokenNameEOF : + // case TokenNamecase : + // case TokenNamecatch : + // case TokenNameelse : + // case TokenNameextends : + // case TokenNamefinally : + // case TokenNameimplements : + // case TokenNamethrows : + // case TokenNameinstanceof : + // case TokenNameEQUAL_EQUAL : + // case TokenNameLESS_EQUAL : + // case TokenNameGREATER_EQUAL : + // case TokenNameNOT_EQUAL : + // case TokenNameLEFT_SHIFT : + // case TokenNameRIGHT_SHIFT : + // case TokenNameUNSIGNED_RIGHT_SHIFT : + // case TokenNamePLUS_EQUAL : + // case TokenNameMINUS_EQUAL : + // case TokenNameMULTIPLY_EQUAL : + // case TokenNameDIVIDE_EQUAL : + // case TokenNameAND_EQUAL : + // case TokenNameOR_EQUAL : + // case TokenNameXOR_EQUAL : + // case TokenNameREMAINDER_EQUAL : + // case TokenNameLEFT_SHIFT_EQUAL : + // case TokenNameRIGHT_SHIFT_EQUAL : + // case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : + // case TokenNameOR_OR : + // case TokenNameAND_AND : + // case TokenNameREMAINDER : + // case TokenNameXOR : + // case TokenNameAND : + // case TokenNameMULTIPLY : + // case TokenNameOR : + // case TokenNameDIVIDE : + // case TokenNameGREATER : + } +} +protected void consumeUnaryExpression(int op) { + // UnaryExpression ::= '+' PushPosition UnaryExpression + // UnaryExpression ::= '-' PushPosition UnaryExpression + // UnaryExpressionNotPlusMinus ::= '~' PushPosition UnaryExpression + // UnaryExpressionNotPlusMinus ::= '!' PushPosition UnaryExpression + + //optimize the push/pop + + //handle manually the -2147483648 while it is not a real + //computation of an - and 2147483648 (notice that 2147483648 + //is Integer.MAX_VALUE+1.....) + //Same for -9223372036854775808L ............ + + //this.intStack have the position of the operator + + Expression r, exp = this.expressionStack[this.expressionPtr]; + if (op == MINUS) { + if ((exp instanceof IntLiteral) && (((IntLiteral) exp).mayRepresentMIN_VALUE())) { + r = this.expressionStack[this.expressionPtr] = new IntLiteralMinValue(); + } else { + r = this.expressionStack[this.expressionPtr] = new UnaryExpression(exp, op); + } + } else { + r = this.expressionStack[this.expressionPtr] = new UnaryExpression(exp, op); + } + r.sourceStart = this.intStack[this.intPtr--]; + r.sourceEnd = exp.sourceEnd; +} +protected void consumeUnaryExpression(int op, boolean post) { + // PreIncrementExpression ::= '++' PushPosition UnaryExpression + // PreDecrementExpression ::= '--' PushPosition UnaryExpression + + // ++ and -- operators + //optimize the push/pop + + //this.intStack has the position of the operator when prefix + + Expression leftHandSide = this.expressionStack[this.expressionPtr]; + if (leftHandSide instanceof Reference) { + // ++foo()++ is unvalid + if (post) { + this.expressionStack[this.expressionPtr] = + new PostfixExpression( + leftHandSide, + IntLiteral.getOne(), + op, + this.endStatementPosition); + } else { + this.expressionStack[this.expressionPtr] = + new PrefixExpression( + leftHandSide, + IntLiteral.getOne(), + op, + this.intStack[this.intPtr--]); + } + } else { + //the ++ or the -- is NOT taken into account if code gen proceeds + if (!post) { + this.intPtr--; + } + if(!this.statementRecoveryActivated) problemReporter().invalidUnaryExpression(leftHandSide); + } +} +protected void consumeVariableDeclarators() { + // VariableDeclarators ::= VariableDeclarators ',' VariableDeclarator + optimizedConcatNodeLists(); +} +protected void consumeVariableInitializers() { + // VariableInitializers ::= VariableInitializers ',' VariableInitializer + concatExpressionLists(); +} +/** + * Given the current comment stack, answer whether some comment is available in a certain exclusive range + * + * @param sourceStart int + * @param sourceEnd int + * @return boolean + */ +public boolean containsComment(int sourceStart, int sourceEnd) { + int iComment = this.scanner.commentPtr; + for (; iComment >= 0; iComment--) { + int commentStart = this.scanner.commentStarts[iComment]; + // ignore comments before start + if (commentStart < sourceStart) continue; + // ignore comments after end + if (commentStart > sourceEnd) continue; + return true; + } + return false; +} +public MethodDeclaration convertToMethodDeclaration(ConstructorDeclaration c, CompilationResult compilationResult) { + MethodDeclaration m = new MethodDeclaration(compilationResult); + m.sourceStart = c.sourceStart; + m.sourceEnd = c.sourceEnd; + m.bodyStart = c.bodyStart; + m.bodyEnd = c.bodyEnd; + m.declarationSourceEnd = c.declarationSourceEnd; + m.declarationSourceStart = c.declarationSourceStart; + m.setSelector(c.getName()); + m.statements = c.statements; + m.modifiers = c.modifiers; + m.arguments = c.arguments; + m.explicitDeclarations = c.explicitDeclarations; + m.returnType = null; + m.javadoc = c.javadoc; + return m; +} +protected TypeReference copyDims(TypeReference typeRef, int dim) { + return typeRef.copyDims(dim); +} +protected FieldDeclaration createFieldDeclaration(char[] fieldDeclarationName, int sourceStart, int sourceEnd) { + return new FieldDeclaration(fieldDeclarationName, sourceStart, sourceEnd); +} +protected JavadocParser createJavadocParser() { + return new JavadocParser(this); +} +protected LocalDeclaration createLocalDeclaration(char[] localDeclarationName, int sourceStart, int sourceEnd) { + return new LocalDeclaration(localDeclarationName, sourceStart, sourceEnd); +} +protected StringLiteral createStringLiteral(char[] token, int start, int end, int lineNumber) { + return new StringLiteral(token, start, end, lineNumber); +} + + protected RecoveredType currentRecoveryType() { + if(this.currentElement != null) { + if(this.currentElement instanceof RecoveredType) { + return (RecoveredType) this.currentElement; + } else { + return this.currentElement.enclosingType(); + } + } + return null; +} +public CompilationUnitDeclaration dietParse(ICompilationUnit sourceUnit, CompilationResult compilationResult) { + + CompilationUnitDeclaration parsedUnit; + boolean old = this.diet; + try { + this.diet = DO_DIET_PARSE; + parsedUnit = parse(sourceUnit, compilationResult); + } finally { + this.diet = old; + } + return parsedUnit; +} +protected void dispatchDeclarationInto(int length) { + /* they are length on this.astStack that should go into + methods fields constructors lists of the typeDecl + + Return if there is a constructor declaration in the methods declaration */ + + + // Looks for the size of each array . + + if (length == 0) + return; + int[] flag = new int[length + 1]; //plus one -- see + int size1 = 0, size2 = 0, size3 = 0; + boolean hasAbstractMethods = false; + for (int i = length - 1; i >= 0; i--) { + ASTNode astNode = this.astStack[this.astPtr--]; + if (astNode instanceof AbstractMethodDeclaration) { + //methods and constructors have been regrouped into one single list + flag[i] = 2; + size2++; + if (((AbstractMethodDeclaration) astNode).isAbstract()) { + hasAbstractMethods = true; + } + } else if (astNode instanceof TypeDeclaration) { + flag[i] = 3; + size3++; + } else { + //field + flag[i] = 1; + size1++; + } + } + + //arrays creation + TypeDeclaration typeDecl = (TypeDeclaration) this.astStack[this.astPtr]; + if (size1 != 0) { + typeDecl.fields = new FieldDeclaration[size1]; + } + if (size2 != 0) { + typeDecl.methods = new AbstractMethodDeclaration[size2]; + if (hasAbstractMethods) typeDecl.bits |= ASTNode.HasAbstractMethods; + } + if (size3 != 0) { + typeDecl.memberTypes = new TypeDeclaration[size3]; + } + + //arrays fill up + size1 = size2 = size3 = 0; + int flagI = flag[0], start = 0; + int length2; + for (int end = 0; end <= length; end++) // the plus one allows to + { + if (flagI != flag[end]) //treat the last element as a ended flag..... + { //array copy + switch (flagI) { + case 1 : + size1 += (length2 = end - start); + System.arraycopy( + this.astStack, + this.astPtr + start + 1, + typeDecl.fields, + size1 - length2, + length2); + break; + case 2 : + size2 += (length2 = end - start); + System.arraycopy( + this.astStack, + this.astPtr + start + 1, + typeDecl.methods, + size2 - length2, + length2); + break; + case 3 : + size3 += (length2 = end - start); + System.arraycopy( + this.astStack, + this.astPtr + start + 1, + typeDecl.memberTypes, + size3 - length2, + length2); + break; + } + flagI = flag[start = end]; + } + } + + if (typeDecl.memberTypes != null) { + for (int i = typeDecl.memberTypes.length - 1; i >= 0; i--) { + typeDecl.memberTypes[i].enclosingType = typeDecl; + } + } +} +protected void dispatchDeclarationIntoEnumDeclaration(int length) { + + if (length == 0) + return; + int[] flag = new int[length + 1]; //plus one -- see + int size1 = 0, size2 = 0, size3 = 0; + TypeDeclaration enumDeclaration = (TypeDeclaration) this.astStack[this.astPtr - length]; + boolean hasAbstractMethods = false; + for (int i = length - 1; i >= 0; i--) { + ASTNode astNode = this.astStack[this.astPtr--]; + if (astNode instanceof AbstractMethodDeclaration) { + //methods and constructors have been regrouped into one single list + flag[i] = 2; + size2++; + if (((AbstractMethodDeclaration) astNode).isAbstract()) { + hasAbstractMethods = true; + } + } else if (astNode instanceof TypeDeclaration) { + flag[i] = 3; + size3++; + } else if (astNode instanceof FieldDeclaration) { + flag[i] = 1; + size1++; +// if(astNode instanceof EnumConstant) { +// EnumConstant constant = (EnumConstant) astNode; +// ((AllocationExpression)constant.initialization).type = new SingleTypeReference(enumDeclaration.name, +// (((long) enumDeclaration.sourceStart) << 32) + enumDeclaration.sourceEnd); +// } + } + } + + //arrays creation + if (size1 != 0) { + enumDeclaration.fields = new FieldDeclaration[size1]; + } + if (size2 != 0) { + enumDeclaration.methods = new AbstractMethodDeclaration[size2]; + if (hasAbstractMethods) enumDeclaration.bits |= ASTNode.HasAbstractMethods; + } + if (size3 != 0) { + enumDeclaration.memberTypes = new TypeDeclaration[size3]; + } + + //arrays fill up + size1 = size2 = size3 = 0; + int flagI = flag[0], start = 0; + int length2; + for (int end = 0; end <= length; end++) // the plus one allows to + { + if (flagI != flag[end]) //treat the last element as a ended flag..... + { //array copy + switch (flagI) { + case 1 : + size1 += (length2 = end - start); + System.arraycopy( + this.astStack, + this.astPtr + start + 1, + enumDeclaration.fields, + size1 - length2, + length2); + break; + case 2 : + size2 += (length2 = end - start); + System.arraycopy( + this.astStack, + this.astPtr + start + 1, + enumDeclaration.methods, + size2 - length2, + length2); + break; + case 3 : + size3 += (length2 = end - start); + System.arraycopy( + this.astStack, + this.astPtr + start + 1, + enumDeclaration.memberTypes, + size3 - length2, + length2); + break; + } + flagI = flag[start = end]; + } + } + + if (enumDeclaration.memberTypes != null) { + for (int i = enumDeclaration.memberTypes.length - 1; i >= 0; i--) { + enumDeclaration.memberTypes[i].enclosingType = enumDeclaration; + } + }} +protected CompilationUnitDeclaration endParse(int act) { + + this.lastAct = act; + + if(this.statementRecoveryActivated ) { + RecoveredElement recoveredElement = this.buildInitialRecoveryState(); + recoveredElement.topElement().updateParseTree(); + if(this.hasError) this.resetStacks(); + } else if (this.currentElement != null){ + if (VERBOSE_RECOVERY){ + System.out.print(Messages.parser_syntaxRecovery); + System.out.println("--------------------------"); //$NON-NLS-1$ + System.out.println(this.compilationUnit); + System.out.println("----------------------------------"); //$NON-NLS-1$ + } + recoverAST(this.currentElement); + this.currentElement.topElement().updateParseTree(); + } else { + if (this.diet & VERBOSE_RECOVERY){ + System.out.print(Messages.parser_regularParse); + System.out.println("--------------------------"); //$NON-NLS-1$ + System.out.println(this.compilationUnit); + System.out.println("----------------------------------"); //$NON-NLS-1$ + } + } + persistLineSeparatorPositions(); + for (int i = 0; i < this.scanner.foundTaskCount; i++){ + if(!this.statementRecoveryActivated) problemReporter().task( + new String(this.scanner.foundTaskTags[i]), + new String(this.scanner.foundTaskMessages[i]), + this.scanner.foundTaskPriorities[i] == null ? null : new String(this.scanner.foundTaskPriorities[i]), + this.scanner.foundTaskPositions[i][0], + this.scanner.foundTaskPositions[i][1]); + } + if (this.compilationUnit.statements==null) + this.compilationUnit.statements=new ProgramElement[0]; + return this.compilationUnit; +} +/* + * Flush comments defined prior to a given positions. + * + * Note: comments are stacked in syntactical order + * + * Either answer given , or the end position of a comment line + * immediately following the (same line) + * + * e.g. + * void foo(){ + * } // end of method foo + */ + +public int flushCommentsDefinedPriorTo(int position) { + + int lastCommentIndex = this.scanner.commentPtr; + if (lastCommentIndex < 0) return position; // no comment + + // compute the index of the first obsolete comment + int index = lastCommentIndex; + int validCount = 0; + while (index >= 0){ + int commentEnd = this.scanner.commentStops[index]; + if (commentEnd < 0) commentEnd = -commentEnd; // negative end position for non-javadoc comments + if (commentEnd <= position){ + break; + } + index--; + validCount++; + } + // if the source at is immediately followed by a line comment, then + // flush this comment and shift to the comment end. + if (validCount > 0){ + int immediateCommentEnd = -this.scanner.commentStops[index+1]; //non-javadoc comment end positions are negative + if (immediateCommentEnd > 0){ // only tolerating non-javadoc comments + // is there any line break until the end of the immediate comment ? (thus only tolerating line comment) + immediateCommentEnd--; // comment end in one char too far + if (Util.getLineNumber(position, this.scanner.lineEnds, 0, this.scanner.linePtr) + == Util.getLineNumber(immediateCommentEnd, this.scanner.lineEnds, 0, this.scanner.linePtr)){ + position = immediateCommentEnd; + validCount--; // flush this comment + index++; + } + } + } + + if (index < 0) return position; // no obsolete comment + + switch (validCount) { + case 0: + // do nothing + break; + // move valid comment infos, overriding obsolete comment infos + case 2: + this.scanner.commentStarts[0] = this.scanner.commentStarts[index+1]; + this.scanner.commentStops[0] = this.scanner.commentStops[index+1]; + this.scanner.commentTagStarts[0] = this.scanner.commentTagStarts[index+1]; + this.scanner.commentStarts[1] = this.scanner.commentStarts[index+2]; + this.scanner.commentStops[1] = this.scanner.commentStops[index+2]; + this.scanner.commentTagStarts[1] = this.scanner.commentTagStarts[index+2]; + break; + case 1: + this.scanner.commentStarts[0] = this.scanner.commentStarts[index+1]; + this.scanner.commentStops[0] = this.scanner.commentStops[index+1]; + this.scanner.commentTagStarts[0] = this.scanner.commentTagStarts[index+1]; + break; + default: + System.arraycopy(this.scanner.commentStarts, index + 1, this.scanner.commentStarts, 0, validCount); + System.arraycopy(this.scanner.commentStops, index + 1, this.scanner.commentStops, 0, validCount); + System.arraycopy(this.scanner.commentTagStarts, index + 1, this.scanner.commentTagStarts, 0, validCount); + } + this.scanner.commentPtr = validCount - 1; + return position; +} +public int getFirstToken() { + // the first token is a virtual token that + // allows the parser to parse several goals + // even if they aren't LALR(1).... + // Goal ::= '++' JavaScriptUnit + // Goal ::= '--' MethodBody + // Goal ::= '==' ConstructorBody + // -- Initializer + // Goal ::= '>>' StaticInitializer + // Goal ::= '>>' Block + // -- error recovery + // Goal ::= '>>>' Headers + // Goal ::= '*' BlockStatements + // Goal ::= '*' MethodPushModifiersHeader + // -- JDOM + // Goal ::= '&&' FieldDeclaration + // Goal ::= '||' ImportDeclaration + // Goal ::= '?' PackageDeclaration + // Goal ::= '+' TypeDeclaration + // Goal ::= '/' GenericMethodDeclaration + // Goal ::= '&' ClassBodyDeclaration + // -- code snippet + // Goal ::= '%' Expression + // -- completion parser + // Goal ::= '!' ConstructorBlockStatementsopt + // Goal ::= '~' BlockStatementsopt + + return this.firstToken; +} +/* + * Answer back an array of sourceStart/sourceEnd positions of the available JavaDoc comments. + * The array is a flattened structure: 2*n entries with consecutives start and end positions. + * + * If no JavaDoc is available, then null is answered instead of an empty array. + * + * e.g. { 10, 20, 25, 45 } --> javadoc1 from 10 to 20, javadoc2 from 25 to 45 + */ +public int[] getJavaDocPositions() { + + int javadocCount = 0; + for (int i = 0, max = this.scanner.commentPtr; i <= max; i++){ + // javadoc only (non javadoc comment have negative end positions.) + if (this.scanner.commentStops[i] > 0){ + javadocCount++; + } + } + if (javadocCount == 0) return null; + + int[] positions = new int[2*javadocCount]; + int index = 0; + for (int i = 0, max = this.scanner.commentPtr; i <= max; i++){ + // javadoc only (non javadoc comment have negative end positions.) + if (this.scanner.commentStops[i] > 0){ + positions[index++] = this.scanner.commentStarts[i]; + positions[index++] = this.scanner.commentStops[i]-1; //stop is one over + } + } + return positions; +} + public void getMethodBodies(CompilationUnitDeclaration unit) { + //fill the methods bodies in order for the code to be generated + + if (unit == null) return; + + if (unit.ignoreMethodBodies) { + unit.ignoreFurtherInvestigation = true; + return; + // if initial diet parse did not work, no need to dig into method bodies. + } + + if ((unit.bits & ASTNode.HasAllMethodBodies) != 0) + return; //work already done ... + + // save existing values to restore them at the end of the parsing process + // see bug 47079 for more details + int[] oldLineEnds = this.scanner.lineEnds; + int oldLinePtr = this.scanner.linePtr; + + //real parse of the method.... + CompilationResult compilationResult = unit.compilationResult; + char[] contents = compilationResult.compilationUnit.getContents(); + this.scanner.setSource(contents, compilationResult); + + if (this.javadocParser != null && this.javadocParser.checkDocComment) { + this.javadocParser.scanner.setSource(contents); + } + if (unit.types != null) { + for (int i = unit.types.length; --i >= 0;) + unit.types[i].parseMethod(this, unit); + } + + // tag unit has having read bodies + unit.bits |= ASTNode.HasAllMethodBodies; + + // this is done to prevent any side effects on the compilation unit result + // line separator positions array. + this.scanner.lineEnds = oldLineEnds; + this.scanner.linePtr = oldLinePtr; + } +protected char getNextCharacter(char[] comment, int[] index) { + char nextCharacter = comment[index[0]++]; + switch(nextCharacter) { + case '\\' : + int c1, c2, c3, c4; + index[0]++; + while (comment[index[0]] == 'u') index[0]++; + if (!(((c1 = ScannerHelper.getNumericValue(comment[index[0]++])) > 15 + || c1 < 0) + || ((c2 = ScannerHelper.getNumericValue(comment[index[0]++])) > 15 || c2 < 0) + || ((c3 = ScannerHelper.getNumericValue(comment[index[0]++])) > 15 || c3 < 0) + || ((c4 = ScannerHelper.getNumericValue(comment[index[0]++])) > 15 || c4 < 0))) { + nextCharacter = (char) (((c1 * 16 + c2) * 16 + c3) * 16 + c4); + } + break; + } + return nextCharacter; +} +protected Expression getTypeReference(Expression exp) { + + exp.bits &= ~ASTNode.RestrictiveFlagMASK; + exp.bits |= Binding.TYPE; + return exp; +} +protected TypeReference getTypeReference(int dim) { + /* build a Reference on a variable that may be qualified or not + This variable is a type reference and dim will be its dimensions*/ + + TypeReference ref; + int length = this.identifierLengthStack[this.identifierLengthPtr--]; + if (length < 0) { //flag for precompiled type reference on base types + ref = TypeReference.baseTypeReference(-length, dim); + ref.sourceStart = this.intStack[this.intPtr--]; + if (dim == 0) { + ref.sourceEnd = this.intStack[this.intPtr--]; + } else { + this.intPtr--; + ref.sourceEnd = this.endPosition; + } + } else { + int numberOfIdentifiers = this.genericsIdentifiersLengthStack[this.genericsIdentifiersLengthPtr--]; + if (length != numberOfIdentifiers || this.genericsLengthStack[this.genericsLengthPtr] != 0) { + ref = null; + } else if (length == 1) { + // single variable reference + this.genericsLengthPtr--; // pop the 0 + if (dim == 0) { + ref = + new SingleTypeReference( + this.identifierStack[this.identifierPtr], + this.identifierPositionStack[this.identifierPtr--]); + } else { + ref = + new ArrayTypeReference( + this.identifierStack[this.identifierPtr], + dim, + this.identifierPositionStack[this.identifierPtr--]); + ref.sourceEnd = this.endPosition; + } + } else { + this.genericsLengthPtr--; + //Qualified variable reference + char[][] tokens = new char[length][]; + this.identifierPtr -= length; + long[] positions = new long[length]; + System.arraycopy(this.identifierStack, this.identifierPtr + 1, tokens, 0, length); + System.arraycopy( + this.identifierPositionStack, + this.identifierPtr + 1, + positions, + 0, + length); + if (dim == 0) { + ref = new QualifiedTypeReference(tokens, positions); + } else { + ref = new ArrayQualifiedTypeReference(tokens, dim, positions); + ref.sourceEnd = this.endPosition; + } + } + } + return ref; +} +protected NameReference getUnspecifiedReference() { + /* build a (unspecified) NameReference which may be qualified*/ + + int length; + NameReference ref; + if ((length = this.identifierLengthStack[this.identifierLengthPtr--]) == 1) + // single variable reference + ref = + new SingleNameReference( + this.identifierStack[this.identifierPtr], + this.identifierPositionStack[this.identifierPtr--]); + else + //Qualified variable reference + { + char[][] tokens = new char[length][]; + this.identifierPtr -= length; + System.arraycopy(this.identifierStack, this.identifierPtr + 1, tokens, 0, length); + long[] positions = new long[length]; + System.arraycopy(this.identifierPositionStack, this.identifierPtr + 1, positions, 0, length); + ref = + new QualifiedNameReference(tokens, + positions, + (int) (this.identifierPositionStack[this.identifierPtr + 1] >> 32), // sourceStart + (int) this.identifierPositionStack[this.identifierPtr + length]); // sourceEnd + } + return ref; +} +protected NameReference getUnspecifiedReferenceOptimized() { + /* build a (unspecified) NameReference which may be qualified + The optimization occurs for qualified reference while we are + certain in this case the last item of the qualified name is + a field access. This optimization is IMPORTANT while it results + that when a NameReference is build, the type checker should always + look for that it is not a type reference */ + + int length; + NameReference ref; + if ((length = this.identifierLengthStack[this.identifierLengthPtr--]) == 1) { + // single variable reference + ref = + new SingleNameReference( + this.identifierStack[this.identifierPtr], + this.identifierPositionStack[this.identifierPtr--]); + ref.bits &= ~ASTNode.RestrictiveFlagMASK; + ref.bits |= Binding.LOCAL | Binding.FIELD; + return ref; + } + + //Qualified-variable-reference + //In fact it is variable-reference DOT field-ref , but it would result in a type + //conflict tha can be only reduce by making a superclass (or inetrface ) between + //nameReference and FiledReference or putting FieldReference under NameReference + //or else..........This optimisation is not really relevant so just leave as it is + + char[][] tokens = new char[length][]; + this.identifierPtr -= length; + System.arraycopy(this.identifierStack, this.identifierPtr + 1, tokens, 0, length); + long[] positions = new long[length]; + System.arraycopy(this.identifierPositionStack, this.identifierPtr + 1, positions, 0, length); + ref = new QualifiedNameReference( + tokens, + positions, + (int) (this.identifierPositionStack[this.identifierPtr + 1] >> 32), // sourceStart + (int) this.identifierPositionStack[this.identifierPtr + length]); // sourceEnd + ref.bits &= ~ASTNode.RestrictiveFlagMASK; + ref.bits |= Binding.LOCAL | Binding.FIELD; + return ref; +} +public void goForBlockStatementsopt() { + //tells the scanner to go for block statements opt parsing + + this.firstToken = TokenNameTWIDDLE; + this.scanner.recordLineSeparator = false; +} +public void goForProgramElements() { + //tells the scanner to go for block statements opt parsing + + this.firstToken = TokenNamePLUS; + this.scanner.recordLineSeparator = true; +} + +public void goForBlockStatementsOrCatchHeader() { + //tells the scanner to go for block statements or method headers parsing + + this.firstToken = TokenNameMULTIPLY; + this.scanner.recordLineSeparator = false; +} +public void goForClassBodyDeclarations() { + //tells the scanner to go for any body declarations parsing + +// this.firstToken = TokenNameAND; + this.firstToken = TokenNamePLUS; + this.scanner.recordLineSeparator = true; +} +public void goForCompilationUnit(){ + //tells the scanner to go for compilation unit parsing + + this.firstToken = TokenNamePLUS_PLUS ; + this.scanner.foundTaskCount = 0; + this.scanner.recordLineSeparator = true; +} +public void goForExpression() { + //tells the scanner to go for an expression parsing + + this.firstToken = TokenNameREMAINDER; + this.scanner.recordLineSeparator = true; // recovery goals must record line separators +} +public void goForFieldDeclaration(){ + //tells the scanner to go for field declaration parsing + + this.firstToken = TokenNameAND_AND ; + this.scanner.recordLineSeparator = true; +} +public void goForHeaders(){ + //tells the scanner to go for headers only parsing +// RecoveredType currentType = this.currentRecoveryType(); +// if(currentType != null && currentType.insideEnumConstantPart) { +// this.firstToken = TokenNameNOT; +// } else { + this.firstToken = TokenNameUNSIGNED_RIGHT_SHIFT; +// } + this.scanner.recordLineSeparator = true; // recovery goals must record line separators +} +public void goForInitializer(){ + //tells the scanner to go for initializer parsing + + this.firstToken = TokenNameRIGHT_SHIFT ; + this.scanner.recordLineSeparator = false; +} +public void goForMemberValue() { + //tells the scanner to go for a member value parsing + + this.firstToken = TokenNameOR_OR; + this.scanner.recordLineSeparator = true; // recovery goals must record line separators +} +public void goForMethodBody(){ + //tells the scanner to go for method body parsing + + this.firstToken = TokenNameMINUS_MINUS ; + this.scanner.recordLineSeparator = false; +} +public void goForTypeDeclaration() { + //tells the scanner to go for type (interface or class) declaration parsing + + this.firstToken = TokenNamePLUS; + this.scanner.recordLineSeparator = true; +} +protected void ignoreExpressionAssignment() { + // Assignment ::= InvalidArrayInitializerAssignement + // encoded operator would be: this.intStack[this.intPtr] + this.intPtr--; + ArrayInitializer arrayInitializer = (ArrayInitializer) this.expressionStack[this.expressionPtr--]; + this.expressionLengthPtr -- ; +} +public void initialize() { + this.initialize(false); +} +public void initialize(boolean initializeNLS) { + //positionning the parser for a new compilation unit + //avoiding stack reallocation and all that.... + this.astPtr = -1; + this.astLengthPtr = -1; + this.expressionPtr = -1; + this.expressionLengthPtr = -1; + this.identifierPtr = -1; + this.identifierLengthPtr = -1; + this.intPtr = -1; + this.nestedMethod[this.nestedType = 0] = 0; // need to reset for further reuse + this.variablesCounter[this.nestedType] = 0; + this.dimensions = 0 ; + this.realBlockPtr = 0; + this.compilationUnit = null; + this.referenceContext = null; + this.endStatementPosition = 0; + + //remove objects from stack too, while the same parser/compiler couple is + //re-used between two compilations .... + + int astLength = this.astStack.length; + if (this.noAstNodes.length < astLength){ + this.noAstNodes = new ASTNode[astLength]; + //System.out.println("Resized AST stacks : "+ astLength); + + } + System.arraycopy(this.noAstNodes, 0, this.astStack, 0, astLength); + + int expressionLength = this.expressionStack.length; + if (this.noExpressions.length < expressionLength){ + this.noExpressions = new Expression[expressionLength]; + //System.out.println("Resized EXPR stacks : "+ expressionLength); + } + System.arraycopy(this.noExpressions, 0, this.expressionStack, 0, expressionLength); + + // reset this.scanner state + this.scanner.commentPtr = -1; + this.scanner.foundTaskCount = 0; + this.scanner.eofPosition = Integer.MAX_VALUE; + this.recordStringLiterals = true; + final boolean checkNLS = this.options.getSeverity(CompilerOptions.NonExternalizedString) != ProblemSeverities.Ignore; + this.checkExternalizeStrings = checkNLS; + this.scanner.checkNonExternalizedStringLiterals = initializeNLS && checkNLS; + + resetModifiers(); + + // recovery + this.lastCheckPoint = -1; + this.currentElement = null; + this.restartRecovery = false; + this.hasReportedError = false; + this.recoveredStaticInitializerStart = 0; + this.lastIgnoredToken = -1; + this.lastErrorEndPosition = -1; + this.lastErrorEndPositionBeforeRecovery = -1; + this.lastJavadocEnd = -1; + this.listLength = 0; + this.listTypeParameterLength = 0; + + this.rBraceStart = 0; + this.rBraceEnd = 0; + this.rBraceSuccessorStart = 0; + + this.genericsIdentifiersLengthPtr = -1; + this.genericsLengthPtr = -1; + this.genericsPtr = -1; + + this.errorAction= new HashSet(); + +} +public void initializeScanner(){ + this.scanner = new Scanner( + false /*comment*/, + false /*whitespace*/, + false, /* will be set in initialize(boolean) */ + this.options.sourceLevel /*sourceLevel*/, + this.options.complianceLevel /*complianceLevel*/, + this.options.taskTags/*taskTags*/, + this.options.taskPriorites/*taskPriorities*/, + this.options.isTaskCaseSensitive/*taskCaseSensitive*/); +} +public void jumpOverMethodBody() { + //on diet parsing.....do not buffer method statements + + //the scanner.diet is reinitialized to false + //automatically by the scanner once it has jumped over + //the statements + + if (this.diet && (this.dietInt == 0)) + this.scanner.diet = true; +} +private void jumpOverType(){ + if (this.recoveredTypes != null && this.nextTypeStart > -1 && this.nextTypeStart < this.scanner.currentPosition) { + + if (DEBUG_AUTOMATON) { + System.out.println("Jump -"); //$NON-NLS-1$ + } + + TypeDeclaration typeDeclaration = this.recoveredTypes[this.recoveredTypePtr]; + boolean isAnonymous = typeDeclaration.allocation != null; + + int end = this.scanner.eofPosition; + this.scanner.resetTo(typeDeclaration.declarationSourceEnd + 1, end - 1); + if(!isAnonymous) { + ((RecoveryScanner)this.scanner).setPendingTokens(new int[]{TokenNameSEMICOLON, TokenNamebreak}); + } else { + ((RecoveryScanner)this.scanner).setPendingTokens(new int[]{TokenNameIdentifier, TokenNameEQUAL, TokenNameIdentifier}); + } + + this.pendingRecoveredType = typeDeclaration; + + try { + this.currentToken = this.scanner.getNextToken(); + } catch(InvalidInputException e){ + // it's impossible because we added pending tokens before + } + + if(++this.recoveredTypePtr < this.recoveredTypes.length) { + TypeDeclaration nextTypeDeclaration = this.recoveredTypes[this.recoveredTypePtr]; + this.nextTypeStart = + nextTypeDeclaration.allocation == null + ? nextTypeDeclaration.declarationSourceStart + : nextTypeDeclaration.allocation.sourceStart; + } else { + this.nextTypeStart = Integer.MAX_VALUE; + } + } +} +protected void markEnclosingMemberWithLocalType() { + if (this.currentElement != null) return; // this is already done in the recovery code + for (int i = this.astPtr; i >= 0; i--) { + ASTNode node = this.astStack[i]; + if (node instanceof AbstractMethodDeclaration + || node instanceof FieldDeclaration + || (node instanceof TypeDeclaration // mark type for now: all initializers will be marked when added to this type + // and enclosing type must not be closed (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=147485) + && ((TypeDeclaration) node).declarationSourceEnd == 0)) { + node.bits |= ASTNode.HasLocalType; + return; + } + } + // default to reference context (case of parse method body) + if (this.referenceContext instanceof AbstractMethodDeclaration + || this.referenceContext instanceof TypeDeclaration) { + ((ASTNode)this.referenceContext).bits |= ASTNode.HasLocalType; + } +} +protected void markInitializersWithLocalType(TypeDeclaration type) { + if (type.fields == null || (type.bits & ASTNode.HasLocalType) == 0) return; + for (int i = 0, length = type.fields.length; i < length; i++) { + FieldDeclaration field = type.fields[i]; + if (field instanceof Initializer) { + field.bits |= ASTNode.HasLocalType; + } + } +} + +/* + * Move checkpoint location (current implementation is moving it by one token) + * + * Answers true if successfully moved checkpoint (in other words, it did not attempt to move it + * beyond end of file). + */ +protected boolean moveRecoveryCheckpoint() { + + int pos = this.lastCheckPoint; + /* reset this.scanner, and move checkpoint by one token */ + this.scanner.startPosition = pos; + this.scanner.currentPosition = pos; + this.scanner.currentToken=this.scanner.currentNonWhitespaceToken=TokenNameUNKNOWN; + this.scanner.diet = false; // quit jumping over method bodies + + /* if about to restart, then no need to shift token */ + if (this.restartRecovery){ + this.lastIgnoredToken = -1; + this.scanner.insideRecovery = true; + return true; + } + + /* protect against shifting on an invalid token */ + this.lastIgnoredToken = this.nextIgnoredToken; + this.nextIgnoredToken = -1; + do { + try { + this.nextIgnoredToken = this.scanner.getNextToken(); + if(this.scanner.currentPosition == this.scanner.startPosition){ + this.scanner.currentPosition++; // on fake completion identifier + this.nextIgnoredToken = -1; + } + + } catch(InvalidInputException e){ + pos = this.scanner.currentPosition; + } + } while (this.nextIgnoredToken < 0); + + if (this.nextIgnoredToken == TokenNameEOF) { // no more recovery after this point + if (this.currentToken == TokenNameEOF) { // already tried one iteration on EOF + return false; + } + } + this.lastCheckPoint = this.scanner.currentPosition; + + /* reset this.scanner again to previous checkpoint location*/ + this.scanner.startPosition = pos; + this.scanner.currentPosition = pos; + this.scanner.currentToken=TokenNameUNKNOWN; + this.scanner.commentPtr = -1; + this.scanner.foundTaskCount = 0; + return true; + +/* + The following implementation moves the checkpoint location by one line: + + int pos = this.lastCheckPoint; + // reset this.scanner, and move checkpoint by one token + this.scanner.startPosition = pos; + this.scanner.currentPosition = pos; + this.scanner.diet = false; // quit jumping over method bodies + + // if about to restart, then no need to shift token + if (this.restartRecovery){ + this.lastIgnoredToken = -1; + return true; + } + + // protect against shifting on an invalid token + this.lastIgnoredToken = this.nextIgnoredToken; + this.nextIgnoredToken = -1; + + boolean wasTokenizingWhiteSpace = this.scanner.tokenizeWhiteSpace; + this.scanner.tokenizeWhiteSpace = true; + checkpointMove: + do { + try { + this.nextIgnoredToken = this.scanner.getNextToken(); + switch(this.nextIgnoredToken){ + case Scanner.TokenNameWHITESPACE : + if(this.scanner.getLineNumber(this.scanner.startPosition) + == this.scanner.getLineNumber(this.scanner.currentPosition)){ + this.nextIgnoredToken = -1; + } + break; + case TokenNameSEMICOLON : + case TokenNameLBRACE : + case TokenNameRBRACE : + break; + case TokenNameIdentifier : + if(this.scanner.currentPosition == this.scanner.startPosition){ + this.scanner.currentPosition++; // on fake completion identifier + } + default: + this.nextIgnoredToken = -1; + break; + case TokenNameEOF : + break checkpointMove; + } + } catch(InvalidInputException e){ + pos = this.scanner.currentPosition; + } + } while (this.nextIgnoredToken < 0); + this.scanner.tokenizeWhiteSpace = wasTokenizingWhiteSpace; + + if (this.nextIgnoredToken == TokenNameEOF) { // no more recovery after this point + if (this.currentToken == TokenNameEOF) { // already tried one iteration on EOF + return false; + } + } + this.lastCheckPoint = this.scanner.currentPosition; + + // reset this.scanner again to previous checkpoint location + this.scanner.startPosition = pos; + this.scanner.currentPosition = pos; + this.scanner.commentPtr = -1; + + return true; +*/ +} +protected MessageSend newMessageSend() { + // '(' ArgumentListopt ')' + // the arguments are on the expression stack + + MessageSend m = new MessageSend(); + int length; + if ((length = this.expressionLengthStack[this.expressionLengthPtr--]) != 0) { + this.expressionPtr -= length; + System.arraycopy( + this.expressionStack, + this.expressionPtr + 1, + m.arguments = new Expression[length], + 0, + length); + } + return m; +} +protected void optimizedConcatNodeLists() { + /*back from a recursive loop. Virtualy group the + astNode into an array using this.astLengthStack*/ + + /* + * This is a case where you have two sublists into the this.astStack that you want + * to merge in one list. There is no action required on the this.astStack. The only + * thing you need to do is merge the two lengths specified on the astStackLength. + * The top two length are for example: + * ... p n + * and you want to result in a list like: + * ... n+p + * This means that the p could be equals to 0 in case there is no astNode pushed + * on the this.astStack. + * Look at the InterfaceMemberDeclarations for an example. + * This case optimizes the fact that p == 1. + */ + + this.astLengthStack[--this.astLengthPtr]++; +} + +protected boolean isErrorState(int act) { + int stackTop=this.stateStackTop; + int [] tempStack=new int[this.stack.length+2]; + System.arraycopy(this.stack, 0, tempStack, 0, this.stack.length); + boolean first=true; + int currentAction = act; + ProcessTerminals : for (;;) { + int stackLength = tempStack.length; + if (!first) + { + if (++stackTop >= stackLength) { + System.arraycopy( + tempStack, 0, + tempStack = new int[stackLength + StackIncrement], 0, + stackLength); + } + tempStack[stackTop] = currentAction; + } + first=false; + currentAction = tAction(currentAction, this.currentToken); + if (currentAction == ERROR_ACTION) { + return true; + } + if (currentAction <= NUM_RULES) { + stackTop--; + + } else if (currentAction > ERROR_ACTION) { /* shift-reduce */ + if (DEBUG) System.out.println("<>shift-reduce Next Token: "+scanner.dumpCurrent()); +// } catch(InvalidInputException e){ +// if (!this.hasReportedError){ +// this.problemReporter().scannerError(this, e.getMessage()); +// this.hasReportedError = true; +// } +// this.lastCheckPoint = this.scanner.currentPosition; +// this.restartRecovery = true; +// } +// if(this.statementRecoveryActivated) { +// jumpOverTypeAfterReduce = true; +// } +// act -= ERROR_ACTION; + + } else { + if (currentAction < ACCEPT_ACTION) { /* shift */ + if (DEBUG) System.out.println("<>shift next Token: "+scanner.dumpCurrent()); +// } catch(InvalidInputException e){ +// if (!this.hasReportedError){ +// this.problemReporter().scannerError(this, e.getMessage()); +// this.hasReportedError = true; +// } +// this.lastCheckPoint = this.scanner.currentPosition; +// this.restartRecovery = true; +// } +// if(this.statementRecoveryActivated) { +// this.jumpOverType(); +// } +// continue ProcessTerminals; + } + break ProcessTerminals; + } + + // ProcessNonTerminals : + do { /* reduce */ + stackTop -= (rhs[currentAction] - 1); + currentAction = ntAction(tempStack[stackTop], lhs[currentAction]); + } while (currentAction <= NUM_RULES); + } +return false; +} + + +/*main loop of the automat +When a rule is reduced, the method consumeRule(int) is called with the number +of the consumed rule. When a terminal is consumed, the method consumeToken(int) is +called in order to remember (when needed) the consumed token */ +// (int)asr[asi(act)] +// name[symbol_index[currentKind]] +protected void parse() { + if (DEBUG) System.out.println("-- ENTER INSIDE PARSE METHOD --"); //$NON-NLS-1$ + + if (DEBUG_AUTOMATON) { + System.out.println("- Start --------------------------------"); //$NON-NLS-1$ + } + + boolean isDietParse = this.diet; + int oldFirstToken = getFirstToken(); + this.hasError = false; + + this.hasReportedError = false; + boolean insertedSemicolon = false; + int prevAct = START_STATE, + prevToken = getFirstToken(), + prevPos = scanner.startPosition; + + int act = START_STATE; + this.stateStackTop = -1; + this.currentToken = getFirstToken(); + ProcessTerminals : for (;;) { + int stackLength = this.stack.length; + if (++this.stateStackTop >= stackLength) { + System.arraycopy( + this.stack, 0, + this.stack = new int[stackLength + StackIncrement], 0, + stackLength); + } + this.stack[this.stateStackTop] = act; + + if (DEBUG) + System.out.println("action="+act+ ((term_check[base_action[act]+this.currentToken] == this.currentToken)?"":" - take default") ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + prevAct=act; + + if (optionalSemicolonState[act]) + { + if (term_check[base_action[act]+this.currentToken] != this.currentToken) + { + if (isErrorState(act)) + { + if (!insertedSemicolon && shouldInsertSemicolon(prevPos, prevToken) ) + { + currentToken = TokenNameSEMICOLON; + this.insertedSemicolonPosition=prevPos; + scanner.pushBack(); + insertedSemicolon = true; + + } + } + } + } + + act = tAction(act, this.currentToken); + if (act == ERROR_ACTION || this.restartRecovery) { +// if ( act == ERROR_ACTION && +// !insertedSemicolon && +// shouldInsertSemicolon(prevPos, prevToken) +// ) { +// act = prevAct; +// --stateStackTop; +// currentToken = TokenNameSEMICOLON; +// scanner.pushBack(); +// insertedSemicolon = true; +// continue ProcessTerminals; +// } + + if (DEBUG_AUTOMATON) { + if (this.restartRecovery) { + System.out.println("Restart - "); //$NON-NLS-1$ + } else { + System.out.println("Error - "); //$NON-NLS-1$ + } + } + + int errorPos = this.scanner.currentPosition; + if (!this.hasReportedError) { + this.hasError = true; + } + if (resumeOnSyntaxError()) { + if (act == ERROR_ACTION) this.lastErrorEndPosition = errorPos; + act = START_STATE; + this.stateStackTop = -1; + this.currentToken = getFirstToken(); + if (DEBUG) System.out.println("!! Resume on syntax error"); //$NON-NLS-1$ + continue ProcessTerminals; + } + act = ERROR_ACTION; + break ProcessTerminals; + } + if (act <= NUM_RULES) { + insertedSemicolon = false; + this.stateStackTop--; + + if (DEBUG_AUTOMATON) { + System.out.print("Reduce - "); //$NON-NLS-1$ + } + + } else if (act > ERROR_ACTION) { /* shift-reduce */ + if (DEBUG) System.out.println("<>shift-reduce Next Token: "+scanner.dumpCurrent()); //$NON-NLS-1$ + } catch(InvalidInputException e){ + if (!this.hasReportedError){ + this.problemReporter().scannerError(this, e.getMessage()); + this.hasReportedError = true; + } + this.lastCheckPoint = this.scanner.currentPosition; + this.restartRecovery = true; + } + if(this.statementRecoveryActivated) { + this.jumpOverType(); + } + act -= ERROR_ACTION; + + if (DEBUG_AUTOMATON) { + System.out.print("Shift/Reduce - (" + name[terminal_index[this.currentToken]]+") "); //$NON-NLS-1$ //$NON-NLS-2$ + } + + } else { + if (act < ACCEPT_ACTION) { /* shift */ + if (DEBUG) System.out.println("<>shift next Token: "+scanner.dumpCurrent()); //$NON-NLS-1$ + } catch(InvalidInputException e){ + if (!this.hasReportedError){ + this.problemReporter().scannerError(this, e.getMessage()); + this.hasReportedError = true; + } + this.lastCheckPoint = this.scanner.currentPosition; + this.restartRecovery = true; + } + if(this.statementRecoveryActivated) { + this.jumpOverType(); + } + if (DEBUG_AUTOMATON) { + System.out.println("Shift - (" + name[terminal_index[this.currentToken]]+")"); //$NON-NLS-1$ //$NON-NLS-2$ + } + continue ProcessTerminals; + } + break ProcessTerminals; + } + + // ProcessNonTerminals : + do { /* reduce */ + + if (DEBUG_AUTOMATON) { + System.out.println(name[non_terminal_index[lhs[act]]]); + } + + consumeRule(act); + this.stateStackTop -= (rhs[act] - 1); + act = ntAction(this.stack[this.stateStackTop], lhs[act]); + if (DEBUG_AUTOMATON && act <= NUM_RULES) { + System.out.print(" - "); //$NON-NLS-1$ + } + + } while (act <= NUM_RULES); + if (DEBUG_AUTOMATON) { + System.out.println("----------------------------------------"); //$NON-NLS-1$ + } + } + if (DEBUG_AUTOMATON) { + System.out.println("- End ----------------------------------"); //$NON-NLS-1$ + } + + endParse(act); + // record all nls tags in the corresponding compilation unit + final NLSTag[] tags = this.scanner.getNLSTags(); + if (tags != null) { + this.compilationUnit.nlsTags = tags; + } + + this.scanner.checkNonExternalizedStringLiterals = false; + if (this.reportSyntaxErrorIsRequired && this.hasError && !(this.statementRecoveryActivated && DO_DIET_PARSE)) { + if(!this.options.performStatementsRecovery) { + reportSyntaxErrors(isDietParse, oldFirstToken); + } else { + RecoveryScannerData data = this.referenceContext.compilationResult().recoveryScannerData; + + if(this.recoveryScanner == null) { + this.recoveryScanner = new RecoveryScanner(this.scanner, data); + } else { + this.recoveryScanner.setData(data); + } + + this.recoveryScanner.setSource(scanner.source); + this.recoveryScanner.lineEnds = this.scanner.lineEnds; + this.recoveryScanner.linePtr = this.scanner.linePtr; + + reportSyntaxErrors(isDietParse, oldFirstToken); + + if(data == null) { + this.referenceContext.compilationResult().recoveryScannerData = + this.recoveryScanner.getData(); + } + + if (this.methodRecoveryActivated && this.options.performStatementsRecovery && !this.enteredRecoverStatements) { + this.methodRecoveryActivated = false; + this.enteredRecoverStatements=true; + this.recoverStatements(); + this.methodRecoveryActivated = true; + + this.lastAct = ERROR_ACTION; + } + } + } + + if (DEBUG) System.out.println("-- EXIT FROM PARSE METHOD --"); //$NON-NLS-1$ +} +public void parse(ConstructorDeclaration cd, CompilationUnitDeclaration unit) { + parse(cd, unit, false); +} +public void parse(ConstructorDeclaration cd, CompilationUnitDeclaration unit, boolean recordLineSeparator) { + //only parse the method body of cd + //fill out its statements + + //convert bugs into parse error + + boolean oldMethodRecoveryActivated = this.methodRecoveryActivated; + if(this.options.performMethodsFullRecovery) { + this.methodRecoveryActivated = true; + } + + initialize(); + goForBlockStatementsopt(); + if (recordLineSeparator) { + this.scanner.recordLineSeparator = true; + } + this.nestedMethod[this.nestedType]++; + pushOnRealBlockStack(0); + + this.referenceContext = cd; + this.compilationUnit = unit; + + this.scanner.resetTo(cd.bodyStart, cd.bodyEnd); + try { + parse(); + } catch (AbortCompilation ex) { + this.lastAct = ERROR_ACTION; + } finally { + this.nestedMethod[this.nestedType]--; + if(this.options.performStatementsRecovery) { + this.methodRecoveryActivated = oldMethodRecoveryActivated; + } + } + + checkNonNLSAfterBodyEnd(cd.declarationSourceEnd); + + if (this.lastAct == ERROR_ACTION) { + initialize(); + return; + } + + //statements + cd.explicitDeclarations = this.realBlockStack[this.realBlockPtr--]; + int length; + if (astLengthPtr > -1 && (length = this.astLengthStack[this.astLengthPtr--]) != 0) { + this.astPtr -= length; + if (this.astStack[this.astPtr + 1] instanceof ExplicitConstructorCall) + //avoid a isSomeThing that would only be used here BUT what is faster between two alternatives ? + { + System.arraycopy( + this.astStack, + this.astPtr + 2, + cd.statements = new Statement[length - 1], + 0, + length - 1); + cd.constructorCall = (ExplicitConstructorCall) this.astStack[this.astPtr + 1]; + } else { //need to add explicitly the super(); + System.arraycopy( + this.astStack, + this.astPtr + 1, + cd.statements = new Statement[length], + 0, + length); + cd.constructorCall = SuperReference.implicitSuperConstructorCall(); + } + } else { + cd.constructorCall = SuperReference.implicitSuperConstructorCall(); + if (!containsComment(cd.bodyStart, cd.bodyEnd)) { + cd.bits |= ASTNode.UndocumentedEmptyBlock; + } + } + + if (cd.constructorCall.sourceEnd == 0) { + cd.constructorCall.sourceEnd = cd.sourceEnd; + cd.constructorCall.sourceStart = cd.sourceStart; + } +} +// A P I + +public void parse( + FieldDeclaration field, + TypeDeclaration type, + CompilationUnitDeclaration unit, + char[] initializationSource) { + //only parse the initializationSource of the given field + + //convert bugs into parse error + + initialize(); + goForExpression(); + this.nestedMethod[this.nestedType]++; + + this.referenceContext = type; + this.compilationUnit = unit; + + this.scanner.setSource(initializationSource); + this.scanner.resetTo(0, initializationSource.length-1); + try { + parse(); + } catch (AbortCompilation ex) { + this.lastAct = ERROR_ACTION; + } finally { + this.nestedMethod[this.nestedType]--; + } + + if (this.lastAct == ERROR_ACTION) { + return; + } + + field.initialization = this.expressionStack[this.expressionPtr]; + + // mark field with local type if one was found during parsing + if ((type.bits & ASTNode.HasLocalType) != 0) { + field.bits |= ASTNode.HasLocalType; + } +} +// A P I + +public CompilationUnitDeclaration parse( + ICompilationUnit sourceUnit, + CompilationResult compilationResult) { + // parses a compilation unit and manages error handling (even bugs....) + + return parse(sourceUnit, compilationResult, -1, -1/*parse without reseting the scanner*/); +} +// A P I + +public CompilationUnitDeclaration parse( + ICompilationUnit sourceUnit, + CompilationResult compilationResult, + int start, + int end) { + // parses a compilation unit and manages error handling (even bugs....) + + CompilationUnitDeclaration unit; + try { + /* automaton initialization */ + initialize(true); + goForCompilationUnit(); + + /* unit creation */ + this.referenceContext = + this.compilationUnit = + new CompilationUnitDeclaration( + this.problemReporter, + compilationResult, + 0); + + + initializeInferenceEngine(this.compilationUnit); + + /* scanners initialization */ + char[] contents; + try { + contents = sourceUnit.getContents(); + } catch(AbortCompilationUnit abortException) { + this.problemReporter().cannotReadSource(this.compilationUnit, abortException, this.options.verbose); + contents = CharOperation.NO_CHAR; // pretend empty from thereon + } + this.scanner.setSource(contents); + this.compilationUnit.sourceEnd = this.scanner.source.length - 1; + if (end != -1) this.scanner.resetTo(start, end); + if (this.javadocParser != null && this.javadocParser.checkDocComment) { + this.javadocParser.scanner.setSource(contents); + if (end != -1) { + this.javadocParser.scanner.resetTo(start, end); + } + } + /* run automaton */ +if (false) + System.out.println("parsing "+new String(sourceUnit.getFileName())); //$NON-NLS-1$ + parse(); + } finally { + unit = this.compilationUnit; + this.compilationUnit = null; // reset parser + // tag unit has having read bodies + if (!this.diet) unit.bits |= ASTNode.HasAllMethodBodies; + } + return unit; +} + +public void initializeInferenceEngine(CompilationUnitDeclaration compilationUnitDeclaration) { + if (this.inferenceEngines==null) + this.inferenceEngines = InferrenceManager.getInstance().getInferenceEngines(compilationUnitDeclaration); + for (int i = 0; i < this.inferenceEngines.length; i++) { + this.inferenceEngines[i].initializeOptions(this.options.inferOptions); + } +} + +public void parse( + Initializer initializer, + TypeDeclaration type, + CompilationUnitDeclaration unit) { + //only parse the method body of md + //fill out method statements + + //convert bugs into parse error + + boolean oldMethodRecoveryActivated = this.methodRecoveryActivated; + if(this.options.performMethodsFullRecovery) { + this.methodRecoveryActivated = true; + } + + initialize(); + goForBlockStatementsopt(); + this.nestedMethod[this.nestedType]++; + pushOnRealBlockStack(0); + + this.referenceContext = type; + this.compilationUnit = unit; + + this.scanner.resetTo(initializer.bodyStart, initializer.bodyEnd); // just on the beginning { + try { + parse(); + } catch (AbortCompilation ex) { + this.lastAct = ERROR_ACTION; + } finally { + this.nestedMethod[this.nestedType]--; + if(this.options.performStatementsRecovery) { + this.methodRecoveryActivated = oldMethodRecoveryActivated; + } + } + + checkNonNLSAfterBodyEnd(initializer.declarationSourceEnd); + + if (this.lastAct == ERROR_ACTION) { + return; + } + + //refill statements + initializer.block.explicitDeclarations = this.realBlockStack[this.realBlockPtr--]; + int length; + if (astLengthPtr > -1 && (length = this.astLengthStack[this.astLengthPtr--]) > 0) { + System.arraycopy(this.astStack, (this.astPtr -= length) + 1, initializer.block.statements = new Statement[length], 0, length); + } else { + // check whether this block at least contains some comment in it + if (!containsComment(initializer.block.sourceStart, initializer.block.sourceEnd)) { + initializer.block.bits |= ASTNode.UndocumentedEmptyBlock; + } + } + + // mark initializer with local type if one was found during parsing + if ((type.bits & ASTNode.HasLocalType) != 0) { + initializer.bits |= ASTNode.HasLocalType; + } +} +// A P I +public void parse(MethodDeclaration md, CompilationUnitDeclaration unit) { + //only parse the method body of md + //fill out method statements + + //convert bugs into parse error + + if (md.isAbstract()) + return; + if ((md.modifiers & ExtraCompilerModifiers.AccSemicolonBody) != 0) + return; + + boolean oldMethodRecoveryActivated = this.methodRecoveryActivated; + if(this.options.performMethodsFullRecovery) { + this.methodRecoveryActivated = true; + this.rParenPos = md.sourceEnd; + } + initialize(); + goForBlockStatementsopt(); + this.nestedMethod[this.nestedType]++; + pushOnRealBlockStack(0); + + this.referenceContext = md; + this.compilationUnit = unit; + + this.scanner.resetTo(md.bodyStart, md.bodyEnd); + // reset the scanner to parser from { down to } + try { + parse(); + } catch (AbortCompilation ex) { + this.lastAct = ERROR_ACTION; + } finally { + this.nestedMethod[this.nestedType]--; + if(this.options.performStatementsRecovery) { + this.methodRecoveryActivated = oldMethodRecoveryActivated; + } + } + + checkNonNLSAfterBodyEnd(md.declarationSourceEnd); + + if (this.lastAct == ERROR_ACTION) { + return; + } + + //refill statements + md.explicitDeclarations = this.realBlockStack[this.realBlockPtr--]; + int length; + if (astLengthPtr > -1 && (length = this.astLengthStack[this.astLengthPtr--]) != 0) { + System.arraycopy( + this.astStack, + (this.astPtr -= length) + 1, + md.statements = new Statement[length], + 0, + length); + } else { + if (!containsComment(md.bodyStart, md.bodyEnd)) { + md.bits |= ASTNode.UndocumentedEmptyBlock; + } + } +} +public ASTNode[] parseClassBodyDeclarations(char[] source, int offset, int length, CompilationUnitDeclaration unit) { + /* automaton initialization */ + initialize(); + goForClassBodyDeclarations(); + /* scanner initialization */ + this.scanner.setSource(source); + this.scanner.resetTo(offset, offset + length - 1); + if (this.javadocParser != null && this.javadocParser.checkDocComment) { + this.javadocParser.scanner.setSource(source); + this.javadocParser.scanner.resetTo(offset, offset + length - 1); + } + + /* type declaration should be parsed as member type declaration */ + this.nestedType = 1; + + /* unit creation */ + this.referenceContext = unit; + this.compilationUnit = unit; + + /* run automaton */ + try { + parse(); + } catch (AbortCompilation ex) { + this.lastAct = ERROR_ACTION; + } + + if (this.lastAct == ERROR_ACTION || this.hasError) { + return null; + } + int astLength; + if (astLengthPtr > -1 && (astLength = this.astLengthStack[this.astLengthPtr--]) != 0) { + ASTNode[] result = new ASTNode[astLength]; + this.astPtr -= astLength; + System.arraycopy(this.astStack, this.astPtr + 1, result, 0, astLength); + return result; + } + return null; +} +public Expression parseExpression(char[] source, int offset, int length, CompilationUnitDeclaration unit) { + + initialize(); + goForExpression(); + this.nestedMethod[this.nestedType]++; + + this.referenceContext = unit; + this.compilationUnit = unit; + + this.scanner.setSource(source); + this.scanner.resetTo(offset, offset + length - 1); + try { + parse(); + } catch (AbortCompilation ex) { + this.lastAct = ERROR_ACTION; + } finally { + this.nestedMethod[this.nestedType]--; + } + + if (this.lastAct == ERROR_ACTION) { + return null; + } + + return this.expressionStack[this.expressionPtr]; +} +public Expression parseMemberValue(char[] source, int offset, int length, CompilationUnitDeclaration unit) { + + initialize(); + goForMemberValue(); + this.nestedMethod[this.nestedType]++; + + this.referenceContext = unit; + this.compilationUnit = unit; + + this.scanner.setSource(source); + this.scanner.resetTo(offset, offset + length - 1); + try { + parse(); + } catch (AbortCompilation ex) { + this.lastAct = ERROR_ACTION; + } finally { + this.nestedMethod[this.nestedType]--; + } + + if (this.lastAct == ERROR_ACTION) { + return null; + } + + return this.expressionStack[this.expressionPtr]; +} +public void parseStatements(ReferenceContext rc, int start, int end, TypeDeclaration[] types, CompilationUnitDeclaration unit) { + boolean oldStatementRecoveryEnabled = this.statementRecoveryActivated; + this.statementRecoveryActivated = true; + + initialize(); + + if (rc instanceof CompilationUnitDeclaration) + goForCompilationUnit(); + else + goForBlockStatementsopt(); + this.nestedMethod[this.nestedType]++; + pushOnRealBlockStack(0); + + //pushOnAstLengthStack(0); + + this.referenceContext = rc; + this.compilationUnit = unit; + + this.pendingRecoveredType = null; + + if(types != null && types.length > 0) { + this.recoveredTypes = types; + this.recoveredTypePtr = 0; + this.nextTypeStart = + this.recoveredTypes[0].allocation == null + ? this.recoveredTypes[0].declarationSourceStart + : this.recoveredTypes[0].allocation.sourceStart; + } else { + this.recoveredTypes = null; + this.recoveredTypePtr = -1; + this.nextTypeStart = -1; + } + + this.scanner.resetTo(start, end); + // reset the scanner to parser from { down to } + + this.lastCheckPoint = this.scanner.initialPosition; + + + this.stateStackTop = -1; + + try { + parse(); + } catch (AbortCompilation ex) { + this.lastAct = ERROR_ACTION; + } finally { + this.nestedMethod[this.nestedType]--; + this.recoveredTypes = null; + this.statementRecoveryActivated = oldStatementRecoveryEnabled; + } + + checkNonNLSAfterBodyEnd(end); +} +public void persistLineSeparatorPositions() { + if (this.scanner.recordLineSeparator) { + this.compilationUnit.compilationResult.lineSeparatorPositions = this.scanner.getLineEnds(); + } +} +/* + * Prepares the state of the parser to go for BlockStatements. + */ +protected void prepareForBlockStatements() { + this.nestedMethod[this.nestedType = 0] = 1; + this.variablesCounter[this.nestedType] = 0; + this.realBlockStack[this.realBlockPtr = 1] = 0; +} +/** + * Returns this parser's problem reporter initialized with its reference context. + * Also it is assumed that a problem is going to be reported, so initializes + * the compilation result's line positions. + * + * @return ProblemReporter + */ +public ProblemReporter problemReporter(){ + if (this.scanner.recordLineSeparator) { + if (this.compilationUnit!=null) + this.compilationUnit.compilationResult.lineSeparatorPositions = this.scanner.getLineEnds(); + } + this.problemReporter.referenceContext = this.referenceContext; + return this.problemReporter; +} +protected void pushIdentifier() { + /*push the consumeToken on the identifier stack. + Increase the total number of identifier in the stack. + identifierPtr points on the next top */ + + int stackLength = this.identifierStack.length; + if (++this.identifierPtr >= stackLength) { + System.arraycopy( + this.identifierStack, 0, + this.identifierStack = new char[stackLength + 20][], 0, + stackLength); + System.arraycopy( + this.identifierPositionStack, 0, + this.identifierPositionStack = new long[stackLength + 20], 0, + stackLength); + } + this.identifierStack[this.identifierPtr] = this.scanner.getCurrentIdentifierSource(); + this.identifierPositionStack[this.identifierPtr] = + (((long) this.scanner.startPosition) << 32) + (this.scanner.currentPosition - 1); + + stackLength = this.identifierLengthStack.length; + if (++this.identifierLengthPtr >= stackLength) { + System.arraycopy( + this.identifierLengthStack, 0, + this.identifierLengthStack = new int[stackLength + 10], 0, + stackLength); + } + this.identifierLengthStack[this.identifierLengthPtr] = 1; +} +protected void pushIdentifier(int flag) { + /*push a special flag on the stack : + -zero stands for optional Name + -negative number for direct ref to base types. + identifierLengthPtr points on the top */ + + int stackLength = this.identifierLengthStack.length; + if (++this.identifierLengthPtr >= stackLength) { + System.arraycopy( + this.identifierLengthStack, 0, + this.identifierLengthStack = new int[stackLength + 10], 0, + stackLength); + } + this.identifierLengthStack[this.identifierLengthPtr] = flag; +} +protected void pushOnAstLengthStack(int pos) { + + int stackLength = this.astLengthStack.length; + if (++this.astLengthPtr >= stackLength) { + System.arraycopy( + this.astLengthStack, 0, + this.astLengthStack = new int[stackLength + StackIncrement], 0, + stackLength); + } + this.astLengthStack[this.astLengthPtr] = pos; +} +protected void pushOnAstStack(ASTNode node) { + /*add a new obj on top of the ast stack + astPtr points on the top*/ + + int stackLength = this.astStack.length; + if (++this.astPtr >= stackLength) { + System.arraycopy( + this.astStack, 0, + this.astStack = new ASTNode[stackLength + AstStackIncrement], 0, + stackLength); + this.astPtr = stackLength; + } + this.astStack[this.astPtr] = node; + + stackLength = this.astLengthStack.length; + if (++this.astLengthPtr >= stackLength) { + System.arraycopy( + this.astLengthStack, 0, + this.astLengthStack = new int[stackLength + AstStackIncrement], 0, + stackLength); + } + this.astLengthStack[this.astLengthPtr] = 1; +} +protected void pushOnExpressionStack(Expression expr) { + + int stackLength = this.expressionStack.length; + if (++this.expressionPtr >= stackLength) { + System.arraycopy( + this.expressionStack, 0, + this.expressionStack = new Expression[stackLength + ExpressionStackIncrement], 0, + stackLength); + } + this.expressionStack[this.expressionPtr] = expr; + + stackLength = this.expressionLengthStack.length; + if (++this.expressionLengthPtr >= stackLength) { + System.arraycopy( + this.expressionLengthStack, 0, + this.expressionLengthStack = new int[stackLength + ExpressionStackIncrement], 0, + stackLength); + } + this.expressionLengthStack[this.expressionLengthPtr] = 1; +} +protected void pushOnExpressionStackLengthStack(int pos) { + + int stackLength = this.expressionLengthStack.length; + if (++this.expressionLengthPtr >= stackLength) { + System.arraycopy( + this.expressionLengthStack, 0, + this.expressionLengthStack = new int[stackLength + StackIncrement], 0, + stackLength); + } + this.expressionLengthStack[this.expressionLengthPtr] = pos; +} +protected void pushOnGenericsStack(ASTNode node) { + /*add a new obj on top of the generics stack + genericsPtr points on the top*/ + + int stackLength = this.genericsStack.length; + if (++this.genericsPtr >= stackLength) { + System.arraycopy( + this.genericsStack, 0, + this.genericsStack = new ASTNode[stackLength + GenericsStackIncrement], 0, + stackLength); + } + this.genericsStack[this.genericsPtr] = node; + + stackLength = this.genericsLengthStack.length; + if (++this.genericsLengthPtr >= stackLength) { + System.arraycopy( + this.genericsLengthStack, 0, + this.genericsLengthStack = new int[stackLength + GenericsStackIncrement], 0, + stackLength); + } + this.genericsLengthStack[this.genericsLengthPtr] = 1; +} +protected void pushOnGenericsIdentifiersLengthStack(int pos) { + int stackLength = this.genericsIdentifiersLengthStack.length; + if (++this.genericsIdentifiersLengthPtr >= stackLength) { + System.arraycopy( + this.genericsIdentifiersLengthStack, 0, + this.genericsIdentifiersLengthStack = new int[stackLength + GenericsStackIncrement], 0, + stackLength); + } + this.genericsIdentifiersLengthStack[this.genericsIdentifiersLengthPtr] = pos; +} +protected void pushOnGenericsLengthStack(int pos) { + int stackLength = this.genericsLengthStack.length; + if (++this.genericsLengthPtr >= stackLength) { + System.arraycopy( + this.genericsLengthStack, 0, + this.genericsLengthStack = new int[stackLength + GenericsStackIncrement], 0, + stackLength); + } + this.genericsLengthStack[this.genericsLengthPtr] = pos; +} +protected void pushOnIntStack(int pos) { + + int stackLength = this.intStack.length; + if (++this.intPtr >= stackLength) { + System.arraycopy( + this.intStack, 0, + this.intStack = new int[stackLength + StackIncrement], 0, + stackLength); + } + this.intStack[this.intPtr] = pos; +} +protected void pushOnRealBlockStack(int i){ + + int stackLength = this.realBlockStack.length; + if (++this.realBlockPtr >= stackLength) { + System.arraycopy( + this.realBlockStack, 0, + this.realBlockStack = new int[stackLength + StackIncrement], 0, + stackLength); + } + this.realBlockStack[this.realBlockPtr] = i; +} +protected void recoverStatements() { + class MethodVisitor extends ASTVisitor { + public ASTVisitor typeVisitor; + + TypeDeclaration enclosingType; // used only for initializer + + TypeDeclaration[] types = new TypeDeclaration[0]; + int typePtr = -1; + public boolean visit(ConstructorDeclaration constructorDeclaration, ClassScope scope) { + typePtr = -1; + return true; + } + public boolean visit(Initializer initializer, MethodScope scope) { + typePtr = -1; + return true; + } + public boolean visit(MethodDeclaration methodDeclaration,Scope scope) { + typePtr = -1; + return true; + } + public boolean visit(TypeDeclaration typeDeclaration, BlockScope scope) { + return this.visit(typeDeclaration); + } + public boolean visit(TypeDeclaration typeDeclaration, Scope scope) { + return this.visit(typeDeclaration); + } + private boolean visit(TypeDeclaration typeDeclaration) { + if(this.types.length <= ++this.typePtr) { + int length = this.typePtr; + System.arraycopy(this.types, 0, this.types = new TypeDeclaration[length * 2 + 1], 0, length); + } + this.types[this.typePtr] = typeDeclaration; + return false; + } + public void endVisit(ConstructorDeclaration constructorDeclaration, ClassScope scope) { + this.endVisitMethod(constructorDeclaration, scope); + } + public void endVisit(MethodDeclaration methodDeclaration, Scope scope) { + this.endVisitMethod(methodDeclaration, scope); + } + private void endVisitMethod(AbstractMethodDeclaration methodDeclaration, Scope scope) { + TypeDeclaration[] foundTypes = null; +// int length = 0; +// if(this.typePtr > -1) { +// length = this.typePtr + 1; +// foundTypes = new TypeDeclaration[length]; +// System.arraycopy(this.types, 0, foundTypes, 0, length); +// } + ReferenceContext oldContext = Parser.this.referenceContext; + Parser.this.recoveryScanner.resetTo(methodDeclaration.bodyStart, methodDeclaration.bodyEnd); + Scanner oldScanner = Parser.this.scanner; + Parser.this.scanner = Parser.this.recoveryScanner; + Parser.this.parseStatements( + methodDeclaration, + methodDeclaration.bodyStart, + methodDeclaration.bodyEnd, + foundTypes, + compilationUnit); + Parser.this.scanner = oldScanner; + Parser.this.referenceContext = oldContext; + +// for (int i = 0; i < length; i++) { +// foundTypes[i].traverse(typeVisitor, scope); +// } + } + public void endVisit(Initializer initializer, MethodScope scope) { + TypeDeclaration[] foundTypes = null; + int length = 0; + if(this.typePtr > -1) { + length = this.typePtr + 1; + foundTypes = new TypeDeclaration[length]; + System.arraycopy(this.types, 0, foundTypes, 0, length); + } + ReferenceContext oldContext = Parser.this.referenceContext; + Parser.this.recoveryScanner.resetTo(initializer.bodyStart, initializer.bodyEnd); + Scanner oldScanner = Parser.this.scanner; + Parser.this.scanner = Parser.this.recoveryScanner; + Parser.this.parseStatements( + this.enclosingType, + initializer.bodyStart, + initializer.bodyEnd, + foundTypes, + compilationUnit); + Parser.this.scanner = oldScanner; + Parser.this.referenceContext = oldContext; + + for (int i = 0; i < length; i++) { + foundTypes[i].traverse(typeVisitor, scope); + } + } + } + class TypeVisitor extends ASTVisitor { + public MethodVisitor methodVisitor; + + TypeDeclaration[] types = new TypeDeclaration[0]; + int typePtr = -1; + + public void endVisit(TypeDeclaration typeDeclaration, BlockScope scope) { + endVisitType(); + } + public void endVisit(TypeDeclaration typeDeclaration, ClassScope scope) { + endVisitType(); + } + private void endVisitType() { + this.typePtr--; + } + public boolean visit(TypeDeclaration typeDeclaration, BlockScope scope) { + return this.visit(typeDeclaration); + } + public boolean visit(TypeDeclaration typeDeclaration, ClassScope scope) { + return this.visit(typeDeclaration); + } + private boolean visit(TypeDeclaration typeDeclaration) { + if(this.types.length <= ++this.typePtr) { + int length = this.typePtr; + System.arraycopy(this.types, 0, this.types = new TypeDeclaration[length * 2 + 1], 0, length); + } + this.types[this.typePtr] = typeDeclaration; + return true; + } + public boolean visit(ConstructorDeclaration constructorDeclaration, ClassScope scope) { + if(constructorDeclaration.isDefaultConstructor()) return false; + + constructorDeclaration.traverse(methodVisitor, scope); + return false; + } + public boolean visit(Initializer initializer, MethodScope scope) { + methodVisitor.enclosingType = this.types[typePtr]; + initializer.traverse(methodVisitor, scope); + return false; + } + public boolean visit(MethodDeclaration methodDeclaration, Scope scope) { + methodDeclaration.traverse(methodVisitor, scope); + return false; + } + } + + if (false) + { + MethodVisitor methodVisitor = new MethodVisitor(); + TypeVisitor typeVisitor = new TypeVisitor(); + methodVisitor.typeVisitor = typeVisitor; + typeVisitor.methodVisitor = methodVisitor; + + if(this.referenceContext instanceof AbstractMethodDeclaration) { + ((AbstractMethodDeclaration)this.referenceContext).traverse(methodVisitor, (Scope)null); + }else if(this.referenceContext instanceof CompilationUnitDeclaration) { + CompilationUnitDeclaration compilationUnitDeclaration=(CompilationUnitDeclaration)this.referenceContext; + if (compilationUnitDeclaration.statements!=null) + for (int i = 0; i < compilationUnitDeclaration.statements.length; i++) { + if( compilationUnitDeclaration.statements[i] instanceof AbstractMethodDeclaration) + ((AbstractMethodDeclaration)compilationUnitDeclaration.statements[i] ).traverse(methodVisitor, (Scope)null); + } + } else if(this.referenceContext instanceof TypeDeclaration) { + TypeDeclaration typeContext = (TypeDeclaration)this.referenceContext; + + int length = typeContext.fields.length; + for (int i = 0; i < length; i++) { + final FieldDeclaration fieldDeclaration = typeContext.fields[i]; + switch(fieldDeclaration.getKind()) { + case AbstractVariableDeclaration.INITIALIZER: + methodVisitor.enclosingType = typeContext; + ((Initializer) fieldDeclaration).traverse(methodVisitor, (MethodScope)null); + break; + } + } + } + } + else + { + CompilationUnitDeclaration compilationUnitDeclaration=(CompilationUnitDeclaration)this.referenceContext; + + ReferenceContext oldContext = Parser.this.referenceContext; + int start = compilationUnitDeclaration.sourceStart; + int end = compilationUnitDeclaration.sourceEnd; + Parser.this.recoveryScanner.resetTo(start, end); + Scanner oldScanner = Parser.this.scanner; + Parser.this.scanner = Parser.this.recoveryScanner; + /* unit creation */ + this.referenceContext = + this.compilationUnit = compilationUnitDeclaration= + new CompilationUnitDeclaration( + this.problemReporter, + compilationUnitDeclaration.compilationResult, + end); + + Parser.this.parseStatements( + compilationUnitDeclaration, + start, + end, + null, + compilationUnit); + Parser.this.scanner = oldScanner; + Parser.this.referenceContext = oldContext; + } + + +} + +public void recoveryExitFromVariable() { + if(this.currentElement != null && this.currentElement.parent != null) { + if(this.currentElement instanceof RecoveredLocalVariable) { + + int end = ((RecoveredLocalVariable)this.currentElement).localDeclaration.sourceEnd; + this.currentElement.updateSourceEndIfNecessary(end); + this.currentElement = this.currentElement.parent; + } else if(this.currentElement instanceof RecoveredField + && !(this.currentElement instanceof RecoveredInitializer)) { + + int end = ((RecoveredField)this.currentElement).fieldDeclaration.sourceEnd; + this.currentElement.updateSourceEndIfNecessary(end); + this.currentElement = this.currentElement.parent; + } + } +} +/* Token check performed on every token shift once having entered + * recovery mode. + */ +public void recoveryTokenCheck() { + switch (this.currentToken) { + case TokenNameLBRACE : + RecoveredElement newElement = null; + if(!this.ignoreNextOpeningBrace) { + newElement = this.currentElement.updateOnOpeningBrace(this.scanner.startPosition - 1, this.scanner.currentPosition - 1); + } + this.lastCheckPoint = this.scanner.currentPosition; + if (newElement != null){ // null means nothing happened + this.restartRecovery = true; // opening brace detected + this.currentElement = newElement; + } + break; + + case TokenNameRBRACE : + this.rBraceStart = this.scanner.startPosition - 1; + this.rBraceEnd = this.scanner.currentPosition - 1; + this.endPosition = this.flushCommentsDefinedPriorTo(this.rBraceEnd); + newElement = + this.currentElement.updateOnClosingBrace(this.scanner.startPosition, this.rBraceEnd); + this.lastCheckPoint = this.scanner.currentPosition; + if (newElement != this.currentElement){ + this.currentElement = newElement; +// if (newElement instanceof RecoveredField && this.dietInt <= 0) { +// if (((RecoveredField)newElement).fieldDeclaration.type == null) { // enum constant +// this.isInsideEnumConstantPart = true; // restore status +// } +// } + } + break; + case TokenNameSEMICOLON : + this.endStatementPosition = this.scanner.currentPosition - 1; + this.endPosition = this.scanner.startPosition - 1; + this.lastCheckPoint=this.scanner.currentPosition; +// RecoveredType currentType = this.currentRecoveryType(); +// if(currentType != null) { +// currentType.insideEnumConstantPart = false; +// } + // fall through + default : { + if (this.rBraceEnd > this.rBraceSuccessorStart && this.scanner.currentPosition != this.scanner.startPosition){ + this.rBraceSuccessorStart = this.scanner.startPosition; + } + break; + } + } + this.ignoreNextOpeningBrace = false; +} + +protected boolean shouldInsertSemicolon(int prevpos, int prevtoken) { + Integer position = new Integer(prevpos); + if (this.errorAction.contains(position)) { + // should not insert a semi-colon at a location that has already be tried + return false; + } + this.errorAction.add(position); + return this.currentToken == TokenNameRBRACE + || scanner.getLineNumber(scanner.currentPosition) > scanner.getLineNumber(prevpos) + || this.currentToken==TokenNameEOF; +} + +// A P I +protected void reportSyntaxErrors(boolean isDietParse, int oldFirstToken) { + if(this.referenceContext instanceof MethodDeclaration) { + MethodDeclaration methodDeclaration = (MethodDeclaration) this.referenceContext; + if(methodDeclaration.errorInSignature){ + return; + } + } + this.compilationUnit.compilationResult.lineSeparatorPositions = this.scanner.getLineEnds(); + this.scanner.recordLineSeparator = false; + + int start = this.scanner.initialPosition; + int end = this.scanner.eofPosition == Integer.MAX_VALUE ? this.scanner.eofPosition : this.scanner.eofPosition - 1; + if(isDietParse) { + ProgramElement[] statements = this.compilationUnit.statements; +// TypeDeclaration[] types = this.compilationUnit.types; + int[][] intervalToSkip = org.eclipse.wst.jsdt.internal.compiler.parser.diagnose.RangeUtil.computeDietRange(statements); +// int[][] intervalToSkip = org.eclipse.wst.jsdt.internal.compiler.parser.diagnose.RangeUtil.computeDietRange(types); + DiagnoseParser diagnoseParser = new DiagnoseParser(this, oldFirstToken, start, end, intervalToSkip[0], intervalToSkip[1], intervalToSkip[2], this.options); + diagnoseParser.diagnoseParse(false); + + reportSyntaxErrorsForSkippedMethod(statements); +// reportSyntaxErrorsForSkippedMethod(types); + this.scanner.resetTo(start, end); + } else { + DiagnoseParser diagnoseParser = new DiagnoseParser(this, oldFirstToken, start, end, this.options); + diagnoseParser.diagnoseParse(this.options.performStatementsRecovery); + } +} +private void reportSyntaxErrorsForSkippedMethod(ProgramElement[] statements){ + if(statements != null) { + for (int i = 0; i < statements.length; i++) { +// TypeDeclaration[] memberTypes = types[i].memberTypes; +// if(memberTypes != null) { +// reportSyntaxErrorsForSkippedMethod(memberTypes); +// } +// +// AbstractMethodDeclaration[] methods = types[i].methods; +// if(methods != null) { +// for (int j = 0; j < methods.length; j++) { + if (statements[i] instanceof AbstractMethodDeclaration ) + { + AbstractMethodDeclaration method = (AbstractMethodDeclaration)statements[i] ; + if(method.errorInSignature) { + DiagnoseParser diagnoseParser = new DiagnoseParser(this, TokenNameDIVIDE, method.declarationSourceStart, method.declarationSourceEnd, this.options); + diagnoseParser.diagnoseParse(this.options.performStatementsRecovery); + } +// } + } + else if (statements[i] instanceof FieldDeclaration ) + { +// FieldDeclaration field =(FieldDeclaration) statements[i] ; +// if (fields != null) { +// int length = fields.length; +// for (int j = 0; j < length; j++) { +// if (fields[j] instanceof Initializer) { +// Initializer initializer = (Initializer)fields[j]; +// if(initializer.errorInSignature){ +// DiagnoseParser diagnoseParser = new DiagnoseParser(this, TokenNameRIGHT_SHIFT, initializer.declarationSourceStart, initializer.declarationSourceEnd, this.options); +// diagnoseParser.diagnoseParse(this.options.performStatementsRecovery); +// } +// } +// } + } + } + } +} +protected void resetModifiers() { + this.modifiers = ClassFileConstants.AccDefault; + this.modifiersSourceStart = -1; // <-- see comment into modifiersFlag(int) + this.scanner.commentPtr = -1; +} +/* + * Reset context so as to resume to regular parse loop + */ +protected void resetStacks() { + + this.astPtr = -1; + this.astLengthPtr = -1; + this.expressionPtr = -1; + this.expressionLengthPtr = -1; + this.identifierPtr = -1; + this.identifierLengthPtr = -1; + this.intPtr = -1; + this.nestedMethod[this.nestedType = 0] = 0; // need to reset for further reuse + this.variablesCounter[this.nestedType] = 0; + this.dimensions = 0 ; + this.realBlockStack[this.realBlockPtr = 0] = 0; + this.recoveredStaticInitializerStart = 0; + this.listLength = 0; + this.listTypeParameterLength = 0; + + this.genericsIdentifiersLengthPtr = -1; + this.genericsLengthPtr = -1; + this.genericsPtr = -1; + this.errorAction = new HashSet(); +} +/* + * Reset context so as to resume to regular parse loop + * If unable to reset for resuming, answers false. + * + * Move checkpoint location, reset internal stacks and + * decide which grammar goal is activated. + */ +protected boolean resumeAfterRecovery() { + if(!this.methodRecoveryActivated && !this.statementRecoveryActivated) { + + // reset internal stacks + this.resetStacks(); + this.resetModifiers(); + + /* attempt to move checkpoint location */ + if (!this.moveRecoveryCheckpoint()) { + return false; + } + + // only look for headers + if (this.referenceContext instanceof CompilationUnitDeclaration){ + if (DO_DIET_PARSE) + { + goForHeaders(); + this.diet = true; // passed this point, will not consider method bodies + } + else + goForProgramElements(); + return true; + } + + // does not know how to restart + return false; + } else if(!this.statementRecoveryActivated || !DO_DIET_PARSE) { + + // reset internal stacks + this.resetStacks(); + this.resetModifiers(); + + /* attempt to move checkpoint location */ + if (!this.moveRecoveryCheckpoint()) { + return false; + } + + // only look for headers + if (DO_DIET_PARSE) + goForHeaders(); + else + goForProgramElements(); + return true; + } else { + return false; + } +} +protected boolean resumeOnSyntaxError() { + this.checkExternalizeStrings = false; + this.scanner.checkNonExternalizedStringLiterals = false; + /* request recovery initialization */ + if (this.currentElement == null){ + // Reset javadoc before restart parsing after recovery + this.javadoc = null; + + // do not investigate deeper in statement recovery + if (this.statementRecoveryActivated) return false; + + // build some recovered elements + this.currentElement = buildInitialRecoveryState(); + } + /* do not investigate deeper in recovery when no recovered element */ + if (this.currentElement == null) return false; + + /* manual forced recovery restart - after headers */ + if (this.restartRecovery){ + this.restartRecovery = false; + } + /* update recovery state with current error state of the parser */ + this.updateRecoveryState(); + + /* attempt to reset state in order to resume to parse loop */ + return this.resumeAfterRecovery(); +} +public void setMethodsFullRecovery(boolean enabled) { + this.options.performMethodsFullRecovery = enabled; +} +public void setStatementsRecovery(boolean enabled) { + if(enabled) this.options.performMethodsFullRecovery = true; + this.options.performStatementsRecovery = enabled; +} +public String toString() { + + + String s = "lastCheckpoint : int = " + String.valueOf(this.lastCheckPoint) + "\n"; //$NON-NLS-1$ //$NON-NLS-2$ + s = s + "identifierStack : char["+(this.identifierPtr + 1)+"][] = {"; //$NON-NLS-1$ //$NON-NLS-2$ + for (int i = 0; i <= this.identifierPtr; i++) { + s = s + "\"" + String.valueOf(this.identifierStack[i]) + "\","; //$NON-NLS-1$ //$NON-NLS-2$ + } + s = s + "}\n"; //$NON-NLS-1$ + + s = s + "identifierLengthStack : int["+(this.identifierLengthPtr + 1)+"] = {"; //$NON-NLS-1$ //$NON-NLS-2$ + for (int i = 0; i <= this.identifierLengthPtr; i++) { + s = s + this.identifierLengthStack[i] + ","; //$NON-NLS-1$ + } + s = s + "}\n"; //$NON-NLS-1$ + + s = s + "astLengthStack : int["+(this.astLengthPtr + 1)+"] = {"; //$NON-NLS-1$ //$NON-NLS-2$ + for (int i = 0; i <= this.astLengthPtr; i++) { + s = s + this.astLengthStack[i] + ","; //$NON-NLS-1$ + } + s = s + "}\n"; //$NON-NLS-1$ + s = s + "astPtr : int = " + String.valueOf(this.astPtr) + "\n"; //$NON-NLS-1$ //$NON-NLS-2$ + + s = s + "intStack : int["+(this.intPtr + 1)+"] = {"; //$NON-NLS-1$ //$NON-NLS-2$ + for (int i = 0; i <= this.intPtr; i++) { + s = s + this.intStack[i] + ","; //$NON-NLS-1$ + } + s = s + "}\n"; //$NON-NLS-1$ + s = s + "intPtr : int = " + String.valueOf(this.intPtr) + "\n"; //$NON-NLS-1$ //$NON-NLS-2$ + + s = s + "expressionLengthStack : int["+(this.expressionLengthPtr + 1)+"] = {"; //$NON-NLS-1$ //$NON-NLS-2$ + for (int i = 0; i <= this.expressionLengthPtr; i++) { + s = s + this.expressionLengthStack[i] + ","; //$NON-NLS-1$ + } + s = s + "}\n"; //$NON-NLS-1$ + + s = s + "expressionPtr : int = " + String.valueOf(this.expressionPtr) + "\n"; //$NON-NLS-1$ //$NON-NLS-2$ + + s = s + "genericsIdentifiersLengthStack : int["+(this.genericsIdentifiersLengthPtr + 1)+"] = {"; //$NON-NLS-1$ //$NON-NLS-2$ + for (int i = 0; i <= this.genericsIdentifiersLengthPtr; i++) { + s = s + this.genericsIdentifiersLengthStack[i] + ","; //$NON-NLS-1$ + } + s = s + "}\n"; //$NON-NLS-1$ + + s = s + "genericsLengthStack : int["+(this.genericsLengthPtr + 1)+"] = {"; //$NON-NLS-1$ //$NON-NLS-2$ + for (int i = 0; i <= this.genericsLengthPtr; i++) { + s = s + this.genericsLengthStack[i] + ","; //$NON-NLS-1$ + } + s = s + "}\n"; //$NON-NLS-1$ + + s = s + "genericsPtr : int = " + String.valueOf(this.genericsPtr) + "\n"; //$NON-NLS-1$ //$NON-NLS-2$ + + s = s + "\n\n\n----------------Scanner--------------\n" + this.scanner.toString(); //$NON-NLS-1$ + return s; + +} +/* + * Update recovery state based on current parser/scanner state + */ +protected void updateRecoveryState() { + + /* expose parser state to recovery state */ + this.currentElement.updateFromParserState(); + + /* check and update recovered state based on current token, + this action is also performed when shifting token after recovery + got activated once. + */ + this.recoveryTokenCheck(); +} +protected void updateSourceDeclarationParts(int variableDeclaratorsCounter) { + //fields is a definition of fields that are grouped together like in + //public int[] a, b[], c + //which results into 3 fields. + + FieldDeclaration field; + int endTypeDeclarationPosition = + -1 + this.astStack[this.astPtr - variableDeclaratorsCounter + 1].sourceStart; + for (int i = 0; i < variableDeclaratorsCounter - 1; i++) { + //last one is special(see below) + field = (FieldDeclaration) this.astStack[this.astPtr - i - 1]; + field.endPart1Position = endTypeDeclarationPosition; + field.endPart2Position = -1 + this.astStack[this.astPtr - i].sourceStart; + } + //last one + (field = (FieldDeclaration) this.astStack[this.astPtr]).endPart1Position = + endTypeDeclarationPosition; + field.endPart2Position = field.declarationSourceEnd; + +} +protected void updateSourcePosition(Expression exp) { + //update the source Position of the expression + + //this.intStack : int int + //--> + //this.intStack : + + exp.sourceEnd = this.intStack[this.intPtr--]; + exp.sourceStart = this.intStack[this.intPtr--]; +} + +public void inferTypes(CompilationUnitDeclaration parsedUnit, CompilerOptions compileOptions) { + if (parsedUnit.typesHaveBeenInferred) + return; + if (compileOptions==null) + compileOptions=this.options; + + if (this.inferenceEngines==null) + initializeInferenceEngine(parsedUnit); +// InferEngine inferEngine=compileOptions.inferOptions.createEngine(); + for (int i=0;iDetermine if the given path is a match for the given match path. If one path is - * file system absolute and another is relative or absolute to the workspace then the - * path that is not file system absolute will be converted to file system absolute. - * The matching pattern can contain *, **, or ? wild cards.

- * - * @param pathChars check to see if this path matches the matchpathChars - * @param matchPathChars check to see if the given pathChars match this pattern - * @return true if the given pathChars match the given given - * matchPathChars, false otherwise. - */ - public static boolean pathMatch(char[] pathChars, char[] matchPathChars) { - IPath path = new Path(new String(pathChars)); - IPath matchPath = new Path(new String(matchPathChars)); - - //determine if either path is file system absolute - IPath fileSystemWorkspacePath = ResourcesPlugin.getWorkspace().getRoot().getLocation(); - boolean isPathFileSystemAbsolute = fileSystemWorkspacePath.isPrefixOf(path); - boolean isMatchPathFileSystemAbsolute = fileSystemWorkspacePath.isPrefixOf(matchPath); - - /* if the two paths are not both file system absolute or both workspace absolute - * then transform the none file system absolute path to file system absolute - */ - if((!isPathFileSystemAbsolute && isMatchPathFileSystemAbsolute) || (isPathFileSystemAbsolute && !isMatchPathFileSystemAbsolute)){ - if(!isPathFileSystemAbsolute) { - boolean hadTrailingSeparator = path.hasTrailingSeparator(); - path = ResourcesPlugin.getWorkspace().getRoot().getFile(path).getLocation(); - if(hadTrailingSeparator) { - path = path.addTrailingSeparator(); - } - } - - if(!isMatchPathFileSystemAbsolute) { - boolean hadTrailingSeparator = matchPath.hasTrailingSeparator(); - matchPath = ResourcesPlugin.getWorkspace().getRoot().getFile(matchPath).getLocation(); - if(hadTrailingSeparator) { - matchPath = matchPath.addTrailingSeparator(); - } - } - } - - //be sure both are absolute now (fixes 'project1\file.js' to '\project1\file.js') - path = path.makeAbsolute(); - matchPath = matchPath.makeAbsolute(); - - return CharOperation.pathMatch(matchPath.toPortableString().toCharArray(), path.toPortableString().toCharArray(), true, IPath.SEPARATOR); - } -} diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/SuffixConstants.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/SuffixConstants.java index bcfa58e2..0bfac3ae 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/SuffixConstants.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/SuffixConstants.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -28,4 +28,13 @@ public interface SuffixConstants { public final static char[] SUFFIX_zip = SUFFIX_STRING_zip.toCharArray(); public final static char[] SUFFIX_ZIP = SUFFIX_STRING_ZIP.toCharArray(); + + public final static String EXTENSION_jar= "jar"; //$NON-NLS-1$ + public final static String EXTENSION_JAR = "JAR"; //$NON-NLS-1$ + + public final static String SUFFIX_STRING_jar = "." + EXTENSION_jar; //$NON-NLS-1$ + public final static String SUFFIX_STRING_JAR = "." + EXTENSION_JAR; //$NON-NLS-1$ + + public final static char[] SUFFIX_jar = SUFFIX_STRING_jar.toCharArray(); + public final static char[] SUFFIX_JAR = SUFFIX_STRING_JAR.toCharArray(); } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/Util.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/Util.java index c02abbc4..353ef3e1 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/Util.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/compiler/util/Util.java @@ -20,6 +20,9 @@ import java.io.UnsupportedEncodingException; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.Path; import org.eclipse.wst.jsdt.core.IIncludePathEntry; import org.eclipse.wst.jsdt.core.ast.IExpression; import org.eclipse.wst.jsdt.core.ast.IFieldReference; @@ -112,7 +115,7 @@ public class Util implements SuffixConstants { * If a length is specified (ie. if length != -1), only length bytes * are returned. Otherwise all bytes in the stream are returned. * Note this doesn't close the stream. - * @throws IOException if a problem occurred reading the stream. + * @throws IOException if a problem occured reading the stream. */ public static byte[] getInputStreamAsByteArray(InputStream stream, int length) throws IOException { @@ -309,12 +312,22 @@ public class Util implements SuffixConstants { public final static boolean isArchiveFileName(String name) { int nameLength = name == null ? 0 : name.length(); int suffixLength = SUFFIX_ZIP.length; + if (nameLength == suffixLength) { + for (int i = 0; i < suffixLength; i++) { + char c = name.charAt(nameLength - i - 1); + int suffixIndex = suffixLength - i - 1; + if (c != SUFFIX_zip[suffixIndex] && c != SUFFIX_ZIP[suffixIndex]) + break; + } + } + + suffixLength = SUFFIX_JAR.length; if (nameLength < suffixLength) return false; for (int i = 0; i < suffixLength; i++) { char c = name.charAt(nameLength - i - 1); int suffixIndex = suffixLength - i - 1; - if (c != SUFFIX_zip[suffixIndex] && c != SUFFIX_ZIP[suffixIndex]) return false; + if (c != SUFFIX_jar[suffixIndex] && c != SUFFIX_JAR[suffixIndex]) return false; } return true; } @@ -334,7 +347,7 @@ public class Util implements SuffixConstants { return true; } /** - * Returns true iff str.toLowerCase().endsWith(".js") + * Returns true iff str.toLowerCase().endsWith(".class") * implementation is not creating extra strings. */ public final static boolean isClassFileName(String name) { @@ -392,7 +405,7 @@ public class Util implements SuffixConstants { } } } - if (EclipseUtil.pathMatch(path, folderPattern)) { + if (pathMatch(path, folderPattern)) { break inclusionCheck; } } @@ -403,7 +416,7 @@ public class Util implements SuffixConstants { } if (exclusionPatterns != null) { for (int i = 0, length = exclusionPatterns.length; i < length; i++) { - if (EclipseUtil.pathMatch(path, exclusionPatterns[i])) { + if (pathMatch(path, exclusionPatterns[i])) { return true; } } @@ -426,7 +439,7 @@ public class Util implements SuffixConstants { return true; } /** - * Returns true iff str.toLowerCase().endsWith(".js") + * Returns true if str.toLowerCase().endsWith(".js") * implementation is not creating extra strings. */ public final static boolean isJavaFileName(String name) { @@ -550,6 +563,7 @@ public class Util implements SuffixConstants { } else { currExpr = null; + selector = null; } } else if (currExpr instanceof IThisReference) { @@ -568,4 +582,53 @@ public class Util implements SuffixConstants { return selector; } + + /** + *

Determine if the given path is a match for the given match path. If one path is + * file system absolute and another is relative or absolute to the workspace then the + * path that is not file system absolute will be converted to file system absolute. + * The matching pattern can contain *, **, or ? wild cards.

+ * + * @param pathChars check to see if this path matches the matchpathChars + * @param matchPathChars check to see if the given pathChars match this pattern + * @return true if the given pathChars match the given given + * matchPathChars, false otherwise. + */ + public static boolean pathMatch(char[] pathChars, char[] matchPathChars) { + IPath path = new Path(new String(pathChars)); + IPath matchPath = new Path(new String(matchPathChars)); + + //determine if either path is file system absolute + IPath fileSystemWorkspacePath = ResourcesPlugin.getWorkspace().getRoot().getLocation(); + boolean isPathFileSystemAbsolute = fileSystemWorkspacePath.isPrefixOf(path); + boolean isMatchPathFileSystemAbsolute = fileSystemWorkspacePath.isPrefixOf(matchPath); + + /* if the two paths are not both file system absolute or both workspace absolute + * then transform the none file system absolute path to file system absolute + */ + if((!isPathFileSystemAbsolute && isMatchPathFileSystemAbsolute) || (isPathFileSystemAbsolute && !isMatchPathFileSystemAbsolute)){ + if(!isPathFileSystemAbsolute) { + boolean hadTrailingSeparator = path.hasTrailingSeparator(); + path = ResourcesPlugin.getWorkspace().getRoot().getFile(path).getLocation(); + if(hadTrailingSeparator) { + path = path.addTrailingSeparator(); + } + } + + if(!isMatchPathFileSystemAbsolute) { + boolean hadTrailingSeparator = matchPath.hasTrailingSeparator(); + matchPath = ResourcesPlugin.getWorkspace().getRoot().getFile(matchPath).getLocation(); + if(hadTrailingSeparator) { + matchPath = matchPath.addTrailingSeparator(); + } + } + } + + //be sure both are absolute now (fixes 'project1\file.js' to '\project1\file.js') + path = path.makeAbsolute(); + matchPath = matchPath.makeAbsolute(); + + return CharOperation.pathMatch(matchPath.toPortableString().toCharArray(), path.toPortableString().toCharArray(), true, IPath.SEPARATOR); + } + } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BinaryType.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BinaryType.java index 91859647..fedae0fa 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BinaryType.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BinaryType.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -524,8 +524,7 @@ public String[] getTypeParameterSignatures() throws JavaScriptModelException { if (genericSignature == null) return CharOperation.NO_STRINGS; - char[][] typeParams = new char[0][0]; - return CharOperation.toStrings(typeParams); + return CharOperation.toStrings(CharOperation.NO_CHAR_CHAR); } /* diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BinaryTypeConverter.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BinaryTypeConverter.java index 1dd61321..3263fb16 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BinaryTypeConverter.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/BinaryTypeConverter.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -96,7 +96,7 @@ public class BinaryTypeConverter { decl.returnType = createTypeReference(Signature.toString(method.getReturnType()).toCharArray()); methodDeclaration = decl; } - methodDeclaration.selector = method.getElementName().toCharArray(); + methodDeclaration.setSelector(method.getElementName().toCharArray()); int flags = method.getFlags(); boolean isVarargs = Flags.isVarargs(flags); methodDeclaration.modifiers = flags & ~Flags.AccVarargs; diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CancelableProblemFactory.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CancelableProblemFactory.java index afd92d56..a6b5086c 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CancelableProblemFactory.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CancelableProblemFactory.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2004, 2011 IBM Corporation and others. + * Copyright (c) 2004, 2007 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -13,6 +13,7 @@ package org.eclipse.wst.jsdt.internal.core; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.wst.jsdt.core.compiler.CategorizedProblem; +import org.eclipse.wst.jsdt.internal.compiler.problem.AbortCompilation; import org.eclipse.wst.jsdt.internal.compiler.problem.DefaultProblemFactory; @@ -25,10 +26,8 @@ public class CancelableProblemFactory extends DefaultProblemFactory { } public CategorizedProblem createProblem(char[] originatingFileName, int problemId, String[] problemArguments, String[] messageArguments, int severity, int startPosition, int endPosition, int lineNumber, int columnNumber) { - //if canceled throw exception - if (this.monitor != null && this.monitor.isCanceled()) { - throw new OperationCanceledException(); - } + if (this.monitor != null && this.monitor.isCanceled()) + throw new AbortCompilation(true/*silent*/, new OperationCanceledException()); return super.createProblem(originatingFileName, problemId, problemArguments, messageArguments, severity, startPosition, endPosition, lineNumber, columnNumber); } } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ClassFile.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ClassFile.java index 218814e9..4cec5bb8 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ClassFile.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ClassFile.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -10,11 +10,13 @@ *******************************************************************************/ package org.eclipse.wst.jsdt.internal.core; +import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.Map; +import java.util.zip.ZipFile; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; @@ -409,8 +411,7 @@ public IJavaScriptElement getElementAtConsideringSibling(int position) throws Ja if (mapper == null) { return null; } else { - int index = this.name.indexOf('$'); - int prefixLength = index < 0 ? this.name.length() : index; + int prefixLength = this.name.length(); IType type = null; int start = -1; @@ -419,8 +420,7 @@ public IJavaScriptElement getElementAtConsideringSibling(int position) throws Ja for (int i = 0; i < children.length; i++) { String childName = children[i].getElementName(); - int childIndex = childName.indexOf('$'); - int childPrefixLength = childIndex < 0 ? childName.indexOf('.') : childIndex; + int childPrefixLength = childName.indexOf('.'); if (prefixLength == childPrefixLength && this.name.regionMatches(0, childName, 0, prefixLength)) { IClassFile classFile = (IClassFile) children[i]; @@ -483,8 +483,7 @@ protected void getHandleMemento(StringBuffer buff) { PackageFragmentRoot root = getPackageFragmentRoot(); try { - if (root.isArchive() || - (( root instanceof LibraryFragmentRoot || (getParent() instanceof PackageFragment && ((PackageFragment)getParent()).getKind()==IPackageFragmentRoot.K_BINARY)) + if ((( root instanceof LibraryFragmentRoot || (getParent() instanceof PackageFragment && ((PackageFragment)getParent()).getKind()==IPackageFragmentRoot.K_BINARY)) && root.getPath().lastSegment().equalsIgnoreCase(getElementName())) ) { @@ -563,12 +562,12 @@ public ISourceRange getSourceRange() throws JavaScriptModelException { */ public String getTopLevelTypeName() { String topLevelTypeName = getElementName(); - int firstDollar = topLevelTypeName.indexOf('$'); - if (firstDollar != -1) { - topLevelTypeName = topLevelTypeName.substring(0, firstDollar); - } else { +// int firstDollar = topLevelTypeName.indexOf('$'); +// if (firstDollar != -1) { +// topLevelTypeName = topLevelTypeName.substring(0, firstDollar); +// } else { topLevelTypeName = topLevelTypeName.substring(0, topLevelTypeName.length()-SUFFIX_JAVA.length); - } +// } return topLevelTypeName; } /** @@ -582,8 +581,7 @@ public IType getType() { } public String getTypeName() { // Internal class file name doesn't contain ".class" file extension - int lastDollar = this.name.lastIndexOf('$'); - return lastDollar > -1 ? Util.localTypeName(this.name, lastDollar, this.name.length()) : this.name; + return this.name; } /* * @see IClassFile @@ -663,8 +661,23 @@ private IBuffer mapSource(SourceMapper mapper, IBinaryType info) { // resource not in workspace, use default encoding. } try { - contents=org.eclipse.wst.jsdt.internal.compiler.util.Util.getFileCharContent(new File(filePath.toOSString()),fileEncoding); + IPath rootpath = getAncestor(PACKAGE_FRAGMENT_ROOT).getPath(); + if (org.eclipse.wst.jsdt.internal.compiler.util.Util.isArchiveFileName(rootpath.lastSegment())) { + ZipFile zip = JavaModelManager.getJavaModelManager().getZipFile(rootpath); + String entryName = filePath.toString(); + if (!((IPackageFragment) getAncestor(PACKAGE_FRAGMENT)).isDefaultPackage()) { + entryName = ((IPackageFragment) getAncestor(PACKAGE_FRAGMENT)).getElementName() + "/" + entryName; //$NON-NLS-1$ + } + byte[] bytes = org.eclipse.wst.jsdt.internal.compiler.util.Util.getZipEntryByteContent(zip.getEntry(entryName), zip); + contents = org.eclipse.wst.jsdt.internal.compiler.util.Util.getInputStreamAsCharArray(new ByteArrayInputStream(bytes), bytes.length, fileEncoding); + } + else { + contents = org.eclipse.wst.jsdt.internal.compiler.util.Util.getFileCharContent(new File(filePath.toOSString()), fileEncoding); + } } catch (IOException ex){} + catch (CoreException e) { + e.printStackTrace(); + } //mapper.findSource(getType(), info); if (contents != null) { // create buffer @@ -701,11 +714,7 @@ private IBuffer mapSource(SourceMapper mapper, IBinaryType info) { if (className == null) return null; String simpleName = new String(unqualifiedName(className)); - int lastDollar = simpleName.lastIndexOf('$'); - if (lastDollar != -1) - return Util.localTypeName(simpleName, lastDollar, simpleName.length()); - else - return simpleName; + return simpleName; } /** * Returns the Java Model representation of the given name @@ -845,9 +854,31 @@ public IType[] getTypes() throws JavaScriptModelException { } char [] chars=null; try { - chars=org.eclipse.wst.jsdt.internal.compiler.util.Util.getFileCharContent(new File(filePath.toOSString()),fileEncoding); + if (name.indexOf(JAR_FILE_ENTRY_SEPARATOR) > 0) { + ZipFile zip = JavaModelManager.getJavaModelManager().getZipFile(getAncestor(PACKAGE_FRAGMENT_ROOT).getPath()); + String entryName = filePath.lastSegment().substring(name.indexOf(JAR_FILE_ENTRY_SEPARATOR)+1); + if(!((IPackageFragment)getAncestor(PACKAGE_FRAGMENT)).isDefaultPackage()) { + entryName = ((IPackageFragment)getAncestor(PACKAGE_FRAGMENT)).getElementName() + "/" + entryName; //$NON-NLS-1$ + } + byte[] bytes = org.eclipse.wst.jsdt.internal.compiler.util.Util.getZipEntryByteContent(zip.getEntry(entryName), zip); + chars = org.eclipse.wst.jsdt.internal.compiler.util.Util.getInputStreamAsCharArray(new ByteArrayInputStream(bytes), bytes.length, fileEncoding); + } + else if (org.eclipse.wst.jsdt.internal.compiler.util.Util.isArchiveFileName(getAncestor(PACKAGE_FRAGMENT_ROOT).getPath().lastSegment())) { + ZipFile zip = JavaModelManager.getJavaModelManager().getZipFile(getAncestor(PACKAGE_FRAGMENT_ROOT).getPath()); + String entryName = filePath.toString(); + if(!((IPackageFragment)getAncestor(PACKAGE_FRAGMENT)).isDefaultPackage()) { + entryName = ((IPackageFragment)getAncestor(PACKAGE_FRAGMENT)).getElementName() + "/" + entryName; //$NON-NLS-1$ + } + byte[] bytes = org.eclipse.wst.jsdt.internal.compiler.util.Util.getZipEntryByteContent(zip.getEntry(entryName), zip); + chars = org.eclipse.wst.jsdt.internal.compiler.util.Util.getInputStreamAsCharArray(new ByteArrayInputStream(bytes), bytes.length, fileEncoding); + } + else { + chars = org.eclipse.wst.jsdt.internal.compiler.util.Util.getFileCharContent(new File(filePath.toOSString()), fileEncoding); + } } catch (IOException e) { e.printStackTrace(); + } catch (CoreException e) { + e.printStackTrace(); } return chars; } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CompilationUnit.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CompilationUnit.java index 5cbe7762..6b87a5d0 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CompilationUnit.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CompilationUnit.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -51,7 +51,6 @@ import org.eclipse.wst.jsdt.core.JavaScriptCore; import org.eclipse.wst.jsdt.core.JavaScriptModelException; import org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer; import org.eclipse.wst.jsdt.core.LibrarySuperType; -import org.eclipse.wst.jsdt.core.Signature; import org.eclipse.wst.jsdt.core.WorkingCopyOwner; import org.eclipse.wst.jsdt.core.compiler.CategorizedProblem; import org.eclipse.wst.jsdt.core.compiler.CharOperation; @@ -81,1324 +80,1426 @@ public class CompilationUnit extends Openable implements IJavaScriptUnit, org.ec protected String name; public WorkingCopyOwner owner; public String superTypeName; + + /** + *

+ * true if currently making this unit consistent, + * false otherwise. + *

+ *

+ * Used to prevent + * {@link #makeConsistent(int, boolean, int, HashMap, IProgressMonitor)} + * from being called in an infinite loop. + *

+ * + * @see #makeConsistent(int, boolean, int, HashMap, IProgressMonitor) + */ + private volatile boolean fIsMakingConsistent; -/** - * Constructs a handle to a compilation unit with the given name in the - * specified package for the specified owner - */ -public CompilationUnit(PackageFragment parent, String name,String superTypeName, WorkingCopyOwner owner) { - super(parent); - this.name = name; - this.owner = owner; - this.superTypeName = superTypeName; -} - -public CompilationUnit(PackageFragment parent, String name, WorkingCopyOwner owner) { - this(parent,name,null,owner); -} - - -/* - * @see IJavaScriptUnit#becomeWorkingCopy(IProblemRequestor, IProgressMonitor) - */ -public void becomeWorkingCopy(IProblemRequestor problemRequestor, IProgressMonitor monitor) throws JavaScriptModelException { - JavaModelManager manager = JavaModelManager.getJavaModelManager(); - JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = manager.getPerWorkingCopyInfo(this, false/*don't create*/, true /*record usage*/, null/*no problem requestor needed*/); - if (perWorkingCopyInfo == null) { - // close cu and its children - close(); - - BecomeWorkingCopyOperation operation = new BecomeWorkingCopyOperation(this, problemRequestor); - operation.runOperation(monitor); - } -} -/* - * @see IJavaScriptUnit#becomeWorkingCopy(IProgressMonitor) - */ -public void becomeWorkingCopy(IProgressMonitor monitor) throws JavaScriptModelException { - IProblemRequestor requestor = this.owner == null ? null : this.owner.getProblemRequestor(this); - becomeWorkingCopy(requestor, monitor); -} -protected boolean buildStructure(OpenableElementInfo info, final IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaScriptModelException { - - // check if this compilation unit can be opened - if (!isWorkingCopy()) { // no check is done on root kind or exclusion pattern for working copies - IStatus status = validateCompilationUnit(underlyingResource); - if (!status.isOK()) throw newJavaModelException(status); - } - - // prevents reopening of non-primary working copies (they are closed when they are discarded and should not be reopened) - if (!isPrimary() && getPerWorkingCopyInfo() == null) { - throw newNotPresentException(); + /** + * Constructs a handle to a compilation unit with the given name in the + * specified package for the specified owner + */ + public CompilationUnit(PackageFragment parent, String name,String superTypeName, WorkingCopyOwner owner) { + super(parent); + this.name = name; + this.owner = owner; + this.superTypeName = superTypeName; + this.fIsMakingConsistent = false; } - - CompilationUnitElementInfo unitInfo = (CompilationUnitElementInfo) info; - - // get buffer contents - IBuffer buffer = getBufferManager().getBuffer(CompilationUnit.this); - if (buffer == null) { - buffer = openBuffer(pm, unitInfo); // open buffer independently from the info, since we are building the info - } - final char[] contents; - if (buffer == null) { - contents = CharOperation.NO_CHAR ; - } else { - char[] characters = buffer.getCharacters(); - contents = characters == null ? CharOperation.NO_CHAR : characters; + + public CompilationUnit(PackageFragment parent, String name, WorkingCopyOwner owner) { + this(parent,name,null,owner); } - - // generate structure and compute syntax problems if needed - CompilationUnitStructureRequestor requestor = new CompilationUnitStructureRequestor(this, unitInfo, newElements); - JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = getPerWorkingCopyInfo(); - IJavaScriptProject project = getJavaScriptProject(); - - boolean createAST; - boolean resolveBindings; - int reconcileFlags; - HashMap problems; - if (info instanceof ASTHolderCUInfo) { - ASTHolderCUInfo astHolder = (ASTHolderCUInfo) info; - createAST = astHolder.astLevel != NO_AST; - resolveBindings = astHolder.resolveBindings; - reconcileFlags = astHolder.reconcileFlags; - problems = astHolder.problems; - } else { - createAST = false; - resolveBindings = false; - reconcileFlags = 0; - problems = null; + + /* + * @see IJavaScriptUnit#becomeWorkingCopy(IProblemRequestor, IProgressMonitor) + */ + public void becomeWorkingCopy(IProblemRequestor problemRequestor, IProgressMonitor monitor) throws JavaScriptModelException { + JavaModelManager manager = JavaModelManager.getJavaModelManager(); + JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = manager.getPerWorkingCopyInfo(this, false/*don't create*/, true /*record usage*/, null/*no problem requestor needed*/); + if (perWorkingCopyInfo == null) { + // close cu and its children + close(); + + BecomeWorkingCopyOperation operation = new BecomeWorkingCopyOperation(this, problemRequestor); + operation.runOperation(monitor); + } } - - boolean computeProblems = perWorkingCopyInfo != null && perWorkingCopyInfo.isActive() && project != null && JavaProject.hasJavaNature(project.getProject()); - IProblemFactory problemFactory = new DefaultProblemFactory(); - Map options = project == null ? JavaScriptCore.getOptions() : project.getOptions(true); - if (!computeProblems) { - // disable task tags checking to speed up parsing - options.put(JavaScriptCore.COMPILER_TASK_TAGS, ""); //$NON-NLS-1$ - } - SourceElementParser parser = new SourceElementParser( - requestor, - problemFactory, - new CompilerOptions(options), - true/*report local declarations*/, - !createAST /*optimize string literals only if not creating a DOM AST*/); - parser.reportOnlyOneSyntaxError = !computeProblems; - parser.setMethodsFullRecovery(true); - parser.setStatementsRecovery((reconcileFlags & IJavaScriptUnit.ENABLE_STATEMENTS_RECOVERY) != 0); - -// if (!computeProblems && !resolveBindings && !createAST) // disable javadoc parsing if not computing problems, not resolving and not creating ast -// parser.javadocParser.checkDocComment = false; - requestor.parser = parser; - CompilationUnitDeclaration unit = parser.parseCompilationUnit( - new org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit() { - public char[] getContents() { - return contents; - } - public char[] getMainTypeName() { - return CompilationUnit.this.getMainTypeName(); - } - public char[][] getPackageName() { - return CompilationUnit.this.getPackageName(); - } - public char[] getFileName() { - return CompilationUnit.this.getFileName(); - } - public LibrarySuperType getCommonSuperType() { - return CompilationUnit.this.getCommonSuperType(); - } - public String getInferenceID() { - return CompilationUnit.this.getInferenceID(); - } - - - }, - true /*full parse to find local elements*/); - - // update timestamp (might be IResource.NULL_STAMP if original does not exist) - if (underlyingResource == null) { - underlyingResource = getResource(); + /* + * @see IJavaScriptUnit#becomeWorkingCopy(IProgressMonitor) + */ + public void becomeWorkingCopy(IProgressMonitor monitor) throws JavaScriptModelException { + IProblemRequestor requestor = this.owner == null ? null : this.owner.getProblemRequestor(this); + becomeWorkingCopy(requestor, monitor); } - // underlying resource is null in the case of a working copy on a class file in a jar - if (underlyingResource != null) - unitInfo.timestamp = ((IFile)underlyingResource).getModificationStamp(); - - // compute other problems if needed - CompilationUnitDeclaration compilationUnitDeclaration = null; - try { - if (computeProblems) { - if (problems == null) { - // report problems to the problem requestor - problems = new HashMap(); - compilationUnitDeclaration = CompilationUnitProblemFinder.process(unit, this, contents, parser, this.owner, problems, createAST, reconcileFlags, pm); - try { - perWorkingCopyInfo.beginReporting(); - for (Iterator iteraror = problems.values().iterator(); iteraror.hasNext();) { - CategorizedProblem[] categorizedProblems = (CategorizedProblem[]) iteraror.next(); - if (categorizedProblems == null) continue; - for (int i = 0, length = categorizedProblems.length; i < length; i++) { - perWorkingCopyInfo.acceptProblem(categorizedProblems[i]); + protected boolean buildStructure(OpenableElementInfo info, final IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaScriptModelException { + + // check if this compilation unit can be opened + if (!isWorkingCopy()) { // no check is done on root kind or exclusion pattern for working copies + IStatus status = validateCompilationUnit(underlyingResource); + if (!status.isOK()) throw newJavaModelException(status); + } + + // prevents reopening of non-primary working copies (they are closed when they are discarded and should not be reopened) + if (!isPrimary() && getPerWorkingCopyInfo() == null) { + throw newNotPresentException(); + } + + CompilationUnitElementInfo unitInfo = (CompilationUnitElementInfo) info; + + // get buffer contents + IBuffer buffer = getBufferManager().getBuffer(CompilationUnit.this); + if (buffer == null) { + buffer = openBuffer(pm, unitInfo); // open buffer independently from the info, since we are building the info + } + final char[] contents; + if (buffer == null) { + contents = CharOperation.NO_CHAR ; + } else { + char[] characters = buffer.getCharacters(); + contents = characters == null ? CharOperation.NO_CHAR : characters; + } + + // generate structure and compute syntax problems if needed + CompilationUnitStructureRequestor requestor = new CompilationUnitStructureRequestor(this, unitInfo, newElements); + JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = getPerWorkingCopyInfo(); + IJavaScriptProject project = getJavaScriptProject(); + + boolean createAST; + boolean resolveBindings; + int reconcileFlags; + HashMap problems; + if (info instanceof ASTHolderCUInfo) { + ASTHolderCUInfo astHolder = (ASTHolderCUInfo) info; + createAST = astHolder.astLevel != NO_AST; + resolveBindings = astHolder.resolveBindings; + reconcileFlags = astHolder.reconcileFlags; + problems = astHolder.problems; + } else { + createAST = false; + resolveBindings = false; + reconcileFlags = 0; + problems = null; + } + + boolean computeProblems = perWorkingCopyInfo != null && perWorkingCopyInfo.isActive() && project != null && JavaProject.hasJavaNature(project.getProject()); + IProblemFactory problemFactory = new DefaultProblemFactory(); + Map options = project == null ? JavaScriptCore.getOptions() : project.getOptions(true); + if (!computeProblems) { + // disable task tags checking to speed up parsing + options.put(JavaScriptCore.COMPILER_TASK_TAGS, ""); //$NON-NLS-1$ + } + SourceElementParser parser = new SourceElementParser( + requestor, + problemFactory, + new CompilerOptions(options), + true/*report local declarations*/, + !createAST /*optimize string literals only if not creating a DOM AST*/); + parser.reportOnlyOneSyntaxError = !computeProblems; + parser.setMethodsFullRecovery(true); + parser.setStatementsRecovery((reconcileFlags & IJavaScriptUnit.ENABLE_STATEMENTS_RECOVERY) != 0); + + requestor.parser = parser; + CompilationUnitDeclaration unit = parser.parseCompilationUnit( + new org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit() { + public char[] getContents() { + return contents; + } + public char[] getMainTypeName() { + return CompilationUnit.this.getMainTypeName(); + } + public char[][] getPackageName() { + return CompilationUnit.this.getPackageName(); + } + public char[] getFileName() { + return CompilationUnit.this.getFileName(); + } + public LibrarySuperType getCommonSuperType() { + return CompilationUnit.this.getCommonSuperType(); + } + public String getInferenceID() { + return CompilationUnit.this.getInferenceID(); + } + + + }, + true /*full parse to find local elements*/); + + // update timestamp (might be IResource.NULL_STAMP if original does not exist) + if (underlyingResource == null) { + underlyingResource = getResource(); + } + // underlying resource is null in the case of a working copy on a class file in a jar + if (underlyingResource != null) + unitInfo.timestamp = ((IFile)underlyingResource).getModificationStamp(); + + // compute other problems if needed + CompilationUnitDeclaration compilationUnitDeclaration = null; + try { + if (computeProblems) { + if (problems == null) { + // report problems to the problem requestor + problems = new HashMap(); + compilationUnitDeclaration = CompilationUnitProblemFinder.process(unit, this, contents, parser, this.owner, problems, createAST, reconcileFlags, pm); + try { + perWorkingCopyInfo.beginReporting(); + for (Iterator iteraror = problems.values().iterator(); iteraror.hasNext();) { + CategorizedProblem[] categorizedProblems = (CategorizedProblem[]) iteraror.next(); + if (categorizedProblems == null) continue; + for (int i = 0, length = categorizedProblems.length; i < length; i++) { + perWorkingCopyInfo.acceptProblem(categorizedProblems[i]); + } } + } finally { + perWorkingCopyInfo.endReporting(); } - } finally { - perWorkingCopyInfo.endReporting(); + } else { + // collect problems + compilationUnitDeclaration = CompilationUnitProblemFinder.process(unit, this, contents, parser, this.owner, problems, createAST, reconcileFlags, pm); } - } else { - // collect problems - compilationUnitDeclaration = CompilationUnitProblemFinder.process(unit, this, contents, parser, this.owner, problems, createAST, reconcileFlags, pm); } + + if (createAST) { + int astLevel = ((ASTHolderCUInfo) info).astLevel; + org.eclipse.wst.jsdt.core.dom.JavaScriptUnit cu = AST.convertCompilationUnit(astLevel, unit, contents, options, computeProblems, this, reconcileFlags, pm); + ((ASTHolderCUInfo) info).ast = cu; + } + } finally { + if (compilationUnitDeclaration != null) { + compilationUnitDeclaration.cleanUp(); + if (compilationUnitDeclaration.scope!=null) + compilationUnitDeclaration.scope.cleanup(); + } } - - if (createAST) { - int astLevel = ((ASTHolderCUInfo) info).astLevel; - org.eclipse.wst.jsdt.core.dom.JavaScriptUnit cu = AST.convertCompilationUnit(astLevel, unit, contents, options, computeProblems, this, reconcileFlags, pm); - ((ASTHolderCUInfo) info).ast = cu; + + return unitInfo.isStructureKnown(); + } + /* + * @see Openable#canBeRemovedFromCache + */ + public boolean canBeRemovedFromCache() { + if (getPerWorkingCopyInfo() != null) return false; // working copies should remain in the cache until they are destroyed + return super.canBeRemovedFromCache(); + } + /* + * @see Openable#canBufferBeRemovedFromCache + */ + public boolean canBufferBeRemovedFromCache(IBuffer buffer) { + if (getPerWorkingCopyInfo() != null) return false; // working copy buffers should remain in the cache until working copy is destroyed + return super.canBufferBeRemovedFromCache(buffer); + }/* + * @see org.eclipse.wst.jsdt.core.IOpenable#close + */ + public void close() throws JavaScriptModelException { + if (getPerWorkingCopyInfo() != null) return; // a working copy must remain opened until it is discarded + super.close(); + } + /* + * @see Openable#closing + */ + protected void closing(Object info) { + if (getPerWorkingCopyInfo() == null) { + super.closing(info); + } // else the buffer of a working copy must remain open for the lifetime of the working copy + } + /* (non-Javadoc) + * @see org.eclipse.wst.jsdt.core.ICodeAssist#codeComplete(int, org.eclipse.wst.jsdt.core.CompletionRequestor) + */ + public void codeComplete(int offset, CompletionRequestor requestor) throws JavaScriptModelException { + codeComplete(offset, requestor, DefaultWorkingCopyOwner.PRIMARY); + } + + /* (non-Javadoc) + * @see org.eclipse.wst.jsdt.core.ICodeAssist#codeComplete(int, org.eclipse.wst.jsdt.core.CompletionRequestor, org.eclipse.wst.jsdt.core.WorkingCopyOwner) + */ + public void codeComplete(int offset, CompletionRequestor requestor, WorkingCopyOwner workingCopyOwner) throws JavaScriptModelException { + codeComplete(this, isWorkingCopy() ? (org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit) getOriginalElement() : this, offset, requestor, workingCopyOwner); + } + + /** + * @see org.eclipse.wst.jsdt.core.ICodeAssist#codeSelect(int, int) + */ + public IJavaScriptElement[] codeSelect(int offset, int length) throws JavaScriptModelException { + return codeSelect(offset, length, DefaultWorkingCopyOwner.PRIMARY); + } + /** + * @see org.eclipse.wst.jsdt.core.ICodeAssist#codeSelect(int, int, WorkingCopyOwner) + */ + public IJavaScriptElement[] codeSelect(int offset, int length, WorkingCopyOwner workingCopyOwner) throws JavaScriptModelException { + return super.codeSelect(this, offset, length, workingCopyOwner); + } + /** + * @see org.eclipse.wst.jsdt.core.IWorkingCopy#commit(boolean, IProgressMonitor) + * @deprecated + */ + public void commit(boolean force, IProgressMonitor monitor) throws JavaScriptModelException { + commitWorkingCopy(force, monitor); + } + /** + * @see IJavaScriptUnit#commitWorkingCopy(boolean, IProgressMonitor) + */ + public void commitWorkingCopy(boolean force, IProgressMonitor monitor) throws JavaScriptModelException { + CommitWorkingCopyOperation op= new CommitWorkingCopyOperation(this, force); + op.runOperation(monitor); + } + /** + * @see org.eclipse.wst.jsdt.core.ISourceManipulation#copy(IJavaScriptElement, IJavaScriptElement, String, boolean, IProgressMonitor) + */ + public void copy(IJavaScriptElement container, IJavaScriptElement sibling, String rename, boolean force, IProgressMonitor monitor) throws JavaScriptModelException { + if (container == null) { + throw new IllegalArgumentException(Messages.operation_nullContainer); + } + IJavaScriptElement[] elements = new IJavaScriptElement[] {this}; + IJavaScriptElement[] containers = new IJavaScriptElement[] {container}; + String[] renamings = null; + if (rename != null) { + renamings = new String[] {rename}; } - } finally { - if (compilationUnitDeclaration != null) { - compilationUnitDeclaration.cleanUp(); - if (compilationUnitDeclaration.scope!=null) - compilationUnitDeclaration.scope.cleanup(); - } + getJavaScriptModel().copy(elements, containers, null, renamings, force, monitor); } - - return unitInfo.isStructureKnown(); -} -/* - * @see Openable#canBeRemovedFromCache - */ -public boolean canBeRemovedFromCache() { - if (getPerWorkingCopyInfo() != null) return false; // working copies should remain in the cache until they are destroyed - return super.canBeRemovedFromCache(); -} -/* - * @see Openable#canBufferBeRemovedFromCache - */ -public boolean canBufferBeRemovedFromCache(IBuffer buffer) { - if (getPerWorkingCopyInfo() != null) return false; // working copy buffers should remain in the cache until working copy is destroyed - return super.canBufferBeRemovedFromCache(buffer); -}/* - * @see org.eclipse.wst.jsdt.core.IOpenable#close - */ -public void close() throws JavaScriptModelException { - if (getPerWorkingCopyInfo() != null) return; // a working copy must remain opened until it is discarded - super.close(); -} -/* - * @see Openable#closing - */ -protected void closing(Object info) { - if (getPerWorkingCopyInfo() == null) { - super.closing(info); - } // else the buffer of a working copy must remain open for the lifetime of the working copy -} -/* (non-Javadoc) - * @see org.eclipse.wst.jsdt.core.ICodeAssist#codeComplete(int, org.eclipse.wst.jsdt.core.CompletionRequestor) - */ -public void codeComplete(int offset, CompletionRequestor requestor) throws JavaScriptModelException { - codeComplete(offset, requestor, DefaultWorkingCopyOwner.PRIMARY); -} - -/* (non-Javadoc) - * @see org.eclipse.wst.jsdt.core.ICodeAssist#codeComplete(int, org.eclipse.wst.jsdt.core.CompletionRequestor, org.eclipse.wst.jsdt.core.WorkingCopyOwner) - */ -public void codeComplete(int offset, CompletionRequestor requestor, WorkingCopyOwner workingCopyOwner) throws JavaScriptModelException { - codeComplete(this, isWorkingCopy() ? (org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit) getOriginalElement() : this, offset, requestor, workingCopyOwner); -} - -/** - * @see org.eclipse.wst.jsdt.core.ICodeAssist#codeSelect(int, int) - */ -public IJavaScriptElement[] codeSelect(int offset, int length) throws JavaScriptModelException { - return codeSelect(offset, length, DefaultWorkingCopyOwner.PRIMARY); -} -/** - * @see org.eclipse.wst.jsdt.core.ICodeAssist#codeSelect(int, int, WorkingCopyOwner) - */ -public IJavaScriptElement[] codeSelect(int offset, int length, WorkingCopyOwner workingCopyOwner) throws JavaScriptModelException { - return super.codeSelect(this, offset, length, workingCopyOwner); -} -/** - * @see org.eclipse.wst.jsdt.core.IWorkingCopy#commit(boolean, IProgressMonitor) - * @deprecated - */ -public void commit(boolean force, IProgressMonitor monitor) throws JavaScriptModelException { - commitWorkingCopy(force, monitor); -} -/** - * @see IJavaScriptUnit#commitWorkingCopy(boolean, IProgressMonitor) - */ -public void commitWorkingCopy(boolean force, IProgressMonitor monitor) throws JavaScriptModelException { - CommitWorkingCopyOperation op= new CommitWorkingCopyOperation(this, force); - op.runOperation(monitor); -} -/** - * @see org.eclipse.wst.jsdt.core.ISourceManipulation#copy(IJavaScriptElement, IJavaScriptElement, String, boolean, IProgressMonitor) - */ -public void copy(IJavaScriptElement container, IJavaScriptElement sibling, String rename, boolean force, IProgressMonitor monitor) throws JavaScriptModelException { - if (container == null) { - throw new IllegalArgumentException(Messages.operation_nullContainer); - } - IJavaScriptElement[] elements = new IJavaScriptElement[] {this}; - IJavaScriptElement[] containers = new IJavaScriptElement[] {container}; - String[] renamings = null; - if (rename != null) { - renamings = new String[] {rename}; - } - getJavaScriptModel().copy(elements, containers, null, renamings, force, monitor); -} -/** - * Returns a new element info for this element. - */ -protected Object createElementInfo() { - return new CompilationUnitElementInfo(); -} -/** - * @see IJavaScriptUnit#createImport(String, IJavaScriptElement, IProgressMonitor) - */ -public IImportDeclaration createImport(String importName, IJavaScriptElement sibling, IProgressMonitor monitor) throws JavaScriptModelException { - return createImport(importName, sibling, Flags.AccDefault, monitor); -} - -/** - * @see IJavaScriptUnit#createImport(String, IJavaScriptElement, int, IProgressMonitor) - * @since 3.0 - */ -public IImportDeclaration createImport(String importName, IJavaScriptElement sibling, int flags, IProgressMonitor monitor) throws JavaScriptModelException { - CreateImportOperation op = new CreateImportOperation(importName, this, flags); - if (sibling != null) { - op.createBefore(sibling); - } - op.runOperation(monitor); - return getImport(importName); -} - -/** - * @see IJavaScriptUnit#createType(String, IJavaScriptElement, boolean, IProgressMonitor) - */ -public IType createType(String content, IJavaScriptElement sibling, boolean force, IProgressMonitor monitor) throws JavaScriptModelException { - if (!exists()) { - //autogenerate this compilation unit - IPackageFragment pkg = (IPackageFragment) getParent(); - String source = ""; //$NON-NLS-1$ - if (!pkg.isDefaultPackage()) { - //not the default package...add the package declaration - String lineSeparator = Util.getLineSeparator(null/*no existing source*/, getJavaScriptProject()); - source = "package " + pkg.getElementName() + ";" + lineSeparator + lineSeparator; //$NON-NLS-1$ //$NON-NLS-2$ + /** + * Returns a new element info for this element. + */ + protected Object createElementInfo() { + return new CompilationUnitElementInfo(); + } + /** + * @see IJavaScriptUnit#createImport(String, IJavaScriptElement, IProgressMonitor) + */ + public IImportDeclaration createImport(String importName, IJavaScriptElement sibling, IProgressMonitor monitor) throws JavaScriptModelException { + return createImport(importName, sibling, Flags.AccDefault, monitor); + } + + /** + * @see IJavaScriptUnit#createImport(String, IJavaScriptElement, int, IProgressMonitor) + * @since 3.0 + */ + public IImportDeclaration createImport(String importName, IJavaScriptElement sibling, int flags, IProgressMonitor monitor) throws JavaScriptModelException { + CreateImportOperation op = new CreateImportOperation(importName, this, flags); + if (sibling != null) { + op.createBefore(sibling); } - CreateCompilationUnitOperation op = new CreateCompilationUnitOperation(pkg, this.name, source, force); op.runOperation(monitor); + return getImport(importName); } - CreateTypeOperation op = new CreateTypeOperation(this, content, force); - if (sibling != null) { - op.createBefore(sibling); + + /** + * @see IJavaScriptUnit#createType(String, IJavaScriptElement, boolean, IProgressMonitor) + */ + public IType createType(String content, IJavaScriptElement sibling, boolean force, IProgressMonitor monitor) throws JavaScriptModelException { + if (!exists()) { + //autogenerate this compilation unit + IPackageFragment pkg = (IPackageFragment) getParent(); + String source = ""; //$NON-NLS-1$ + if (!pkg.isDefaultPackage()) { + //not the default package...add the package declaration + String lineSeparator = Util.getLineSeparator(null/*no existing source*/, getJavaScriptProject()); + source = "package " + pkg.getElementName() + ";" + lineSeparator + lineSeparator; //$NON-NLS-1$ //$NON-NLS-2$ + } + CreateCompilationUnitOperation op = new CreateCompilationUnitOperation(pkg, this.name, source, force); + op.runOperation(monitor); + } + CreateTypeOperation op = new CreateTypeOperation(this, content, force); + if (sibling != null) { + op.createBefore(sibling); + } + op.runOperation(monitor); + return (IType) op.getResultElements()[0]; } - op.runOperation(monitor); - return (IType) op.getResultElements()[0]; -} -/** - * @see org.eclipse.wst.jsdt.core.ISourceManipulation#delete(boolean, IProgressMonitor) - */ -public void delete(boolean force, IProgressMonitor monitor) throws JavaScriptModelException { - IJavaScriptElement[] elements= new IJavaScriptElement[] {this}; - getJavaScriptModel().delete(elements, force, monitor); -} -/** - * @see org.eclipse.wst.jsdt.core.IWorkingCopy#destroy() - * @deprecated - */ -public void destroy() { - try { - discardWorkingCopy(); - } catch (JavaScriptModelException e) { - if (JavaModelManager.VERBOSE) - e.printStackTrace(); - } -} -/* - * @see IJavaScriptUnit#discardWorkingCopy - */ -public void discardWorkingCopy() throws JavaScriptModelException { - // discard working copy and its children - DiscardWorkingCopyOperation op = new DiscardWorkingCopyOperation(this); - op.runOperation(null); -} -/** - * Returns true if this handle represents the same Java element - * as the given handle. - * - * @see Object#equals(java.lang.Object) - */ -public boolean equals(Object obj) { - if (!(obj instanceof CompilationUnit)) return false; - CompilationUnit other = (CompilationUnit)obj; - return this.owner.equals(other.owner) && super.equals(obj); -} -public boolean exists() { - // working copy always exists in the model until it is gotten rid of (even if not on classpath) - if (getPerWorkingCopyInfo() != null) return true; - - // if not a working copy, it exists only if it is a primary compilation unit - return isPrimary() && validateCompilationUnit(getResource()).isOK(); -} -/** - * @see IJavaScriptUnit#findElements(IJavaScriptElement) - */ -public IJavaScriptElement[] findElements(IJavaScriptElement element) { - ArrayList children = new ArrayList(); - while (element != null && element.getElementType() != IJavaScriptElement.JAVASCRIPT_UNIT) { - children.add(element); - element = element.getParent(); - } - if (element == null) return null; - IJavaScriptElement currentElement = this; - for (int i = children.size()-1; i >= 0; i--) { - SourceRefElement child = (SourceRefElement)children.get(i); - switch (child.getElementType()) { - case IJavaScriptElement.IMPORT_CONTAINER: - currentElement = ((IJavaScriptUnit)currentElement).getImportContainer(); - break; - case IJavaScriptElement.IMPORT_DECLARATION: - currentElement = ((IImportContainer)currentElement).getImport(child.getElementName()); - break; - case IJavaScriptElement.TYPE: - switch (currentElement.getElementType()) { - case IJavaScriptElement.JAVASCRIPT_UNIT: - currentElement = ((IJavaScriptUnit)currentElement).getType(child.getElementName()); - break; - case IJavaScriptElement.TYPE: - currentElement = ((IType)currentElement).getType(child.getElementName()); - break; - case IJavaScriptElement.FIELD: - case IJavaScriptElement.INITIALIZER: - case IJavaScriptElement.METHOD: - currentElement = ((IMember)currentElement).getType(child.getElementName(), child.occurrenceCount); - break; - } - break; - case IJavaScriptElement.INITIALIZER: - currentElement = ((IType)currentElement).getInitializer(child.occurrenceCount); - break; - case IJavaScriptElement.FIELD: - if (currentElement instanceof CompilationUnit) - currentElement = ((CompilationUnit)currentElement).getField(child.getElementName()); - else - if (currentElement instanceof IType) - currentElement = ((IType)currentElement).getField(child.getElementName()); - break; - case IJavaScriptElement.METHOD: - if (currentElement instanceof CompilationUnit) - currentElement = ((CompilationUnit)currentElement).getFunction(child.getElementName(), ((IFunction)child).getParameterTypes()); - else if (currentElement instanceof SourceMethod) - currentElement = ((SourceMethod)currentElement).getFunction(child.getElementName(), ((IFunction)child).getParameterTypes()); - else - currentElement = ((IType)currentElement).getFunction(child.getElementName(), ((IFunction)child).getParameterTypes()); - break; + /** + * @see org.eclipse.wst.jsdt.core.ISourceManipulation#delete(boolean, IProgressMonitor) + */ + public void delete(boolean force, IProgressMonitor monitor) throws JavaScriptModelException { + IJavaScriptElement[] elements= new IJavaScriptElement[] {this}; + getJavaScriptModel().delete(elements, force, monitor); + } + /** + * @see org.eclipse.wst.jsdt.core.IWorkingCopy#destroy() + * @deprecated + */ + public void destroy() { + try { + discardWorkingCopy(); + } catch (JavaScriptModelException e) { + if (JavaModelManager.VERBOSE) + e.printStackTrace(); } - } - if (currentElement != null && currentElement.exists()) { - return new IJavaScriptElement[] {currentElement}; - } else { - return null; + + /* + * @see IJavaScriptUnit#discardWorkingCopy + */ + public void discardWorkingCopy() throws JavaScriptModelException { + // discard working copy and its children + DiscardWorkingCopyOperation op = new DiscardWorkingCopyOperation(this); + op.runOperation(null); } -} -/** - * @see IJavaScriptUnit#findPrimaryType() - */ -public IType findPrimaryType() { - String typeName = Util.getNameWithoutJavaLikeExtension(getElementName()); - IType primaryType= getType(typeName); - if (primaryType.exists()) { - return primaryType; - } - return null; -} - -/** - * @see org.eclipse.wst.jsdt.core.IWorkingCopy#findSharedWorkingCopy(IBufferFactory) - * @deprecated - */ -public IJavaScriptElement findSharedWorkingCopy(IBufferFactory factory) { - - // if factory is null, default factory must be used - if (factory == null) factory = this.getBufferManager().getDefaultBufferFactory(); - - return findWorkingCopy(BufferFactoryWrapper.create(factory)); -} - -/** - * @see IJavaScriptUnit#findWorkingCopy(WorkingCopyOwner) - */ -public IJavaScriptUnit findWorkingCopy(WorkingCopyOwner workingCopyOwner) { - CompilationUnit cu = new CompilationUnit((PackageFragment)this.parent, getElementName(), workingCopyOwner); - if (workingCopyOwner == DefaultWorkingCopyOwner.PRIMARY) { - return cu; - } else { - // must be a working copy - JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = cu.getPerWorkingCopyInfo(); - if (perWorkingCopyInfo != null) { - return perWorkingCopyInfo.getWorkingCopy(); + + /** + * Returns true if this handle represents the same Java element + * as the given handle. + * + * @see Object#equals(java.lang.Object) + */ + public boolean equals(Object obj) { + if (!(obj instanceof CompilationUnit)) return false; + CompilationUnit other = (CompilationUnit)obj; + return this.owner.equals(other.owner) && super.equals(obj); + } + public boolean exists() { + // working copy always exists in the model until it is gotten rid of (even if not on classpath) + if (getPerWorkingCopyInfo() != null) return true; + + // if not a working copy, it exists only if it is a primary compilation unit + return isPrimary() && validateCompilationUnit(getResource()).isOK(); + } + + /** + * @see IJavaScriptUnit#findElements(IJavaScriptElement) + */ + public IJavaScriptElement[] findElements(IJavaScriptElement element) { + ArrayList children = new ArrayList(); + while (element != null && element.getElementType() != IJavaScriptElement.JAVASCRIPT_UNIT) { + children.add(element); + element = element.getParent(); + } + if (element == null) return null; + IJavaScriptElement currentElement = this; + for (int i = children.size()-1; i >= 0; i--) { + SourceRefElement child = (SourceRefElement)children.get(i); + switch (child.getElementType()) { + case IJavaScriptElement.IMPORT_CONTAINER: + currentElement = ((IJavaScriptUnit)currentElement).getImportContainer(); + break; + case IJavaScriptElement.IMPORT_DECLARATION: + currentElement = ((IImportContainer)currentElement).getImport(child.getElementName()); + break; + case IJavaScriptElement.TYPE: + switch (currentElement.getElementType()) { + case IJavaScriptElement.JAVASCRIPT_UNIT: + currentElement = ((IJavaScriptUnit)currentElement).getType(child.getElementName()); + break; + case IJavaScriptElement.TYPE: + currentElement = ((IType)currentElement).getType(child.getElementName()); + break; + case IJavaScriptElement.FIELD: + case IJavaScriptElement.INITIALIZER: + case IJavaScriptElement.METHOD: + currentElement = ((IMember)currentElement).getType(child.getElementName(), child.occurrenceCount); + break; + } + break; + case IJavaScriptElement.INITIALIZER: + currentElement = ((IType)currentElement).getInitializer(child.occurrenceCount); + break; + case IJavaScriptElement.FIELD: + if (currentElement instanceof CompilationUnit) + currentElement = ((CompilationUnit)currentElement).getField(child.getElementName()); + else + if (currentElement instanceof IType) + currentElement = ((IType)currentElement).getField(child.getElementName()); + break; + case IJavaScriptElement.METHOD: + if (currentElement instanceof CompilationUnit) + currentElement = ((CompilationUnit)currentElement).getFunction(child.getElementName(), ((IFunction)child).getParameterTypes()); + else if (currentElement instanceof SourceMethod) + currentElement = ((SourceMethod)currentElement).getFunction(child.getElementName(), ((IFunction)child).getParameterTypes()); + else + currentElement = ((IType)currentElement).getFunction(child.getElementName(), ((IFunction)child).getParameterTypes()); + break; + } + + } + if (currentElement != null && currentElement.exists()) { + return new IJavaScriptElement[] {currentElement}; } else { return null; } } -} -/** - * @see IJavaScriptUnit#getAllTypes() - */ -public IType[] getAllTypes() throws JavaScriptModelException { - IJavaScriptElement[] types = getTypes(); - int i; - ArrayList allTypes = new ArrayList(types.length); - ArrayList typesToTraverse = new ArrayList(types.length); - for (i = 0; i < types.length; i++) { - typesToTraverse.add(types[i]); - } - while (!typesToTraverse.isEmpty()) { - IType type = (IType) typesToTraverse.get(0); - typesToTraverse.remove(type); - allTypes.add(type); - types = type.getTypes(); + + /** + * @see IJavaScriptUnit#findPrimaryType() + */ + public IType findPrimaryType() { + String typeName = Util.getNameWithoutJavaLikeExtension(getElementName()); + IType primaryType= getType(typeName); + if (primaryType.exists()) { + return primaryType; + } + return null; + } + + /** + * @see org.eclipse.wst.jsdt.core.IWorkingCopy#findSharedWorkingCopy(IBufferFactory) + * @deprecated + */ + public IJavaScriptElement findSharedWorkingCopy(IBufferFactory factory) { + + // if factory is null, default factory must be used + if (factory == null) factory = this.getBufferManager().getDefaultBufferFactory(); + + return findWorkingCopy(BufferFactoryWrapper.create(factory)); + } + + /** + * @see IJavaScriptUnit#findWorkingCopy(WorkingCopyOwner) + */ + public IJavaScriptUnit findWorkingCopy(WorkingCopyOwner workingCopyOwner) { + CompilationUnit cu = new CompilationUnit((PackageFragment)this.parent, getElementName(), workingCopyOwner); + if (workingCopyOwner == DefaultWorkingCopyOwner.PRIMARY) { + return cu; + } else { + // must be a working copy + JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = cu.getPerWorkingCopyInfo(); + if (perWorkingCopyInfo != null) { + return perWorkingCopyInfo.getWorkingCopy(); + } else { + return null; + } + } + } + + /** + * @see IJavaScriptUnit#getAllTypes() + */ + public IType[] getAllTypes() throws JavaScriptModelException { + IJavaScriptElement[] types = getTypes(); + int i; + ArrayList allTypes = new ArrayList(types.length); + ArrayList typesToTraverse = new ArrayList(types.length); for (i = 0; i < types.length; i++) { typesToTraverse.add(types[i]); } + while (!typesToTraverse.isEmpty()) { + IType type = (IType) typesToTraverse.get(0); + typesToTraverse.remove(type); + allTypes.add(type); + types = type.getTypes(); + for (i = 0; i < types.length; i++) { + typesToTraverse.add(types[i]); + } + } + IType[] arrayOfAllTypes = new IType[allTypes.size()]; + allTypes.toArray(arrayOfAllTypes); + return arrayOfAllTypes; } - IType[] arrayOfAllTypes = new IType[allTypes.size()]; - allTypes.toArray(arrayOfAllTypes); - return arrayOfAllTypes; -} -/** - * @see IMember#getCompilationUnit() - * @deprecated Use {@link #getJavaScriptUnit()} instead - */ -public IJavaScriptUnit getCompilationUnit() { - return getJavaScriptUnit(); -} - -/** - * @see IMember#getJavaScriptUnit() - */ -public IJavaScriptUnit getJavaScriptUnit() { - return this; -} -/** - * @see org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit#getContents() - */ -public char[] getContents() { - IBuffer buffer = getBufferManager().getBuffer(this); - if (buffer == null) { - // no need to force opening of CU to get the content - // also this cannot be a working copy, as its buffer is never closed while the working copy is alive - try { - return Util.getResourceContentsAsCharArray((IFile) getResource()); - } catch (JavaScriptModelException e) { + + /** + * @see IMember#getCompilationUnit() + * @deprecated Use {@link #getJavaScriptUnit()} instead + */ + public IJavaScriptUnit getCompilationUnit() { + return getJavaScriptUnit(); + } + + /** + * @see IMember#getJavaScriptUnit() + */ + public IJavaScriptUnit getJavaScriptUnit() { + return this; + } + + /** + * @see org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit#getContents() + */ + public char[] getContents() { + IBuffer buffer = getBufferManager().getBuffer(this); + if (buffer == null) { + // no need to force opening of CU to get the content + // also this cannot be a working copy, as its buffer is never closed while the working copy is alive + try { + return Util.getResourceContentsAsCharArray((IFile) getResource()); + } catch (JavaScriptModelException e) { + return CharOperation.NO_CHAR; + } + } + char[] contents = buffer.getCharacters(); + if (contents == null) // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=129814 return CharOperation.NO_CHAR; + return contents; + } + /** + * A compilation unit has a corresponding resource unless it is contained + * in a jar. + * + * @see IJavaScriptElement#getCorrespondingResource() + */ + public IResource getCorrespondingResource() throws JavaScriptModelException { + PackageFragmentRoot root = getPackageFragmentRoot(); + if (root == null || root.isArchive()) { + return null; + } else { + return getUnderlyingResource(); } } - char[] contents = buffer.getCharacters(); - if (contents == null) // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=129814 - return CharOperation.NO_CHAR; - return contents; -} -/** - * A compilation unit has a corresponding resource unless it is contained - * in a jar. - * - * @see IJavaScriptElement#getCorrespondingResource() - */ -public IResource getCorrespondingResource() throws JavaScriptModelException { - PackageFragmentRoot root = getPackageFragmentRoot(); - if (root == null || root.isArchive()) { - return null; - } else { - return getUnderlyingResource(); + + /** + * @see IJavaScriptUnit#getElementAt(int) + */ + public IJavaScriptElement getElementAt(int position) throws JavaScriptModelException { + + IJavaScriptElement e= getSourceElementAt(position); + if (e == this) { + return null; + } else { + return e; + } } -} -/** - * @see IJavaScriptUnit#getElementAt(int) - */ -public IJavaScriptElement getElementAt(int position) throws JavaScriptModelException { - - IJavaScriptElement e= getSourceElementAt(position); - if (e == this) { - return null; - } else { - return e; + + public String getElementName() { + return this.name; } -} -public String getElementName() { - return this.name; -} -/** - * @see IJavaScriptElement - */ -public int getElementType() { - return JAVASCRIPT_UNIT; -} -/** - * @see org.eclipse.wst.jsdt.internal.compiler.env.IDependent#getFileName() - */ -public char[] getFileName(){ - if (name.startsWith("http:")) //$NON-NLS-1$ - return name.toCharArray(); - return getPath().toString().toCharArray(); -} - -/* - * @see JavaElement - */ -public IJavaScriptElement getHandleFromMemento(String token, MementoTokenizer memento, WorkingCopyOwner workingCopyOwner) { - switch (token.charAt(0)) { - case JEM_IMPORTDECLARATION: - JavaElement container = (JavaElement)getImportContainer(); - return container.getHandleFromMemento(token, memento, workingCopyOwner); - case JEM_TYPE: - if (!memento.hasMoreTokens()) return this; - String typeName = memento.nextToken(); - JavaElement type = (JavaElement)getType(typeName); - return type.getHandleFromMemento(memento, workingCopyOwner); - - - case JEM_FIELD: - if (!memento.hasMoreTokens()) return this; - String fieldName = memento.nextToken(); - JavaElement field = (JavaElement)getField(fieldName); - return field.getHandleFromMemento(memento, workingCopyOwner); - - case JEM_LOCALVARIABLE: - if (!memento.hasMoreTokens()) return this; - String varName = memento.nextToken(); - if (!memento.hasMoreTokens()) return this; - memento.nextToken(); // JEM_COUNT - if (!memento.hasMoreTokens()) return this; - int declarationStart = Integer.parseInt(memento.nextToken()); - if (!memento.hasMoreTokens()) return this; - memento.nextToken(); // JEM_COUNT - if (!memento.hasMoreTokens()) return this; - int declarationEnd = Integer.parseInt(memento.nextToken()); - if (!memento.hasMoreTokens()) return this; - memento.nextToken(); // JEM_COUNT - if (!memento.hasMoreTokens()) return this; - int nameStart = Integer.parseInt(memento.nextToken()); - if (!memento.hasMoreTokens()) return this; - memento.nextToken(); // JEM_COUNT - if (!memento.hasMoreTokens()) return this; - int nameEnd = Integer.parseInt(memento.nextToken()); - if (!memento.hasMoreTokens()) return this; - memento.nextToken(); // JEM_COUNT - if (!memento.hasMoreTokens()) return this; - String typeSignature = memento.nextToken(); - return new LocalVariable(this, varName, declarationStart, declarationEnd, nameStart, nameEnd, typeSignature); - - case JEM_METHOD: - if (!memento.hasMoreTokens()) return this; - String selector = memento.nextToken(); - ArrayList params = new ArrayList(); - nextParam: while (memento.hasMoreTokens()) { - token = memento.nextToken(); + + /** + * @see IJavaScriptElement + */ + public int getElementType() { + return JAVASCRIPT_UNIT; + } + + /** + * @see org.eclipse.wst.jsdt.internal.compiler.env.IDependent#getFileName() + */ + public char[] getFileName(){ + if (name.startsWith("http:")) //$NON-NLS-1$ + return name.toCharArray(); + return getPath().toString().toCharArray(); + } + + /* + * @see JavaElement + */ + public IJavaScriptElement getHandleFromMemento(String token, MementoTokenizer memento, WorkingCopyOwner workingCopyOwner) { + switch (token.charAt(0)) { + case JEM_IMPORTDECLARATION: + JavaElement container = (JavaElement)getImportContainer(); + return container.getHandleFromMemento(token, memento, workingCopyOwner); + case JEM_TYPE: + if (!memento.hasMoreTokens()) return this; + String typeName = memento.nextToken(); + JavaElement type = (JavaElement)getType(typeName); + return type.getHandleFromMemento(memento, workingCopyOwner); + + + case JEM_FIELD: + if (!memento.hasMoreTokens()) return this; + String fieldName = memento.nextToken(); + JavaElement field = (JavaElement)getField(fieldName); + return field.getHandleFromMemento(memento, workingCopyOwner); + + case JEM_LOCALVARIABLE: + if (!memento.hasMoreTokens()) return this; + String varName = memento.nextToken(); + if (!memento.hasMoreTokens()) return this; + memento.nextToken(); // JEM_COUNT + if (!memento.hasMoreTokens()) return this; + int declarationStart = Integer.parseInt(memento.nextToken()); + if (!memento.hasMoreTokens()) return this; + memento.nextToken(); // JEM_COUNT + if (!memento.hasMoreTokens()) return this; + int declarationEnd = Integer.parseInt(memento.nextToken()); + if (!memento.hasMoreTokens()) return this; + memento.nextToken(); // JEM_COUNT + if (!memento.hasMoreTokens()) return this; + int nameStart = Integer.parseInt(memento.nextToken()); + if (!memento.hasMoreTokens()) return this; + memento.nextToken(); // JEM_COUNT + if (!memento.hasMoreTokens()) return this; + int nameEnd = Integer.parseInt(memento.nextToken()); + if (!memento.hasMoreTokens()) return this; + memento.nextToken(); // JEM_COUNT + if (!memento.hasMoreTokens()) return this; + String typeSignature = memento.nextToken(); + return new LocalVariable(this, varName, declarationStart, declarationEnd, nameStart, nameEnd, typeSignature); + + case JEM_METHOD: + if (!memento.hasMoreTokens()) return this; + String selector = memento.nextToken(); + ArrayList params = new ArrayList(); + nextParam: while (memento.hasMoreTokens()) { + token = memento.nextToken(); + switch (token.charAt(0)) { + case JEM_TYPE: + case JEM_TYPE_PARAMETER: + break nextParam; +// case JEM_METHOD: +// if (!memento.hasMoreTokens()) return this; +// String param = memento.nextToken(); +// StringBuffer buffer = new StringBuffer(); +// while (param.length() == 1 && Signature.C_ARRAY == param.charAt(0)) { // backward compatible with 3.0 mementos +// buffer.append(Signature.C_ARRAY); +// if (!memento.hasMoreTokens()) return this; +// param = memento.nextToken(); +// } +// params.add(buffer.toString() + param); +// break; + default: + break nextParam; + } + } + String[] parameters = new String[params.size()]; + params.toArray(parameters); + JavaElement method = (JavaElement)getFunction(selector, parameters); + if (token.charAt(0) == JEM_COUNT) { + if (!memento.hasMoreTokens()) return method; + memento.nextToken(); // JEM_COUNT + if (!memento.hasMoreTokens()) return method; + token = memento.nextToken(); + } switch (token.charAt(0)) { case JEM_TYPE: case JEM_TYPE_PARAMETER: - break nextParam; + case JEM_LOCALVARIABLE: + return method.getHandleFromMemento(token, memento, workingCopyOwner); case JEM_METHOD: - if (!memento.hasMoreTokens()) return this; - String param = memento.nextToken(); - StringBuffer buffer = new StringBuffer(); - while (param.length() == 1 && Signature.C_ARRAY == param.charAt(0)) { // backward compatible with 3.0 mementos - buffer.append(Signature.C_ARRAY); - if (!memento.hasMoreTokens()) return this; - param = memento.nextToken(); - } - params.add(buffer.toString() + param); - break; + if (memento.hasMoreTokens()) + return method.getHandleFromMemento(token, memento, workingCopyOwner); default: - break nextParam; + return method; } - } - String[] parameters = new String[params.size()]; - params.toArray(parameters); - JavaElement method = (JavaElement)getFunction(selector, parameters); - switch (token.charAt(0)) { - case JEM_TYPE: - case JEM_TYPE_PARAMETER: - case JEM_LOCALVARIABLE: - return method.getHandleFromMemento(token, memento, workingCopyOwner); - default: - return method; - } - + } + return null; } - return null; -} - -/** - * @see JavaElement#getHandleMementoDelimiter() - */ -protected char getHandleMementoDelimiter() { - return JavaElement.JEM_COMPILATIONUNIT; -} -/** - * @see IJavaScriptUnit#getImport(String) - */ -public IImportDeclaration getImport(String importName) { - return getImportContainer().getImport(importName); -} -/** - * @see IJavaScriptUnit#getImportContainer() - */ -public IImportContainer getImportContainer() { - return new ImportContainer(this); -} - - -/** - * @see IJavaScriptUnit#getImports() - */ -public IImportDeclaration[] getImports() throws JavaScriptModelException { - IImportContainer container= getImportContainer(); - JavaModelManager manager = JavaModelManager.getJavaModelManager(); - Object info = manager.getInfo(container); - if (info == null) { - if (manager.getInfo(this) != null) - // CU was opened, but no import container, then no imports - return NO_IMPORTS; - else { - open(null); // force opening of CU - info = manager.getInfo(container); - if (info == null) - // after opening, if no import container, then no imports + + /** + * @see JavaElement#getHandleMementoDelimiter() + */ + protected char getHandleMementoDelimiter() { + return JavaElement.JEM_COMPILATIONUNIT; + } + + /** + * @see IJavaScriptUnit#getImport(String) + */ + public IImportDeclaration getImport(String importName) { + return getImportContainer().getImport(importName); + } + + /** + * @see IJavaScriptUnit#getImportContainer() + */ + public IImportContainer getImportContainer() { + return new ImportContainer(this); + } + + /** + * @see IJavaScriptUnit#getImports() + */ + public IImportDeclaration[] getImports() throws JavaScriptModelException { + IImportContainer container= getImportContainer(); + JavaModelManager manager = JavaModelManager.getJavaModelManager(); + Object info = manager.getInfo(container); + if (info == null) { + if (manager.getInfo(this) != null) + // CU was opened, but no import container, then no imports return NO_IMPORTS; + else { + open(null); // force opening of CU + info = manager.getInfo(container); + if (info == null) + // after opening, if no import container, then no imports + return NO_IMPORTS; + } } + IJavaScriptElement[] elements = ((JavaElementInfo) info).children; + int length = elements.length; + IImportDeclaration[] imports = new IImportDeclaration[length]; + System.arraycopy(elements, 0, imports, 0, length); + return imports; } - IJavaScriptElement[] elements = ((JavaElementInfo) info).children; - int length = elements.length; - IImportDeclaration[] imports = new IImportDeclaration[length]; - System.arraycopy(elements, 0, imports, 0, length); - return imports; -} -/** - * @see IMember#getTypeRoot() - */ -public ITypeRoot getTypeRoot() { - return this; -} -/** - * @see org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit#getMainTypeName() - */ -public char[] getMainTypeName(){ - return Util.getNameWithoutJavaLikeExtension(getElementName()).toCharArray(); -} -/** - * @see org.eclipse.wst.jsdt.core.IWorkingCopy#getOriginal(IJavaScriptElement) - * @deprecated - */ -public IJavaScriptElement getOriginal(IJavaScriptElement workingCopyElement) { - // backward compatibility - if (!isWorkingCopy()) return null; - CompilationUnit cu = (CompilationUnit)workingCopyElement.getAncestor(JAVASCRIPT_UNIT); - if (cu == null || !this.owner.equals(cu.owner)) { - return null; + + /** + * @see IMember#getTypeRoot() + */ + public ITypeRoot getTypeRoot() { + return this; } - - return workingCopyElement.getPrimaryElement(); -} -/** - * @see org.eclipse.wst.jsdt.core.IWorkingCopy#getOriginalElement() - * @deprecated - */ -public IJavaScriptElement getOriginalElement() { - // backward compatibility - if (!isWorkingCopy()) return null; - - return getPrimaryElement(); -} -/* - * @see IJavaScriptUnit#getOwner() - */ -public WorkingCopyOwner getOwner() { - return isPrimary() || !isWorkingCopy() ? null : this.owner; -} - -/** - * @see org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit#getPackageName() - */ -public char[][] getPackageName() { - PackageFragment packageFragment = (PackageFragment) getParent(); - if (packageFragment == null) return CharOperation.NO_CHAR_CHAR; - return Util.toCharArrays(packageFragment.names); -} - -/** - * @see IJavaScriptElement#getPath() - */ -public IPath getPath() { - PackageFragmentRoot root = getPackageFragmentRoot(); - if (root == null) return new Path(getElementName()); // working copy not in workspace - if (root.isArchive()) { - return root.getPath(); - } else { - return getParent().getPath().append(getElementName()); - } -} -/* - * Returns the per working copy info for the receiver, or null if none exist. - * Note: the use count of the per working copy info is NOT incremented. - */ -public JavaModelManager.PerWorkingCopyInfo getPerWorkingCopyInfo() { - return JavaModelManager.getJavaModelManager().getPerWorkingCopyInfo(this, false/*don't create*/, false/*don't record usage*/, null/*no problem requestor needed*/); -} -/* - * @see IJavaScriptUnit#getPrimary() - */ -public IJavaScriptUnit getPrimary() { - return (IJavaScriptUnit)getPrimaryElement(true); -} -/* - * @see JavaElement#getPrimaryElement(boolean) - */ -public IJavaScriptElement getPrimaryElement(boolean checkOwner) { - if (checkOwner && isPrimary()) return this; - return new CompilationUnit((PackageFragment)getParent(), getElementName(), DefaultWorkingCopyOwner.PRIMARY); -} -/** - * @see IJavaScriptElement#getResource() - */ -public IResource getResource() { - PackageFragmentRoot root = getPackageFragmentRoot(); - if (root == null) return null; // working copy not in workspace - if (root.isArchive()) { - return root.getResource(); - } else { - IContainer parentResource = (IContainer) getParent().getResource(); - if (parentResource!=null) - return parentResource.getFile(new Path(getElementName())); - } - return null; -} -/** - * @see org.eclipse.wst.jsdt.core.ISourceReference#getSource() - */ -public String getSource() throws JavaScriptModelException { - IBuffer buffer = getBuffer(); - if (buffer == null) return ""; //$NON-NLS-1$ - return buffer.getContents(); -} -/** - * @see org.eclipse.wst.jsdt.core.ISourceReference#getSourceRange() - */ -public ISourceRange getSourceRange() throws JavaScriptModelException { - return ((CompilationUnitElementInfo) getElementInfo()).getSourceRange(); -} -/** - * @see IJavaScriptUnit#getType(String) - */ -public IType getType(String typeName) { - return new SourceType(this, typeName); -} -/** - * @see IJavaScriptUnit#getTypes() - */ -public IType[] getTypes() throws JavaScriptModelException { - ArrayList list = getChildrenOfType(TYPE); - IType[] array= new IType[list.size()]; - list.toArray(array); - return array; -} -/** - * @see IJavaScriptElement - */ -public IResource getUnderlyingResource() throws JavaScriptModelException { - if (isWorkingCopy() && !isPrimary()) return null; - return super.getUnderlyingResource(); -} -/** - * @see org.eclipse.wst.jsdt.core.IWorkingCopy#getSharedWorkingCopy(IProgressMonitor, IBufferFactory, IProblemRequestor) - * @deprecated - */ -public IJavaScriptElement getSharedWorkingCopy(IProgressMonitor pm, IBufferFactory factory, IProblemRequestor problemRequestor) throws JavaScriptModelException { - - // if factory is null, default factory must be used - if (factory == null) factory = this.getBufferManager().getDefaultBufferFactory(); - - return getWorkingCopy(BufferFactoryWrapper.create(factory), problemRequestor, pm); -} -/** - * @see org.eclipse.wst.jsdt.core.IWorkingCopy#getWorkingCopy() - * @deprecated - */ -public IJavaScriptElement getWorkingCopy() throws JavaScriptModelException { - return getWorkingCopy(null); -} -/** - * @see IJavaScriptUnit#getWorkingCopy(IProgressMonitor) - */ -public IJavaScriptUnit getWorkingCopy(IProgressMonitor monitor) throws JavaScriptModelException { - return getWorkingCopy(new WorkingCopyOwner() {/*non shared working copy*/}, null/*no problem requestor*/, monitor); -} -/** - * @see ITypeRoot#getWorkingCopy(WorkingCopyOwner, IProgressMonitor) - */ -public IJavaScriptUnit getWorkingCopy(WorkingCopyOwner workingCopyOwner, IProgressMonitor monitor) throws JavaScriptModelException { - return getWorkingCopy(workingCopyOwner, null, monitor); -} -/** - * @see org.eclipse.wst.jsdt.core.IWorkingCopy#getWorkingCopy(IProgressMonitor, IBufferFactory, IProblemRequestor) - * @deprecated - */ -public IJavaScriptElement getWorkingCopy(IProgressMonitor monitor, IBufferFactory factory, IProblemRequestor problemRequestor) throws JavaScriptModelException { - return getWorkingCopy(BufferFactoryWrapper.create(factory), problemRequestor, monitor); -} -/** - * @see IJavaScriptUnit#getWorkingCopy(WorkingCopyOwner, IProblemRequestor, IProgressMonitor) - * @deprecated - */ -public IJavaScriptUnit getWorkingCopy(WorkingCopyOwner workingCopyOwner, IProblemRequestor problemRequestor, IProgressMonitor monitor) throws JavaScriptModelException { - if (!isPrimary()) return this; - - JavaModelManager manager = JavaModelManager.getJavaModelManager(); - - CompilationUnit workingCopy = new CompilationUnit((PackageFragment)getParent(), getElementName(),superTypeName, workingCopyOwner); - JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = - manager.getPerWorkingCopyInfo(workingCopy, false/*don't create*/, true/*record usage*/, null/*not used since don't create*/); - if (perWorkingCopyInfo != null) { - return perWorkingCopyInfo.getWorkingCopy(); // return existing handle instead of the one created above - } - BecomeWorkingCopyOperation op = new BecomeWorkingCopyOperation(workingCopy, problemRequestor); - op.runOperation(monitor); - return workingCopy; -} -/** - * @see Openable#hasBuffer() - */ -protected boolean hasBuffer() { - return true; -} -/* - * @see IJavaScriptUnit#hasResourceChanged() - */ -public boolean hasResourceChanged() { - if (!isWorkingCopy()) return false; - - // if resource got deleted, then #getModificationStamp() will answer IResource.NULL_STAMP, which is always different from the cached - // timestamp - Object info = JavaModelManager.getJavaModelManager().getInfo(this); - if (info == null) return false; - IResource resource = getResource(); - if (resource == null) return false; - return ((CompilationUnitElementInfo)info).timestamp != resource.getModificationStamp(); -} -/** - * @see org.eclipse.wst.jsdt.core.IWorkingCopy#isBasedOn(IResource) - * @deprecated - */ -public boolean isBasedOn(IResource resource) { - if (!isWorkingCopy()) return false; - if (!getResource().equals(resource)) return false; - return !hasResourceChanged(); -} -/** - * @see org.eclipse.wst.jsdt.core.IOpenable#isConsistent() - */ -public boolean isConsistent() { - return !JavaModelManager.getJavaModelManager().getElementsOutOfSynchWithBuffers().contains(this); -} -public boolean isPrimary() { - return this.owner == DefaultWorkingCopyOwner.PRIMARY; -} -/** - * @see Openable#isSourceElement() - */ -protected boolean isSourceElement() { - return true; -} -protected IStatus validateCompilationUnit(IResource resource) { - IPackageFragmentRoot root = getPackageFragmentRoot(); - // root never null as validation is not done for working copies - if (resource != null) { - char[][] inclusionPatterns = ((PackageFragmentRoot)root).fullInclusionPatternChars(); - char[][] exclusionPatterns = ((PackageFragmentRoot)root).fullExclusionPatternChars(); - if (Util.isExcluded(resource, inclusionPatterns, exclusionPatterns)) - return new JavaModelStatus(IJavaScriptModelStatusConstants.ELEMENT_NOT_ON_CLASSPATH, this); - if (!resource.isAccessible()) - return new JavaModelStatus(IJavaScriptModelStatusConstants.ELEMENT_DOES_NOT_EXIST, this); - } - IJavaScriptProject project = getJavaScriptProject(); - return JavaScriptConventions.validateCompilationUnitName(getElementName(),project.getOption(JavaScriptCore.COMPILER_SOURCE, true), project.getOption(JavaScriptCore.COMPILER_COMPLIANCE, true)); -} -/* - * @see IJavaScriptUnit#isWorkingCopy() - */ -public boolean isWorkingCopy() { - // For backward compatibility, non primary working copies are always returning true; in removal - // delta, clients can still check that element was a working copy before being discarded. - return !isPrimary() || getPerWorkingCopyInfo() != null; -} -/** - * @see org.eclipse.wst.jsdt.core.IOpenable#makeConsistent(IProgressMonitor) - */ -public void makeConsistent(IProgressMonitor monitor) throws JavaScriptModelException { - makeConsistent(NO_AST, false/*don't resolve bindings*/, 0 /* don't perform statements recovery */, null/*don't collect problems but report them*/, monitor); -} -public org.eclipse.wst.jsdt.core.dom.JavaScriptUnit makeConsistent(int astLevel, boolean resolveBindings, int reconcileFlags, HashMap problems, IProgressMonitor monitor) throws JavaScriptModelException { - if (isConsistent()) return null; - - // create a new info and make it the current info - // (this will remove the info and its children just before storing the new infos) - if (astLevel != NO_AST || problems != null) { - ASTHolderCUInfo info = new ASTHolderCUInfo(); - info.astLevel = astLevel; - info.resolveBindings = resolveBindings; - info.reconcileFlags = reconcileFlags; - info.problems = problems; - openWhenClosed(info, monitor); - org.eclipse.wst.jsdt.core.dom.JavaScriptUnit result = info.ast; - info.ast = null; - return result; - } else { - openWhenClosed(createElementInfo(), monitor); + + /** + * @see org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit#getMainTypeName() + */ + public char[] getMainTypeName(){ + return Util.getNameWithoutJavaLikeExtension(getElementName()).toCharArray(); + } + + /** + * @see org.eclipse.wst.jsdt.core.IWorkingCopy#getOriginal(IJavaScriptElement) + * @deprecated + */ + public IJavaScriptElement getOriginal(IJavaScriptElement workingCopyElement) { + // backward compatibility + if (!isWorkingCopy()) return null; + CompilationUnit cu = (CompilationUnit)workingCopyElement.getAncestor(JAVASCRIPT_UNIT); + if (cu == null || !this.owner.equals(cu.owner)) { + return null; + } + + return workingCopyElement.getPrimaryElement(); + } + + /** + * @see org.eclipse.wst.jsdt.core.IWorkingCopy#getOriginalElement() + * @deprecated + */ + public IJavaScriptElement getOriginalElement() { + // backward compatibility + if (!isWorkingCopy()) return null; + + return getPrimaryElement(); + } + + /* + * @see IJavaScriptUnit#getOwner() + */ + public WorkingCopyOwner getOwner() { + return isPrimary() || !isWorkingCopy() ? null : this.owner; + } + + /** + * @see org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit#getPackageName() + */ + public char[][] getPackageName() { + PackageFragment packageFragment = (PackageFragment) getParent(); + if (packageFragment == null) return CharOperation.NO_CHAR_CHAR; + return Util.toCharArrays(packageFragment.names); + } + + /** + * @see IJavaScriptElement#getPath() + */ + public IPath getPath() { + PackageFragmentRoot root = getPackageFragmentRoot(); + if (root == null) return new Path(getElementName()); // working copy not in workspace + if (root.isArchive()) { + return root.getPath(); + } else { + return getParent().getPath().append(getElementName()); + } + } + /* + * Returns the per working copy info for the receiver, or null if none exist. + * Note: the use count of the per working copy info is NOT incremented. + */ + public JavaModelManager.PerWorkingCopyInfo getPerWorkingCopyInfo() { + return JavaModelManager.getJavaModelManager().getPerWorkingCopyInfo(this, false/*don't create*/, false/*don't record usage*/, null/*no problem requestor needed*/); + } + + /* + * @see IJavaScriptUnit#getPrimary() + */ + public IJavaScriptUnit getPrimary() { + return (IJavaScriptUnit)getPrimaryElement(true); + } + + /* + * @see JavaElement#getPrimaryElement(boolean) + */ + public IJavaScriptElement getPrimaryElement(boolean checkOwner) { + if (checkOwner && isPrimary()) return this; + return new CompilationUnit((PackageFragment)getParent(), getElementName(), DefaultWorkingCopyOwner.PRIMARY); + } + + /** + * @see IJavaScriptElement#getResource() + */ + public IResource getResource() { + PackageFragmentRoot root = getPackageFragmentRoot(); + if (root == null) return null; // working copy not in workspace + if (root.isArchive()) { + return root.getResource(); + } else { + IContainer parentResource = (IContainer) getParent().getResource(); + if (parentResource!=null) + return parentResource.getFile(new Path(getElementName())); + } return null; } -} -/** - * @see org.eclipse.wst.jsdt.core.ISourceManipulation#move(IJavaScriptElement, IJavaScriptElement, String, boolean, IProgressMonitor) - */ -public void move(IJavaScriptElement container, IJavaScriptElement sibling, String rename, boolean force, IProgressMonitor monitor) throws JavaScriptModelException { - if (container == null) { - throw new IllegalArgumentException(Messages.operation_nullContainer); + + /** + * @see org.eclipse.wst.jsdt.core.ISourceReference#getSource() + */ + public String getSource() throws JavaScriptModelException { + IBuffer buffer = getBuffer(); + if (buffer == null) return ""; //$NON-NLS-1$ + return buffer.getContents(); } - IJavaScriptElement[] elements= new IJavaScriptElement[] {this}; - IJavaScriptElement[] containers= new IJavaScriptElement[] {container}; - - String[] renamings= null; - if (rename != null) { - renamings= new String[] {rename}; + + /** + * @see org.eclipse.wst.jsdt.core.ISourceReference#getSourceRange() + */ + public ISourceRange getSourceRange() throws JavaScriptModelException { + return ((CompilationUnitElementInfo) getElementInfo()).getSourceRange(); } - getJavaScriptModel().move(elements, containers, null, renamings, force, monitor); -} - -/** - * @see Openable#openBuffer(IProgressMonitor, Object) - */ -protected IBuffer openBuffer(IProgressMonitor pm, Object info) throws JavaScriptModelException { - - // create buffer - BufferManager bufManager = getBufferManager(); - boolean isWorkingCopy = isWorkingCopy(); - IBuffer buffer = - isWorkingCopy - ? this.owner.createBuffer(this) - : BufferManager.createBuffer(this); - if (buffer == null) return null; - - // synchronize to ensure that 2 threads are not putting 2 different buffers at the same time - // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=146331 - synchronized(bufManager) { - IBuffer existingBuffer = bufManager.getBuffer(this); - if (existingBuffer != null) - return existingBuffer; - - // set the buffer source - if (buffer.getCharacters() == null) { - if (isWorkingCopy) { - IJavaScriptUnit original; - if (!isPrimary() - && (original = new CompilationUnit((PackageFragment)getParent(), getElementName(), DefaultWorkingCopyOwner.PRIMARY)).isOpen()) { - buffer.setContents(original.getSource()); - } else { - IFile file = (IFile)getResource(); - if (file == null || !file.exists()) { - // initialize buffer with empty contents - buffer.setContents(CharOperation.NO_CHAR); + + /** + * @see IJavaScriptUnit#getType(String) + */ + public IType getType(String typeName) { + return new SourceType(this, typeName); + } + + /** + * @see IJavaScriptUnit#getTypes() + */ + public IType[] getTypes() throws JavaScriptModelException { + ArrayList list = getChildrenOfType(TYPE); + IType[] array= new IType[list.size()]; + list.toArray(array); + return array; + } + + /** + * @see IJavaScriptElement + */ + public IResource getUnderlyingResource() throws JavaScriptModelException { + if (isWorkingCopy() && !isPrimary()) return null; + return super.getUnderlyingResource(); + } + + /** + * @see org.eclipse.wst.jsdt.core.IWorkingCopy#getSharedWorkingCopy(IProgressMonitor, IBufferFactory, IProblemRequestor) + * @deprecated + */ + public IJavaScriptElement getSharedWorkingCopy(IProgressMonitor pm, IBufferFactory factory, IProblemRequestor problemRequestor) throws JavaScriptModelException { + + // if factory is null, default factory must be used + if (factory == null) factory = this.getBufferManager().getDefaultBufferFactory(); + + return getWorkingCopy(BufferFactoryWrapper.create(factory), problemRequestor, pm); + } + + /** + * @see org.eclipse.wst.jsdt.core.IWorkingCopy#getWorkingCopy() + * @deprecated + */ + public IJavaScriptElement getWorkingCopy() throws JavaScriptModelException { + return getWorkingCopy(null); + } + + /** + * @see IJavaScriptUnit#getWorkingCopy(IProgressMonitor) + */ + public IJavaScriptUnit getWorkingCopy(IProgressMonitor monitor) throws JavaScriptModelException { + return getWorkingCopy(new WorkingCopyOwner() {/*non shared working copy*/}, null/*no problem requestor*/, monitor); + } + + /** + * @see ITypeRoot#getWorkingCopy(WorkingCopyOwner, IProgressMonitor) + */ + public IJavaScriptUnit getWorkingCopy(WorkingCopyOwner workingCopyOwner, IProgressMonitor monitor) throws JavaScriptModelException { + return getWorkingCopy(workingCopyOwner, null, monitor); + } + + /** + * @see org.eclipse.wst.jsdt.core.IWorkingCopy#getWorkingCopy(IProgressMonitor, IBufferFactory, IProblemRequestor) + * @deprecated + */ + public IJavaScriptElement getWorkingCopy(IProgressMonitor monitor, IBufferFactory factory, IProblemRequestor problemRequestor) throws JavaScriptModelException { + return getWorkingCopy(BufferFactoryWrapper.create(factory), problemRequestor, monitor); + } + + /** + * @see IJavaScriptUnit#getWorkingCopy(WorkingCopyOwner, IProblemRequestor, IProgressMonitor) + * @deprecated + */ + public IJavaScriptUnit getWorkingCopy(WorkingCopyOwner workingCopyOwner, IProblemRequestor problemRequestor, IProgressMonitor monitor) throws JavaScriptModelException { + if (!isPrimary()) return this; + + JavaModelManager manager = JavaModelManager.getJavaModelManager(); + + CompilationUnit workingCopy = new CompilationUnit((PackageFragment)getParent(), getElementName(),superTypeName, workingCopyOwner); + JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = + manager.getPerWorkingCopyInfo(workingCopy, false/*don't create*/, true/*record usage*/, null/*not used since don't create*/); + if (perWorkingCopyInfo != null) { + return perWorkingCopyInfo.getWorkingCopy(); // return existing handle instead of the one created above + } + BecomeWorkingCopyOperation op = new BecomeWorkingCopyOperation(workingCopy, problemRequestor); + op.runOperation(monitor); + return workingCopy; + } + + /** + * @see Openable#hasBuffer() + */ + protected boolean hasBuffer() { + return true; + } + + /* + * @see IJavaScriptUnit#hasResourceChanged() + */ + public boolean hasResourceChanged() { + if (!isWorkingCopy()) return false; + + // if resource got deleted, then #getModificationStamp() will answer IResource.NULL_STAMP, which is always different from the cached + // timestamp + Object info = JavaModelManager.getJavaModelManager().getInfo(this); + if (info == null) return false; + IResource resource = getResource(); + if (resource == null) return false; + return ((CompilationUnitElementInfo)info).timestamp != resource.getModificationStamp(); + } + + /** + * @see org.eclipse.wst.jsdt.core.IWorkingCopy#isBasedOn(IResource) + * @deprecated + */ + public boolean isBasedOn(IResource resource) { + if (!isWorkingCopy()) return false; + if (!getResource().equals(resource)) return false; + return !hasResourceChanged(); + } + + /** + * @see org.eclipse.wst.jsdt.core.IOpenable#isConsistent() + */ + public boolean isConsistent() { + return !JavaModelManager.getJavaModelManager().getElementsOutOfSynchWithBuffers().contains(this); + } + + public boolean isPrimary() { + return this.owner == DefaultWorkingCopyOwner.PRIMARY; + } + + /** + * @see Openable#isSourceElement() + */ + protected boolean isSourceElement() { + return true; + } + + protected IStatus validateCompilationUnit(IResource resource) { + IPackageFragmentRoot root = getPackageFragmentRoot(); + // root never null as validation is not done for working copies + if (resource != null) { + char[][] inclusionPatterns = ((PackageFragmentRoot)root).fullInclusionPatternChars(); + char[][] exclusionPatterns = ((PackageFragmentRoot)root).fullExclusionPatternChars(); + if (Util.isExcluded(resource, inclusionPatterns, exclusionPatterns)) + return new JavaModelStatus(IJavaScriptModelStatusConstants.ELEMENT_NOT_ON_CLASSPATH, this); + if (!resource.isAccessible()) + return new JavaModelStatus(IJavaScriptModelStatusConstants.ELEMENT_DOES_NOT_EXIST, this); + } + IJavaScriptProject project = getJavaScriptProject(); + return JavaScriptConventions.validateCompilationUnitName(getElementName(),project.getOption(JavaScriptCore.COMPILER_SOURCE, true), project.getOption(JavaScriptCore.COMPILER_COMPLIANCE, true)); + } + + /* + * @see IJavaScriptUnit#isWorkingCopy() + */ + public boolean isWorkingCopy() { + // For backward compatibility, non primary working copies are always returning true; in removal + // delta, clients can still check that element was a working copy before being discarded. + return !isPrimary() || getPerWorkingCopyInfo() != null; + } + + /** + * @see org.eclipse.wst.jsdt.core.IOpenable#makeConsistent(IProgressMonitor) + */ + public void makeConsistent(IProgressMonitor monitor) throws JavaScriptModelException { + makeConsistent(NO_AST, false/*don't resolve bindings*/, 0 /* don't perform statements recovery */, null/*don't collect problems but report them*/, monitor); + } + + public org.eclipse.wst.jsdt.core.dom.JavaScriptUnit makeConsistent(int astLevel, boolean resolveBindings, int reconcileFlags, HashMap problems, IProgressMonitor monitor) throws JavaScriptModelException { + if (isConsistent() || this.fIsMakingConsistent) return null; + + this.fIsMakingConsistent = true; + + try { + // create a new info and make it the current info + // (this will remove the info and its children just before storing the new infos) + if (astLevel != NO_AST || problems != null) { + ASTHolderCUInfo info = new ASTHolderCUInfo(); + info.astLevel = astLevel; + info.resolveBindings = resolveBindings; + info.reconcileFlags = reconcileFlags; + info.problems = problems; + openWhenClosed(info, monitor); + org.eclipse.wst.jsdt.core.dom.JavaScriptUnit result = info.ast; + info.ast = null; + return result; + } else { + openWhenClosed(createElementInfo(), monitor); + return null; + } + } finally { + this.fIsMakingConsistent = false; + } + } + + /** + * @see org.eclipse.wst.jsdt.core.ISourceManipulation#move(IJavaScriptElement, IJavaScriptElement, String, boolean, IProgressMonitor) + */ + public void move(IJavaScriptElement container, IJavaScriptElement sibling, String rename, boolean force, IProgressMonitor monitor) throws JavaScriptModelException { + if (container == null) { + throw new IllegalArgumentException(Messages.operation_nullContainer); + } + IJavaScriptElement[] elements= new IJavaScriptElement[] {this}; + IJavaScriptElement[] containers= new IJavaScriptElement[] {container}; + + String[] renamings= null; + if (rename != null) { + renamings= new String[] {rename}; + } + getJavaScriptModel().move(elements, containers, null, renamings, force, monitor); + } + + /** + * @see Openable#openBuffer(IProgressMonitor, Object) + */ + protected IBuffer openBuffer(IProgressMonitor pm, Object info) throws JavaScriptModelException { + + // create buffer + BufferManager bufManager = getBufferManager(); + boolean isWorkingCopy = isWorkingCopy(); + IBuffer buffer = + isWorkingCopy + ? this.owner.createBuffer(this) + : BufferManager.createBuffer(this); + if (buffer == null) return null; + + // synchronize to ensure that 2 threads are not putting 2 different buffers at the same time + // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=146331 + synchronized(bufManager) { + IBuffer existingBuffer = bufManager.getBuffer(this); + if (existingBuffer != null) + return existingBuffer; + + // set the buffer source + if (buffer.getCharacters() == null) { + if (isWorkingCopy) { + IJavaScriptUnit original; + if (!isPrimary() + && (original = new CompilationUnit((PackageFragment)getParent(), getElementName(), DefaultWorkingCopyOwner.PRIMARY)).isOpen()) { + buffer.setContents(original.getSource()); } else { - buffer.setContents(Util.getResourceContentsAsCharArray(file)); + IFile file = (IFile)getResource(); + if (file == null || !file.exists()) { + // initialize buffer with empty contents + buffer.setContents(CharOperation.NO_CHAR); + } else { + buffer.setContents(Util.getResourceContentsAsCharArray(file)); + } } + } else { + IFile file = (IFile)this.getResource(); + if (file == null || !file.exists()) throw newNotPresentException(); + buffer.setContents(Util.getResourceContentsAsCharArray(file)); } - } else { - IFile file = (IFile)this.getResource(); - if (file == null || !file.exists()) throw newNotPresentException(); - buffer.setContents(Util.getResourceContentsAsCharArray(file)); } + + // add buffer to buffer cache + // note this may cause existing buffers to be removed from the buffer cache, but only primary compilation unit's buffer + // can be closed, thus no call to a client's IBuffer#close() can be done in this synchronized block. + bufManager.addBuffer(buffer); + + // listen to buffer changes + buffer.addBufferChangedListener(this); } - - // add buffer to buffer cache - // note this may cause existing buffers to be removed from the buffer cache, but only primary compilation unit's buffer - // can be closed, thus no call to a client's IBuffer#close() can be done in this synchronized block. - bufManager.addBuffer(buffer); - - // listen to buffer changes - buffer.addBufferChangedListener(this); - } - return buffer; -} -protected void openParent(Object childInfo, HashMap newElements, IProgressMonitor pm) throws JavaScriptModelException { - if (!isWorkingCopy()) - super.openParent(childInfo, newElements, pm); - // don't open parent for a working copy to speed up the first becomeWorkingCopy - // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=89411) -} -/** - * @see IJavaScriptUnit#reconcile() - * @deprecated - */ -public IMarker[] reconcile() throws JavaScriptModelException { - reconcile(NO_AST, false/*don't force problem detection*/, false, null/*use primary owner*/, null/*no progress monitor*/); - return null; -} -/** - * @see IJavaScriptUnit#reconcile(int, boolean, WorkingCopyOwner, IProgressMonitor) - */ -public void reconcile(boolean forceProblemDetection, IProgressMonitor monitor) throws JavaScriptModelException { - reconcile(NO_AST, forceProblemDetection? IJavaScriptUnit.FORCE_PROBLEM_DETECTION : 0, null/*use primary owner*/, monitor); -} - -/** - * @see IJavaScriptUnit#reconcile(int, boolean, WorkingCopyOwner, IProgressMonitor) - * @since 3.0 - */ -public org.eclipse.wst.jsdt.core.dom.JavaScriptUnit reconcile( - int astLevel, - boolean forceProblemDetection, - WorkingCopyOwner workingCopyOwner, - IProgressMonitor monitor) throws JavaScriptModelException { - return reconcile(astLevel, forceProblemDetection, false, workingCopyOwner, monitor); -} - -/** - * @see IJavaScriptUnit#reconcile(int, boolean, WorkingCopyOwner, IProgressMonitor) - * @since 3.0 - */ -public org.eclipse.wst.jsdt.core.dom.JavaScriptUnit reconcile( - int astLevel, - boolean forceProblemDetection, - boolean enableStatementsRecovery, - WorkingCopyOwner workingCopyOwner, - IProgressMonitor monitor) throws JavaScriptModelException { - int flags = 0; - if (forceProblemDetection) flags |= IJavaScriptUnit.FORCE_PROBLEM_DETECTION; - if (enableStatementsRecovery) flags |= IJavaScriptUnit.ENABLE_STATEMENTS_RECOVERY; - return reconcile(astLevel, flags, workingCopyOwner, monitor); -} - -public org.eclipse.wst.jsdt.core.dom.JavaScriptUnit reconcile( - int astLevel, - int reconcileFlags, - WorkingCopyOwner workingCopyOwner, - IProgressMonitor monitor) - throws JavaScriptModelException { - - if (!isWorkingCopy()) return null; // Reconciling is not supported on non working copies - if (workingCopyOwner == null) workingCopyOwner = DefaultWorkingCopyOwner.PRIMARY; - - - PerformanceStats stats = null; - if(ReconcileWorkingCopyOperation.PERF) { - stats = PerformanceStats.getStats(JavaModelManager.RECONCILE_PERF, this); - stats.startRun(new String(this.getFileName())); - } - ReconcileWorkingCopyOperation op = new ReconcileWorkingCopyOperation(this, astLevel, reconcileFlags, workingCopyOwner); - JavaModelManager manager = JavaModelManager.getJavaModelManager(); - try { - manager.cacheZipFiles(); // cache zip files for performance (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=134172) - op.runOperation(monitor); - } finally { - manager.flushZipFiles(); + return buffer; } - if(ReconcileWorkingCopyOperation.PERF) { - stats.endRun(); + protected void openParent(Object childInfo, HashMap newElements, IProgressMonitor pm) throws JavaScriptModelException { + if (!isWorkingCopy()) + super.openParent(childInfo, newElements, pm); + // don't open parent for a working copy to speed up the first becomeWorkingCopy + // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=89411) } - return op.ast; -} - -/** - * @see org.eclipse.wst.jsdt.core.ISourceManipulation#rename(String, boolean, IProgressMonitor) - */ -public void rename(String newName, boolean force, IProgressMonitor monitor) throws JavaScriptModelException { - if (newName == null) { - throw new IllegalArgumentException(Messages.operation_nullName); - } - IJavaScriptElement[] elements= new IJavaScriptElement[] {this}; - IJavaScriptElement[] dests= new IJavaScriptElement[] {this.getParent()}; - String[] renamings= new String[] {newName}; - getJavaScriptModel().rename(elements, dests, renamings, force, monitor); -} -/* - * @see IJavaScriptUnit - */ -public void restore() throws JavaScriptModelException { - - if (!isWorkingCopy()) return; - - CompilationUnit original = (CompilationUnit) getOriginalElement(); - IBuffer buffer = this.getBuffer(); - if (buffer == null) return; - buffer.setContents(original.getContents()); - updateTimeStamp(original); - makeConsistent(null); -} -/** - * @see org.eclipse.wst.jsdt.core.IOpenable - */ -public void save(IProgressMonitor pm, boolean force) throws JavaScriptModelException { - if (isWorkingCopy()) { - // no need to save the buffer for a working copy (this is a noop) - reconcile(); // not simply makeConsistent, also computes fine-grain deltas - // in case the working copy is being reconciled already (if not it would miss - // one iteration of deltas). - } else { - super.save(pm, force); - } -} -/** - * Debugging purposes - */ -protected void toStringInfo(int tab, StringBuffer buffer, Object info, boolean showResolvedInfo) { - if (!isPrimary()) { - buffer.append(this.tabString(tab)); - buffer.append("[Working copy] "); //$NON-NLS-1$ - toStringName(buffer); - } else { + + /** + * @see IJavaScriptUnit#reconcile() + * @deprecated + */ + public IMarker[] reconcile() throws JavaScriptModelException { + reconcile(NO_AST, false/*don't force problem detection*/, false, null/*use primary owner*/, null/*no progress monitor*/); + return null; + } + + /** + * @see IJavaScriptUnit#reconcile(int, boolean, WorkingCopyOwner, IProgressMonitor) + */ + public void reconcile(boolean forceProblemDetection, IProgressMonitor monitor) throws JavaScriptModelException { + reconcile(NO_AST, forceProblemDetection? IJavaScriptUnit.FORCE_PROBLEM_DETECTION : 0, null/*use primary owner*/, monitor); + } + + /** + * @see IJavaScriptUnit#reconcile(int, boolean, WorkingCopyOwner, IProgressMonitor) + * @since 3.0 + */ + public org.eclipse.wst.jsdt.core.dom.JavaScriptUnit reconcile( + int astLevel, + boolean forceProblemDetection, + WorkingCopyOwner workingCopyOwner, + IProgressMonitor monitor) throws JavaScriptModelException { + return reconcile(astLevel, forceProblemDetection, false, workingCopyOwner, monitor); + } + + /** + * @see IJavaScriptUnit#reconcile(int, boolean, WorkingCopyOwner, IProgressMonitor) + * @since 3.0 + */ + public org.eclipse.wst.jsdt.core.dom.JavaScriptUnit reconcile( + int astLevel, + boolean forceProblemDetection, + boolean enableStatementsRecovery, + WorkingCopyOwner workingCopyOwner, + IProgressMonitor monitor) throws JavaScriptModelException { + int flags = 0; + if (forceProblemDetection) flags |= IJavaScriptUnit.FORCE_PROBLEM_DETECTION; + if (enableStatementsRecovery) flags |= IJavaScriptUnit.ENABLE_STATEMENTS_RECOVERY; + return reconcile(astLevel, flags, workingCopyOwner, monitor); + } + + public org.eclipse.wst.jsdt.core.dom.JavaScriptUnit reconcile( + int astLevel, + int reconcileFlags, + WorkingCopyOwner workingCopyOwner, + IProgressMonitor monitor) + throws JavaScriptModelException { + + if (!isWorkingCopy()) return null; // Reconciling is not supported on non working copies + if (workingCopyOwner == null) workingCopyOwner = DefaultWorkingCopyOwner.PRIMARY; + + + PerformanceStats stats = null; + if(ReconcileWorkingCopyOperation.PERF) { + stats = PerformanceStats.getStats(JavaModelManager.RECONCILE_PERF, this); + stats.startRun(new String(this.getFileName())); + } + ReconcileWorkingCopyOperation op = new ReconcileWorkingCopyOperation(this, astLevel, reconcileFlags, workingCopyOwner); + JavaModelManager manager = JavaModelManager.getJavaModelManager(); + try { + manager.cacheZipFiles(); // cache zip files for performance (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=134172) + op.runOperation(monitor); + } finally { + manager.flushZipFiles(); + } + if(ReconcileWorkingCopyOperation.PERF) { + stats.endRun(); + } + return op.ast; + } + + /** + * @see org.eclipse.wst.jsdt.core.ISourceManipulation#rename(String, boolean, IProgressMonitor) + */ + public void rename(String newName, boolean force, IProgressMonitor monitor) throws JavaScriptModelException { + if (newName == null) { + throw new IllegalArgumentException(Messages.operation_nullName); + } + IJavaScriptElement[] elements= new IJavaScriptElement[] {this}; + IJavaScriptElement[] dests= new IJavaScriptElement[] {this.getParent()}; + String[] renamings= new String[] {newName}; + getJavaScriptModel().rename(elements, dests, renamings, force, monitor); + } + + /* + * @see IJavaScriptUnit + */ + public void restore() throws JavaScriptModelException { + + if (!isWorkingCopy()) return; + + CompilationUnit original = (CompilationUnit) getOriginalElement(); + IBuffer buffer = this.getBuffer(); + if (buffer == null) return; + buffer.setContents(original.getContents()); + updateTimeStamp(original); + makeConsistent(null); + } + + /** + * @see org.eclipse.wst.jsdt.core.IOpenable + */ + public void save(IProgressMonitor pm, boolean force) throws JavaScriptModelException { if (isWorkingCopy()) { + // no need to save the buffer for a working copy (this is a noop) + reconcile(); // not simply makeConsistent, also computes fine-grain deltas + // in case the working copy is being reconciled already (if not it would miss + // one iteration of deltas). + } else { + super.save(pm, force); + } + } + + /** + * Debugging purposes + */ + protected void toStringInfo(int tab, StringBuffer buffer, Object info, boolean showResolvedInfo) { + if (!isPrimary()) { buffer.append(this.tabString(tab)); buffer.append("[Working copy] "); //$NON-NLS-1$ toStringName(buffer); - if (info == null) { - buffer.append(" (not open)"); //$NON-NLS-1$ - } } else { - super.toStringInfo(tab, buffer, info, showResolvedInfo); + if (isWorkingCopy()) { + buffer.append(this.tabString(tab)); + buffer.append("[Working copy] "); //$NON-NLS-1$ + toStringName(buffer); + if (info == null) { + buffer.append(" (not open)"); //$NON-NLS-1$ + } + } else { + super.toStringInfo(tab, buffer, info, showResolvedInfo); + } } } -} -/* - * Assume that this is a working copy - */ -protected void updateTimeStamp(CompilationUnit original) throws JavaScriptModelException { - long timeStamp = - ((IFile) original.getResource()).getModificationStamp(); - if (timeStamp == IResource.NULL_STAMP) { - throw new JavaScriptModelException( - new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_RESOURCE)); - } - ((CompilationUnitElementInfo) getElementInfo()).timestamp = timeStamp; -} - -public IField getField(String fieldName) { - return new SourceField(this, fieldName); -} -public IField[] getFields() throws JavaScriptModelException { - ArrayList list = getChildrenOfType(FIELD); - IField[] array= new IField[list.size()]; - list.toArray(array); - return array; - -} -public IFunction getFunction(String selector, String[] parameterTypeSignatures) { - return new SourceMethod(this, selector, parameterTypeSignatures); -} -/** - * @deprecated Use {@link #getFunctions()} instead - */ -public IFunction[] getMethods() throws JavaScriptModelException { - return getFunctions(); -} - -public IFunction[] getFunctions() throws JavaScriptModelException { - ArrayList list = getChildrenOfType(METHOD); - IFunction[] array= new IFunction[list.size()]; - list.toArray(array); - return array; -} -public IField createField(String contents, IJavaScriptElement sibling, boolean force, IProgressMonitor monitor) throws JavaScriptModelException { - CreateFieldOperation op = new CreateFieldOperation(this, contents, force); - if (sibling != null) { - op.createBefore(sibling); - } - op.runOperation(monitor); - return (IField) op.getResultElements()[0]; -} -/** - * @see IType - */ - -/** - * @see IType - */ -public IFunction createMethod(String contents, IJavaScriptElement sibling, boolean force, IProgressMonitor monitor) throws JavaScriptModelException { - CreateMethodOperation op = new CreateMethodOperation(this, contents, force); - if (sibling != null) { - op.createBefore(sibling); - } - op.runOperation(monitor); - return (IFunction) op.getResultElements()[0]; -} - -public String getDisplayName() { - if(isVirtual()) { - - JsGlobalScopeContainerInitializer init = ((IVirtualParent)parent).getContainerInitializer(); - if(init==null) return super.getDisplayName(); - return init.getDescription(new Path(getElementName()), getJavaScriptProject()); + + /* + * Assume that this is a working copy + */ + protected void updateTimeStamp(CompilationUnit original) throws JavaScriptModelException { + long timeStamp = + ((IFile) original.getResource()).getModificationStamp(); + if (timeStamp == IResource.NULL_STAMP) { + throw new JavaScriptModelException( + new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_RESOURCE)); + } + ((CompilationUnitElementInfo) getElementInfo()).timestamp = timeStamp; } - return super.getDisplayName(); -} - - -public URI getHostPath() { - if(isVirtual()) { - JsGlobalScopeContainerInitializer init = ((IVirtualParent)parent).getContainerInitializer(); - if(init!=null) return init.getHostPath(new Path(getElementName()), getJavaScriptProject()); + + public IField getField(String fieldName) { + return new SourceField(this, fieldName); } - return null; -} - -public JsGlobalScopeContainerInitializer getContainerInitializer() { - JsGlobalScopeContainerInitializer init = null; - if (parent instanceof IVirtualParent) - init=((IVirtualParent)parent).getContainerInitializer(); - return init; -} - -public LibrarySuperType getCommonSuperType() { - IJavaScriptProject javaProject = getJavaScriptProject(); - if(javaProject!=null && javaProject.exists()) return javaProject.getCommonSuperType(); - return null; -} - -public IFunction[] findFunctions(IFunction method) { - ArrayList list = new ArrayList(); - try { - IFunction[]methods=getFunctions(); - String elementName = method.getElementName(); - for (int i = 0, length = methods.length; i < length; i++) { - IFunction existingMethod = methods[i]; - if (elementName.equals(existingMethod.getElementName())) - { - list.add(existingMethod); + + public IField[] getFields() throws JavaScriptModelException { + ArrayList list = getChildrenOfType(FIELD); + IField[] array= new IField[list.size()]; + list.toArray(array); + return array; + + } + + public IFunction getFunction(String selector, String[] parameterTypeSignatures) { + return new SourceMethod(this, selector, parameterTypeSignatures); + } + + /** + * @deprecated Use {@link #getFunctions()} instead + */ + public IFunction[] getMethods() throws JavaScriptModelException { + return getFunctions(); + } + + public IFunction[] getFunctions() throws JavaScriptModelException { + ArrayList list = getChildrenOfType(METHOD); + IFunction[] array= new IFunction[list.size()]; + list.toArray(array); + return array; + } + + public IField createField(String contents, IJavaScriptElement sibling, boolean force, IProgressMonitor monitor) throws JavaScriptModelException { + CreateFieldOperation op = new CreateFieldOperation(this, contents, force); + if (sibling != null) { + op.createBefore(sibling); + } + op.runOperation(monitor); + return (IField) op.getResultElements()[0]; + } + + /** + * @see IType + */ + public IFunction createMethod(String contents, IJavaScriptElement sibling, boolean force, IProgressMonitor monitor) throws JavaScriptModelException { + CreateMethodOperation op = new CreateMethodOperation(this, contents, force); + if (sibling != null) { + op.createBefore(sibling); + } + op.runOperation(monitor); + return (IFunction) op.getResultElements()[0]; + } + + public String getDisplayName() { + if(isVirtual()) { + + JsGlobalScopeContainerInitializer init = ((IVirtualParent)parent).getContainerInitializer(); + if(init==null) return super.getDisplayName(); + return init.getDescription(new Path(getElementName()), getJavaScriptProject()); + } + return super.getDisplayName(); + } + + public URI getHostPath() { + if(isVirtual()) { + JsGlobalScopeContainerInitializer init = ((IVirtualParent)parent).getContainerInitializer(); + if(init!=null) return init.getHostPath(new Path(getElementName()), getJavaScriptProject()); + } + return null; + } + + public JsGlobalScopeContainerInitializer getContainerInitializer() { + JsGlobalScopeContainerInitializer init = null; + if (parent instanceof IVirtualParent) + init=((IVirtualParent)parent).getContainerInitializer(); + return init; + } + + public LibrarySuperType getCommonSuperType() { + IJavaScriptProject javaProject = getJavaScriptProject(); + if(javaProject!=null && javaProject.exists()) return javaProject.getCommonSuperType(); + return null; + } + + public IFunction[] findFunctions(IFunction method) { + ArrayList list = new ArrayList(); + try { + IFunction[]methods=getFunctions(); + String elementName = method.getElementName(); + String parentName = method.getParent().getElementName(); + for (int i = 0, length = methods.length; i < length; i++) { + IFunction existingMethod = methods[i]; + if (elementName.equals(existingMethod.getElementName()) + && parentName.equals(existingMethod.getParent().getElementName())) { + list.add(existingMethod); + } + else { + IFunction nestedMethod = findNestedFunction(existingMethod, elementName, parentName); + if (nestedMethod != null) { + list.add(nestedMethod); + } + } + } + } catch (JavaScriptModelException e) { + } + int size = list.size(); + if (size == 0) { + return null; + } else { + IFunction[] result = new IFunction[size]; + list.toArray(result); + return result; + } + } + + public IFunction findNestedFunction(IFunction method, String elementName, String parentName) { + try { + if (method.hasChildren()) { + ArrayList methods = ((JavaElement) method).getChildrenOfType(METHOD); + for (Iterator iterator = methods.iterator(); iterator.hasNext();) { + IFunction childMethod = (IFunction) iterator.next(); + if (elementName.equals(childMethod.getElementName()) + && parentName.equals(childMethod.getParent().getElementName())) { + return childMethod; + } + IFunction nestedMethod = findNestedFunction(childMethod, elementName, parentName); + if (nestedMethod != null) + return nestedMethod; + } } } - } catch (JavaScriptModelException e) { + catch (JavaScriptModelException e) { + } + return null; } - int size = list.size(); - if (size == 0) { + + public String getInferenceID() { + JsGlobalScopeContainerInitializer containerInitializer = getContainerInitializer(); + if (containerInitializer!=null) + return containerInitializer.getInferenceID(); return null; - } else { - IFunction[] result = new IFunction[size]; - list.toArray(result); - return result; } -} - -public String getInferenceID() { - JsGlobalScopeContainerInitializer containerInitializer = getContainerInitializer(); - if (containerInitializer!=null) - return containerInitializer.getInferenceID(); - return null; -} - -public SearchableEnvironment newSearchableNameEnvironment(WorkingCopyOwner owner) throws JavaScriptModelException { - SearchableEnvironment env=super.newSearchableNameEnvironment(owner); - env.setCompilationUnit(this); - return env; -} - -} + + public SearchableEnvironment newSearchableNameEnvironment(WorkingCopyOwner owner) throws JavaScriptModelException { + SearchableEnvironment env=super.newSearchableNameEnvironment(owner); + env.setCompilationUnit(this); + return env; + } +} \ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CompilationUnitProblemFinder.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CompilationUnitProblemFinder.java index 75534301..25ebbe6d 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CompilationUnitProblemFinder.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CompilationUnitProblemFinder.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -22,6 +22,7 @@ import org.eclipse.wst.jsdt.core.IJavaScriptUnit; import org.eclipse.wst.jsdt.core.JavaScriptModelException; import org.eclipse.wst.jsdt.core.WorkingCopyOwner; import org.eclipse.wst.jsdt.core.compiler.CategorizedProblem; +import org.eclipse.wst.jsdt.core.compiler.CharOperation; import org.eclipse.wst.jsdt.internal.compiler.CompilationResult; import org.eclipse.wst.jsdt.internal.compiler.Compiler; import org.eclipse.wst.jsdt.internal.compiler.DefaultErrorHandlingPolicies; @@ -134,7 +135,7 @@ public class CompilationUnitProblemFinder extends Compiler implements ITypeReque * -> build compilation unit declarations, their bindings and record their results. */ public void accept(org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit sourceUnit, AccessRestriction accessRestriction) { - accept(sourceUnit, new char[0][0], accessRestriction); + accept(sourceUnit, CharOperation.NO_CHAR_CHAR, accessRestriction); } public void accept(ICompilationUnit sourceUnit, char[][] typeNames, @@ -143,19 +144,19 @@ public class CompilationUnitProblemFinder extends Compiler implements ITypeReque CompilationResult unitResult = new CompilationResult(sourceUnit, 1, 1, this.options.maxProblemsPerUnit); try { + if (parsedUnits == null) + parsedUnits = new HashtableOfObject(); + CompilationUnitDeclaration parsedUnit = (CompilationUnitDeclaration) parsedUnits.get(sourceUnit.getFileName()); if (options.verbose) { String count = String.valueOf(totalUnits + 1); this.out.println( Messages.bind(Messages.compilation_request, new String[] { count, - count, + (parsedUnit != null ? "(ITR2:not reparsed)" : count), //$NON-NLS-1$ new String(sourceUnit.getFileName()) })); } - if (parsedUnits == null) - parsedUnits = new HashtableOfObject(); - CompilationUnitDeclaration parsedUnit = (CompilationUnitDeclaration) parsedUnits.get(sourceUnit.getFileName()); if (parsedUnit == null) { // diet parsing for large collection of unit if (totalUnits < parseThreshold) { diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CompilationUnitStructureRequestor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CompilationUnitStructureRequestor.java index 96a231b8..2d4f783d 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CompilationUnitStructureRequestor.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CompilationUnitStructureRequestor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -22,6 +22,7 @@ import org.eclipse.wst.jsdt.core.Signature; import org.eclipse.wst.jsdt.core.compiler.CategorizedProblem; import org.eclipse.wst.jsdt.core.compiler.CharOperation; import org.eclipse.wst.jsdt.core.compiler.IProblem; +import org.eclipse.wst.jsdt.core.infer.IInferEngine; import org.eclipse.wst.jsdt.internal.compiler.ISourceElementRequestor; import org.eclipse.wst.jsdt.internal.compiler.parser.Parser; import org.eclipse.wst.jsdt.internal.compiler.util.HashtableOfObject; @@ -283,9 +284,10 @@ public void enterMethod(MethodInfo methodInfo) { || parentHandle.getElementType() == IJavaScriptElement.JAVASCRIPT_UNIT || parentHandle.getElementType() == IJavaScriptElement.CLASS_FILE || parentHandle.getElementType() == IJavaScriptElement.METHOD + || parentHandle.getElementType() == IJavaScriptElement.FIELD ) { - char[] cs = methodInfo.name!=null ? methodInfo.name: CharOperation.NO_CHAR; + char[] cs = methodInfo.name!=null ? methodInfo.name: CharOperation.concat(IInferEngine.ANONYMOUS_PREFIX, IInferEngine.ANONYMOUS_CLASS_ID); String selector = JavaModelManager.getJavaModelManager().intern(new String(cs)); handle = new SourceMethod(parentHandle, selector, parameterTypeSigs); @@ -329,28 +331,23 @@ public void enterType(TypeInfo typeInfo) { JavaElementInfo parentInfo = (JavaElementInfo) this.infoStack.peek(); JavaElement parentHandle= (JavaElement) this.handleStack.peek(); String nameString= new String(typeInfo.name); + + // if the type is a global type (isIndexed) then make sure its parent is a IJavaScriptUnit + while(typeInfo.isIndexed && !(parentHandle instanceof IJavaScriptUnit)) { + parentHandle = parentHandle.parent; + + // just in case something is messed up with the parenting, it will still get a value set + if(parentHandle == null) { + parentHandle= (JavaElement) this.handleStack.peek(); + break; + } + } - //@GINO: Anonymous setting model as anonymous - SourceType handle = -// typeInfo.anonymousMember ? -// new SourceType(parentHandle, nameString){ -// -// public boolean isAnonymous() { -// return true; -// } -// -// } : - new SourceType(parentHandle, nameString); //NB: occurenceCount is computed in resolveDuplicates + SourceType handle = new SourceType(parentHandle, nameString, typeInfo.anonymousMember); //NB: occurenceCount is computed in resolveDuplicates resolveDuplicates(handle); - SourceTypeElementInfo info = -// typeInfo.anonymousMember ? -// new SourceTypeElementInfo( parentHandle instanceof ClassFile ) { -// public boolean isAnonymousMember() { -// return true; -// } -// } : + SourceTypeElementInfo info = new SourceTypeElementInfo( parentHandle instanceof ClassFile , typeInfo.anonymousMember); info.setHandle(handle); info.setSourceRangeStart(typeInfo.declarationStart); diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CopyPackageFragmentRootOperation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CopyPackageFragmentRootOperation.java index 882016b2..e5dd1889 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CopyPackageFragmentRootOperation.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/CopyPackageFragmentRootOperation.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DeltaProcessor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DeltaProcessor.java index ad7c9f19..3ad1471f 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DeltaProcessor.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DeltaProcessor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -2264,31 +2264,38 @@ public class DeltaProcessor { int length = projects.length; for (int i = 0; i < length; i++){ IProject project = projects[i]; - JavaProject javaProject = (JavaProject)JavaScriptCore.create(project); - try { - IPath projectPath = project.getFullPath(); - IIncludePathEntry[] classpath = javaProject.getResolvedClasspath(); // allowed to reuse model cache - for (int j = 0, cpLength = classpath.length; j < cpLength; j++) { - IIncludePathEntry entry = classpath[j]; - switch (entry.getEntryKind()) { - case IIncludePathEntry.CPE_PROJECT: - if (affectedProjects.contains(entry.getPath())) { - this.state.addClasspathValidation(javaProject); - needCycleValidation = true; - } - break; - case IIncludePathEntry.CPE_LIBRARY: - IPath entryPath = entry.getPath(); - IPath libProjectPath = entryPath.removeLastSegments(entryPath.segmentCount()-1); - if (!libProjectPath.equals(projectPath) // if library contained in another project - && affectedProjects.contains(libProjectPath)) { - this.state.addClasspathValidation(javaProject); - } - break; + /* do not update classpath for closed projects + * + * if class path is updated for a closed project then the correct classpath entries will + * be overwritten by incorrect ones because the containers will not be able to inspect + * the resources of closed projects */ + if(project.isOpen()) { + JavaProject javaProject = (JavaProject)JavaScriptCore.create(project); + try { + IPath projectPath = project.getFullPath(); + IIncludePathEntry[] classpath = javaProject.getResolvedClasspath(); // allowed to reuse model cache + for (int j = 0, cpLength = classpath.length; j < cpLength; j++) { + IIncludePathEntry entry = classpath[j]; + switch (entry.getEntryKind()) { + case IIncludePathEntry.CPE_PROJECT: + if (affectedProjects.contains(entry.getPath())) { + this.state.addClasspathValidation(javaProject); + needCycleValidation = true; + } + break; + case IIncludePathEntry.CPE_LIBRARY: + IPath entryPath = entry.getPath(); + IPath libProjectPath = entryPath.removeLastSegments(entryPath.segmentCount()-1); + if (!libProjectPath.equals(projectPath) // if library contained in another project + && affectedProjects.contains(libProjectPath)) { + this.state.addClasspathValidation(javaProject); + } + break; + } } + } catch(JavaScriptModelException e) { + // project no longer exists } - } catch(JavaScriptModelException e) { - // project no longer exists } } } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JarEntryDirectory.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JarEntryDirectory.java new file mode 100644 index 00000000..f8cbc506 --- /dev/null +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JarEntryDirectory.java @@ -0,0 +1,60 @@ +/******************************************************************************* + * Copyright (c) 2000, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.wst.jsdt.internal.core; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.wst.jsdt.core.IJarEntryResource; + +public class JarEntryDirectory extends JarEntryResource { + private IJarEntryResource[] children; + + public JarEntryDirectory(String simpleName) { + super(simpleName); + } + + public JarEntryResource clone(Object newParent) { + JarEntryDirectory dir = new JarEntryDirectory(this.simpleName); + dir.setParent(newParent); + int length = this.children.length; + if (length > 0) { + IJarEntryResource[] newChildren = new IJarEntryResource[length]; + for (int i = 0; i < length; i++) { + JarEntryResource child = (JarEntryResource) this.children[i]; + newChildren[i] = child.clone(dir); + } + dir.setChildren(newChildren); + } + return dir; + } + + public IJarEntryResource[] getChildren() { + return this.children; + } + + public InputStream getContents() throws CoreException { + return new ByteArrayInputStream(new byte[0]); + } + + public boolean isFile() { + return false; + } + + public void setChildren(IJarEntryResource[] children) { + this.children = children; + } + + public String toString() { + return "JarEntryDirectory["+getEntryName()+"]"; //$NON-NLS-1$ //$NON-NLS-2$ + } +} diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JarEntryFile.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JarEntryFile.java new file mode 100644 index 00000000..e9185848 --- /dev/null +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JarEntryFile.java @@ -0,0 +1,77 @@ +/******************************************************************************* + * Copyright (c) 2000, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.wst.jsdt.internal.core; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +import org.eclipse.core.resources.IStorage; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.wst.jsdt.core.IJarEntryResource; +import org.eclipse.wst.jsdt.core.IJavaScriptModelStatusConstants; +import org.eclipse.wst.jsdt.core.JavaScriptModelException; +import org.eclipse.wst.jsdt.internal.compiler.util.Util; + +/** + * A jar entry that represents a non-java file found in a JAR. + * + * @see IStorage + */ +public class JarEntryFile extends JarEntryResource { + private static final IJarEntryResource[] NO_CHILDREN = new IJarEntryResource[0]; + + public JarEntryFile(String simpleName) { + super(simpleName); + } + + public JarEntryResource clone(Object newParent) { + JarEntryFile file = new JarEntryFile(this.simpleName); + file.setParent(newParent); + return file; + } + + public InputStream getContents() throws CoreException { + ZipFile zipFile = null; + try { + zipFile = getZipFile(); + if (JavaModelManager.ZIP_ACCESS_VERBOSE) { + System.out.println("(" + Thread.currentThread() + ") [JarEntryFile.getContents()] Creating ZipFile on " +zipFile.getName()); //$NON-NLS-1$ //$NON-NLS-2$ + } + String entryName = getEntryName(); + ZipEntry zipEntry = zipFile.getEntry(entryName); + if (zipEntry == null){ + throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.INVALID_PATH, entryName)); + } + byte[] contents = Util.getZipEntryByteContent(zipEntry, zipFile); + return new ByteArrayInputStream(contents); + } catch (IOException e){ + throw new JavaScriptModelException(e, IJavaScriptModelStatusConstants.IO_EXCEPTION); + } finally { + // avoid leaking ZipFiles + JavaModelManager.getJavaModelManager().closeZipFile(zipFile); + } + } + + public IJarEntryResource[] getChildren() { + return NO_CHILDREN; + } + + public boolean isFile() { + return true; + } + + public String toString() { + return "JarEntryFile["+getEntryName()+"]"; //$NON-NLS-2$ //$NON-NLS-1$ + } +} diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JarEntryResource.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JarEntryResource.java new file mode 100644 index 00000000..d540a698 --- /dev/null +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JarEntryResource.java @@ -0,0 +1,98 @@ +/******************************************************************************* + * Copyright (c) 2000, 2012 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.wst.jsdt.internal.core; + +import java.util.zip.ZipFile; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.Path; +import org.eclipse.core.runtime.PlatformObject; +import org.eclipse.wst.jsdt.core.IJarEntryResource; +import org.eclipse.wst.jsdt.core.IPackageFragment; +import org.eclipse.wst.jsdt.core.IPackageFragmentRoot; +import org.eclipse.wst.jsdt.internal.core.util.Util; + +public abstract class JarEntryResource extends PlatformObject implements IJarEntryResource { + + protected Object parent; + protected String simpleName; + + public JarEntryResource(String simpleName) { + this.simpleName = simpleName; + } + + public abstract JarEntryResource clone(Object newParent); + + public boolean equals(Object obj) { + if (! (obj instanceof JarEntryResource)) + return false; + JarEntryResource other = (JarEntryResource) obj; + return this.parent.equals(other.parent) && this.simpleName.equals(other.simpleName); + } + + protected String getEntryName() { + String parentEntryName; + if (this.parent instanceof IPackageFragment) { + String elementName = ((IPackageFragment) this.parent).getElementName(); + parentEntryName = elementName.length() == 0 ? "" : elementName .replace('.', '/') + '/'; //$NON-NLS-1$ + } else if (this.parent instanceof IPackageFragmentRoot) { + parentEntryName = ""; //$NON-NLS-1$ + } else { + parentEntryName = ((JarEntryDirectory) this.parent).getEntryName() + '/'; + } + return parentEntryName + this.simpleName; + } + + public IPath getFullPath() { + return new Path(getEntryName()).makeAbsolute(); + } + + public String getName() { + return this.simpleName; + } + + public Object getParent() { + return this.parent; + } + + public IPackageFragmentRoot getPackageFragmentRoot() { + if (this.parent instanceof IPackageFragment) { + return (IPackageFragmentRoot) ((IPackageFragment) this.parent).getParent(); + } else if (this.parent instanceof IPackageFragmentRoot) { + return (IPackageFragmentRoot) this.parent; + } else { + return ((JarEntryDirectory) this.parent).getPackageFragmentRoot(); + } + } + + protected ZipFile getZipFile() throws CoreException { + if (this.parent instanceof IPackageFragment) { + JarPackageFragmentRoot root = (JarPackageFragmentRoot) ((IPackageFragment) this.parent).getParent(); + return root.getJar(); + } else if (this.parent instanceof JarPackageFragmentRoot) { + return ((JarPackageFragmentRoot) this.parent).getJar(); + } else + return ((JarEntryDirectory) this.parent).getZipFile(); + } + + public int hashCode() { + return Util.combineHashCodes(this.simpleName.hashCode(), this.parent.hashCode()); + } + + public boolean isReadOnly() { + return true; + } + + public void setParent(Object parent) { + this.parent = parent; + } +} diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JarPackageFragment.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JarPackageFragment.java new file mode 100644 index 00000000..e7604145 --- /dev/null +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JarPackageFragment.java @@ -0,0 +1,280 @@ +/******************************************************************************* + * Copyright (c) 2000, 2012 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.wst.jsdt.internal.core; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.zip.ZipEntry; +import java.util.zip.ZipException; +import java.util.zip.ZipFile; + +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.Path; +import org.eclipse.wst.jsdt.core.IClassFile; +import org.eclipse.wst.jsdt.core.IJarEntryResource; +import org.eclipse.wst.jsdt.core.IJavaScriptElement; +import org.eclipse.wst.jsdt.core.IJavaScriptModelStatusConstants; +import org.eclipse.wst.jsdt.core.IJavaScriptUnit; +import org.eclipse.wst.jsdt.core.IPackageFragment; +import org.eclipse.wst.jsdt.core.JavaScriptModelException; +import org.eclipse.wst.jsdt.internal.core.util.Messages; +import org.eclipse.wst.jsdt.internal.core.util.Util; + +/** + * A package fragment that represents a package fragment found in a JAR. + * + * @see org.eclipse.jdt.core.IPackageFragment + */ +class JarPackageFragment extends PackageFragment { +/** + * Constructs a package fragment that is contained within a jar or a zip. + */ +protected JarPackageFragment(PackageFragmentRoot root, String[] names) { + super(root, names); +} +/** + * @see Openable + */ +protected boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaScriptModelException { + JarPackageFragmentRoot root = (JarPackageFragmentRoot) getParent(); + JarPackageFragmentRootInfo parentInfo = (JarPackageFragmentRootInfo) root.getElementInfo(); + ArrayList[] entries = (ArrayList[]) parentInfo.rawPackageInfo.get(this.names); + if (entries == null) + throw newNotPresentException(); + JarPackageFragmentInfo fragInfo = (JarPackageFragmentInfo) info; + + // compute children + fragInfo.setChildren(computeChildren(entries[0/*class files*/])); + + // compute non-Java resources + fragInfo.setNonJavaResources(computeNonJavaResources(entries[1/*non Java resources*/])); + + newElements.put(this, fragInfo); + return true; +} +/** + * Compute the children of this package fragment. Children of jar package fragments + * can only be IClassFile (representing .class files). + */ +private IJavaScriptElement[] computeChildren(ArrayList names) { + int size = names.size(); + if (size == 0 && false) { + File file = getPath().toFile(); + if (!file.isFile()) { + IPath path = ResourcesPlugin.getWorkspace().getRoot().getFile(getPath()).getLocation(); + if (path != null) + file = path.toFile(); + } + + if (file.isFile()) { + String osPath = getPath().toOSString(); + List classFiles = new ArrayList(); + ZipFile zip = null; + try { + zip = new ZipFile(file); + for (Enumeration e = zip.entries(); e.hasMoreElements();) { + ZipEntry ze = (ZipEntry) e.nextElement(); + if (org.eclipse.wst.jsdt.internal.compiler.util.Util.isClassFileName(ze.getName())) { + classFiles.add(new ClassFile(this, ze.getName())); + } + } + } + catch (ZipException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + finally { + if (zip != null) { + try { + zip.close(); + } + catch (IOException e) { + // do nothing + } + } + } + return (IJavaScriptElement[]) classFiles.toArray(new ClassFile[classFiles.size()]); + } + } + IJavaScriptElement[] children = new IJavaScriptElement[size]; + for (int i = 0; i < size; i++) { + String path = (String) names.get(i); + children[i] = new ClassFile(this, path); + } + return children; +} +/** + * Compute all the non-java resources according to the given entry names. + */ +private Object[] computeNonJavaResources(ArrayList entryNames) { + int length = entryNames.size(); + if (length == 0) + return JavaElementInfo.NO_NON_JAVA_RESOURCES; + HashMap jarEntries = new HashMap(); // map from IPath to IJarEntryResource + HashMap childrenMap = new HashMap(); // map from IPath to ArrayList + ArrayList topJarEntries = new ArrayList(); + for (int i = 0; i < length; i++) { + String resName = (String) entryNames.get(i); + // consider that a .java file is not a non-java resource (see bug 12246 Packages view shows .class and .java files when JAR has source) + if (!Util.isJavaLikeFileName(resName)) { + IPath filePath = new Path(resName); + IPath childPath = filePath.removeFirstSegments(this.names.length); + if (jarEntries.containsKey(childPath)) { + // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=222665 + continue; + } + JarEntryFile file = new JarEntryFile(filePath.lastSegment()); + jarEntries.put(childPath, file); + if (childPath.segmentCount() == 1) { + file.setParent(this); + topJarEntries.add(file); + } else { + IPath parentPath = childPath.removeLastSegments(1); + while (parentPath.segmentCount() > 0) { + ArrayList parentChildren = (ArrayList) childrenMap.get(parentPath); + if (parentChildren == null) { + Object dir = new JarEntryDirectory(parentPath.lastSegment()); + jarEntries.put(parentPath, dir); + childrenMap.put(parentPath, parentChildren = new ArrayList()); + parentChildren.add(childPath); + if (parentPath.segmentCount() == 1) { + topJarEntries.add(dir); + break; + } + childPath = parentPath; + parentPath = childPath.removeLastSegments(1); + } else { + parentChildren.add(childPath); + break; // all parents are already registered + } + } + } + } + } + Iterator entries = childrenMap.entrySet().iterator(); + while (entries.hasNext()) { + Map.Entry entry = (Map.Entry) entries.next(); + IPath entryPath = (IPath) entry.getKey(); + ArrayList entryValue = (ArrayList) entry.getValue(); + JarEntryDirectory jarEntryDirectory = (JarEntryDirectory) jarEntries.get(entryPath); + int size = entryValue.size(); + IJarEntryResource[] children = new IJarEntryResource[size]; + for (int i = 0; i < size; i++) { + JarEntryResource child = (JarEntryResource) jarEntries.get(entryValue.get(i)); + child.setParent(jarEntryDirectory); + children[i] = child; + } + jarEntryDirectory.setChildren(children); + if (entryPath.segmentCount() == 1) { + jarEntryDirectory.setParent(this); + } + } + return topJarEntries.toArray(new Object[topJarEntries.size()]); +} +/** + * Returns true if this fragment contains at least one java resource. + * Returns false otherwise. + */ +public boolean containsJavaResources() throws JavaScriptModelException { + return ((JarPackageFragmentInfo) getElementInfo()).containsJavaResources(); +} +/** + * @see org.eclipse.jdt.core.IPackageFragment + */ +public IJavaScriptUnit createCompilationUnit(String cuName, String contents, boolean force, IProgressMonitor monitor) throws JavaScriptModelException { + throw new JavaScriptModelException(new JavaModelStatus(IJavaScriptModelStatusConstants.READ_ONLY, this)); +} +/** + * @see JavaElement + */ +protected Object createElementInfo() { + return new JarPackageFragmentInfo(); +} +/** + * @see org.eclipse.jdt.core.IPackageFragment + */ +public IClassFile[] getClassFiles() throws JavaScriptModelException { + ArrayList list = getChildrenOfType(CLASS_FILE); + IClassFile[] array= new IClassFile[list.size()]; + list.toArray(array); + return array; +} +/** + * @see IPackageFragment#getClassFile(String) + * @exception IllegalArgumentException if the name does not end with ".class" + */ +public IClassFile getClassFile(String classFileName) { + if (!org.eclipse.wst.jsdt.internal.compiler.util.Util.isClassFileName(classFileName) + && !Util.isMetadataFileName(classFileName)) { + throw new IllegalArgumentException(Messages.element_invalidClassFileName); + } + // don't hold on the .class file extension to save memory + // also make sure to not use substring as the resulting String may hold on the underlying char[] which might be much bigger than necessary +// int length = classFileName.length() - SUFFIX_CLASS.length; +// char[] nameWithoutExtension = new char[length]; +// classFileName.getChars(0, length, nameWithoutExtension, 0); + String filename= classFileName; +// if (this.getResource()!=null && this.getResource().getLocation() != null) +// filename= this.getResource().getLocation().toOSString()+IJavaScriptSearchScope.JAR_FILE_ENTRY_SEPARATOR+classFileName; +// else +// filename=getPath().toString() + IJavaScriptSearchScope.JAR_FILE_ENTRY_SEPARATOR + classFileName; + + return (!Util.isMetadataFileName(classFileName)) ? (IClassFile)new ClassFile(this,filename) : (IClassFile)new MetadataFile(this,filename); +} +/** + * A jar package fragment never contains compilation units. + * @see org.eclipse.jdt.core.IPackageFragment + */ +public IJavaScriptUnit[] getCompilationUnits() { + return NO_COMPILATION_UNITS; +} +/** + * A package fragment in a jar has no corresponding resource. + * + * @see IJavaScriptElement + */ +public IResource getCorrespondingResource() { + return null; +} +/** + * Returns an array of non-java resources contained in the receiver. + */ +public Object[] getNonJavaResources() throws JavaScriptModelException { + if (isDefaultPackage()) { + // We don't want to show non java resources of the default package (see PR #1G58NB8) + return JavaElementInfo.NO_NON_JAVA_RESOURCES; + } else { + return storedNonJavaResources(); + } +} +/** + * Jars and jar entries are all read only + */ +public boolean isReadOnly() { + return true; +} +protected Object[] storedNonJavaResources() throws JavaScriptModelException { + return ((JarPackageFragmentInfo) getElementInfo()).getNonJavaResources(); +} +} diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JarPackageFragmentInfo.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JarPackageFragmentInfo.java new file mode 100644 index 00000000..80538d31 --- /dev/null +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JarPackageFragmentInfo.java @@ -0,0 +1,23 @@ +/******************************************************************************* + * Copyright (c) 2000, 2006 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.wst.jsdt.internal.core; + +/** + * Element info for JarPackageFragments. + */ +class JarPackageFragmentInfo extends PackageFragmentInfo { +/** + * Returns an array of non-java resources contained in the receiver. + */ +Object[] getNonJavaResources() { + return this.nonJavaResources; +} +} diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JarPackageFragmentRoot.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JarPackageFragmentRoot.java new file mode 100644 index 00000000..ade94cc2 --- /dev/null +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JarPackageFragmentRoot.java @@ -0,0 +1,300 @@ +/******************************************************************************* + * Copyright (c) 2000, 2012 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.wst.jsdt.internal.core; + +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.Map; +import java.util.zip.ZipEntry; +import java.util.zip.ZipException; +import java.util.zip.ZipFile; + +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.wst.jsdt.internal.core.JavaModelManager; +import org.eclipse.wst.jsdt.internal.core.util.Util; +import org.eclipse.wst.jsdt.core.IJavaScriptElement; +import org.eclipse.wst.jsdt.core.IJavaScriptProject; +import org.eclipse.wst.jsdt.core.IPackageFragment; +import org.eclipse.wst.jsdt.core.IPackageFragmentRoot; +import org.eclipse.wst.jsdt.core.JavaScriptCore; +import org.eclipse.wst.jsdt.core.JavaScriptModelException; +import org.eclipse.wst.jsdt.core.compiler.CharOperation; +import org.eclipse.wst.jsdt.internal.core.util.HashtableOfArrayToObject; + +/** + * A package fragment root that corresponds to a .jar or .zip. + * + *

NOTE: The only visible entries from a .jar or .zip package fragment root + * are .class files. + *

NOTE: A jar package fragment root may or may not have an associated resource. + * + * @see org.eclipse.wst.jsdt.core.IPackageFragmentRoot + * @see org.eclipse.wst.jsdt.internal.core.JarPackageFragmentRootInfo + */ +public class JarPackageFragmentRoot extends PackageFragmentRoot { + + private final static ArrayList EMPTY_LIST = new ArrayList(); + + /** + * The path to the jar file + * (a workspace relative path if the jar is internal, + * or an OS path if the jar is external) + */ + protected final IPath jarPath; + + /** + * Constructs a package fragment root which is the root of the Java package directory hierarchy + * based on a JAR file that is not contained in a IJavaScriptProject and + * does not have an associated IResource. + */ + public JarPackageFragmentRoot(IPath externalJarPath, JavaProject project) { + super(null, project); + this.jarPath = externalJarPath; + } + /** + * Constructs a package fragment root which is the root of the Java package directory hierarchy + * based on a JAR file. + */ + protected JarPackageFragmentRoot(IResource resource, JavaProject project) { + super(resource, project); + this.jarPath = resource.getFullPath(); + } + + /** + * Compute the package fragment children of this package fragment root. + * These are all of the directory zip entries, and any directories implied + * by the path of class files contained in the jar of this package fragment root. + */ + protected boolean computeChildren(OpenableElementInfo info, Map newElements) throws JavaScriptModelException { + HashtableOfArrayToObject rawPackageInfo = new HashtableOfArrayToObject(); + IJavaScriptElement[] children; + ZipFile jar = null; + try { + IJavaScriptProject project = getJavaScriptProject(); + String sourceLevel = project.getOption(JavaScriptCore.COMPILER_SOURCE, true); + String compliance = project.getOption(JavaScriptCore.COMPILER_COMPLIANCE, true); + jar = getJar(); + + // always create the default package + rawPackageInfo.put(CharOperation.NO_STRINGS, new ArrayList[] { EMPTY_LIST, EMPTY_LIST }); + + // loop through all of referenced packages, creating package fragments if necessary + // and cache the entry names in the rawPackageInfo table + for (Enumeration e= jar.entries(); e.hasMoreElements();) { + ZipEntry member= (ZipEntry) e.nextElement(); + initRawPackageInfo(rawPackageInfo, member.getName(), member.isDirectory(), sourceLevel, compliance); + } + + children = new IJavaScriptElement[rawPackageInfo.size()]; + int index = 0; + for (int i = 0, length = rawPackageInfo.keyTable.length; i < length; i++) { + String[] pkgName = (String[]) rawPackageInfo.keyTable[i]; + if (pkgName == null) continue; + children[index++] = getPackageFragment(pkgName); + } + } catch (CoreException e) { + if (e.getCause() instanceof ZipException) { + // not a ZIP archive, leave the children empty + Logger.log(IStatus.ERROR, "Invalid ZIP archive: " + toStringWithAncestors()); //$NON-NLS-1$ + children = NO_ELEMENTS; + } else if (e instanceof JavaScriptModelException) { + throw (JavaScriptModelException)e; + } else { + throw new JavaScriptModelException(e); + } + } finally { + JavaModelManager.getJavaModelManager().closeZipFile(jar); + } + + info.setChildren(children); + ((JarPackageFragmentRootInfo) info).rawPackageInfo = rawPackageInfo; + return true; + } + /** + * Returns a new element info for this element. + */ + protected Object createElementInfo() { + return new JarPackageFragmentRootInfo(); + } + /** + * A Jar is always K_BINARY. + */ + protected int determineKind(IResource underlyingResource) { + return IPackageFragmentRoot.K_BINARY; + } + /** + * Returns true if this handle represents the same jar + * as the given handle. Two jars are equal if they share + * the same zip file. + * + * @see Object#equals + */ + public boolean equals(Object o) { + if (this == o) + return true; + if (o instanceof JarPackageFragmentRoot) { + JarPackageFragmentRoot other= (JarPackageFragmentRoot) o; + return this.jarPath.equals(other.jarPath); + } + return false; + } + /** + * @see IJavaScriptElement + */ + public boolean exists() { + if (isExternal()) + return getPath().toFile().exists() && validateOnClasspath().isOK(); + return super.exists(); + } + public String getElementName() { + return this.jarPath.lastSegment(); + } + /** + * Returns the underlying ZipFile for this Jar package fragment root. + * + * @exception CoreException if an error occurs accessing the jar + */ + public ZipFile getJar() throws CoreException { + return JavaModelManager.getJavaModelManager().getZipFile(getPath()); + } + /** + * @see IPackageFragmentRoot + */ + public int getKind() { + return IPackageFragmentRoot.K_BINARY; + } + int internalKind() throws JavaScriptModelException { + return IPackageFragmentRoot.K_BINARY; + } + /** + * Returns an array of non-java resources contained in the receiver. + */ + public Object[] getNonJavaResources() throws JavaScriptModelException { + // We want to show non java resources of the default package at the root (see PR #1G58NB8) + Object[] defaultPkgResources = ((JarPackageFragment) getPackageFragment(CharOperation.NO_STRINGS)).storedNonJavaResources(); + int length = defaultPkgResources.length; + if (length == 0) + return defaultPkgResources; + Object[] nonJavaResources = new Object[length]; + for (int i = 0; i < length; i++) { + JarEntryResource nonJavaResource = (JarEntryResource) defaultPkgResources[i]; + nonJavaResources[i] = nonJavaResource.clone(this); + } + return nonJavaResources; + } + public PackageFragment getPackageFragment(String[] pkgName) { + return new JarPackageFragment(this, pkgName); + } + /** + * @see IPackageFragmentRoot + */ + public IPackageFragment getPackageFragment(String packageName) { + return getPackageFragment(Util.splitOn('/', packageName, 0, packageName.length())); + } + /* (non-Javadoc) + * @see org.eclipse.wst.jsdt.internal.core.PackageFragmentRoot#getPath() + */ + public IPath getPath() { + if (isExternal()) + return this.jarPath; + return super.getPath(); + } + /** + * @see IJavaScriptElement + */ + public IResource getUnderlyingResource() throws JavaScriptModelException { + if (isExternal()) { + if (!exists()) throw newNotPresentException(); + return null; + } else { + return super.getUnderlyingResource(); + } + } + public int hashCode() { + return this.jarPath.hashCode(); + } + private void initRawPackageInfo(HashtableOfArrayToObject rawPackageInfo, String entryName, boolean isDirectory, String sourceLevel, String compliance) { + int lastSeparator = isDirectory ? entryName.length()-1 : entryName.lastIndexOf('/'); + String[] pkgName = Util.splitOn('/', entryName, 0, lastSeparator); + String[] existing = null; + int length = pkgName.length; + int existingLength = length; + while (existingLength >= 0) { + existing = (String[]) rawPackageInfo.getKey(pkgName, existingLength); + if (existing != null) break; + existingLength--; + } + JavaModelManager manager = JavaModelManager.getJavaModelManager(); + for (int i = existingLength; i < length; i++) { + if (Util.isValidFolderNameForPackage(pkgName[i], sourceLevel, compliance)) { + System.arraycopy(existing, 0, existing = new String[i+1], 0, i); + existing[i] = manager.intern(pkgName[i]); + rawPackageInfo.put(existing, new ArrayList[] { EMPTY_LIST, EMPTY_LIST }); + } else { + // non-Java resource folder + if (!isDirectory) { + ArrayList[] children = (ArrayList[]) rawPackageInfo.get(existing); + if (children[1/*NON_JAVA*/] == EMPTY_LIST) children[1/*NON_JAVA*/] = new ArrayList(); + children[1/*NON_JAVA*/].add(entryName); + } + return; + } + } + if (isDirectory) + return; + + // add classfile info amongst children + ArrayList[] children = (ArrayList[]) rawPackageInfo.get(pkgName); + if (org.eclipse.wst.jsdt.internal.compiler.util.Util.isClassFileName(entryName)) { + if (children[0/*JAVA*/] == EMPTY_LIST) children[0/*JAVA*/] = new ArrayList(); +// String nameWithoutExtension = entryName.substring(lastSeparator + 1, entryName.length() - 3); // length of dot and expected filename extension +// children[0/*JAVA*/].add(nameWithoutExtension); + if (lastSeparator > 0) + children[0/* JAVA */].add(entryName.substring(lastSeparator+1)); + else + children[0/* JAVA */].add(entryName); + } else { + if (children[1/*NON_JAVA*/] == EMPTY_LIST) children[1/*NON_JAVA*/] = new ArrayList(); + children[1/*NON_JAVA*/].add(entryName); + } + + } + /** + * @see IPackageFragmentRoot + */ + public boolean isArchive() { + return true; + } + + /** + * @see IPackageFragmentRoot + */ + public boolean isExternal() { + return resource == null; + } + /** + * Jars and jar entries are all read only + */ + public boolean isReadOnly() { + return true; + } + + protected void toStringAncestors(StringBuffer buffer) { + if (isExternal()) + // don't show project as it is irrelevant for external jar files. + // also see https://bugs.eclipse.org/bugs/show_bug.cgi?id=146615 + return; + super.toStringAncestors(buffer); + } +} diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JarPackageFragmentRootInfo.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JarPackageFragmentRootInfo.java new file mode 100644 index 00000000..6cef43c0 --- /dev/null +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JarPackageFragmentRootInfo.java @@ -0,0 +1,21 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.wst.jsdt.internal.core; + +import org.eclipse.wst.jsdt.internal.core.util.HashtableOfArrayToObject; + +/** + * The element info for JarPackageFragmentRoots. + */ +class JarPackageFragmentRootInfo extends PackageFragmentRootInfo { + // a map from package name (String[]) to a size-2 array of Array, the first element being the .class file names, and the second element being the non-Java resource names + HashtableOfArrayToObject rawPackageInfo; +} diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaCorePreferenceInitializer.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaCorePreferenceInitializer.java index cff4a164..206f97dd 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaCorePreferenceInitializer.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaCorePreferenceInitializer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaModel.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaModel.java index e190c53e..964cda9a 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaModel.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaModel.java @@ -358,10 +358,11 @@ private synchronized static Object getTargetAsExternalFile(IPath path, boolean c } /** - * Helper method - returns whether an object is afile (ie. which returns true to {@link java.io.File#isFile()}. + * Helper method - returns whether an object is a file (ie. which returns true to {@link java.io.File#isFile()}. */ public static boolean isFile(Object target) { - return getFile(target) != null; + File f = getFile(target); + return f != null && f.isFile(); } /** diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaModelManager.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaModelManager.java index 7a217b37..1a1f429f 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaModelManager.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaModelManager.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -108,6 +108,7 @@ import org.eclipse.wst.jsdt.core.compiler.IProblem; import org.eclipse.wst.jsdt.core.compiler.ValidationParticipant; import org.eclipse.wst.jsdt.core.compiler.libraries.LibraryLocation; import org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants; +import org.eclipse.wst.jsdt.core.infer.InferEngine; import org.eclipse.wst.jsdt.internal.codeassist.CompletionEngine; import org.eclipse.wst.jsdt.internal.codeassist.SelectionEngine; import org.eclipse.wst.jsdt.internal.compiler.Compiler; @@ -269,6 +270,7 @@ public class JavaModelManager implements ISaveParticipant, IContentTypeChangeLis private static final String SELECTION_DEBUG = JavaScriptCore.PLUGIN_ID + "/debug/selection" ; //$NON-NLS-1$ private static final String SEARCH_DEBUG = JavaScriptCore.PLUGIN_ID + "/debug/search" ; //$NON-NLS-1$ private static final String SOURCE_MAPPER_DEBUG_VERBOSE = JavaScriptCore.PLUGIN_ID + "/debug/sourcemapper" ; //$NON-NLS-1$ + private static final String INFER_DEBUG = JavaScriptCore.PLUGIN_ID + "/debug/inferEngine" ; //$NON-NLS-1$ public static final String COMPLETION_PERF = JavaScriptCore.PLUGIN_ID + "/perf/completion" ; //$NON-NLS-1$ public static final String SELECTION_PERF = JavaScriptCore.PLUGIN_ID + "/perf/selection" ; //$NON-NLS-1$ @@ -1417,6 +1419,9 @@ public class JavaModelManager implements ISaveParticipant, IContentTypeChangeLis option = Platform.getDebugOption(SOURCE_MAPPER_DEBUG_VERBOSE); if(option != null) SourceMapper.VERBOSE = option.equalsIgnoreCase(TRUE) ; + + option = Platform.getDebugOption(INFER_DEBUG); + if(option != null) InferEngine.DEBUG = option.equalsIgnoreCase(TRUE); } // configure performance options @@ -3825,7 +3830,7 @@ public class JavaModelManager implements ISaveParticipant, IContentTypeChangeLis final Hashtable secondaryTypes = new Hashtable(3); IRestrictedAccessTypeRequestor nameRequestor = new IRestrictedAccessTypeRequestor() { - public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path, AccessRestriction access) { + public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] superTypeNames, char[][] enclosingTypeNames, String path, AccessRestriction access) { String key = packageName==null ? "" : new String(packageName); //$NON-NLS-1$ HashMap types = (HashMap) secondaryTypes.get(key); if (types == null) types = new HashMap(3); diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaProject.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaProject.java index 318eb928..04e4044c 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaProject.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaProject.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -643,20 +643,26 @@ public class JavaProject if (target instanceof IResource){ // internal target - root = getPackageFragmentRoot((IResource) target); + if (((IResource) target).getType() == IResource.FILE && org.eclipse.wst.jsdt.internal.compiler.util.Util.isArchiveFileName(entryPath.lastSegment())) { + root = new JarPackageFragmentRoot((IResource) target, this); + } + else { + root = getPackageFragmentRoot((IResource) target); + } } else { - // external target - only JARs allowed + // external target - JARs, *.js, or directory allowed if (JavaModel.isFile(target)) { - if (true) {//org.eclipse.wst.jsdt.internal.compiler.util.Util.isJavaFileName(entryPath.lastSegment())) { - root = new LibraryFragmentRoot(entryPath, this); - - } - else - { -// root = new JarPackageFragmentRoot(entryPath, this); - - } + if (org.eclipse.wst.jsdt.internal.compiler.util.Util.isArchiveFileName(entryPath.lastSegment())) + { + root = new JarPackageFragmentRoot(entryPath, this); + } + else if (org.eclipse.wst.jsdt.internal.compiler.util.Util.isJavaFileName(entryPath.lastSegment())) { + root = new LibraryFragmentRoot(entryPath, this); + } + } + else { + root = new LibraryFragmentRoot(entryPath, this); } } } else { @@ -716,7 +722,7 @@ public class JavaProject accumulatedRoots, new HashSet(5), // rootIDs null, // inside original project - true, // check existency + true, // check existence retrieveExportedRoots, rootToResolvedEntries); IPackageFragmentRoot[] rootArray = new IPackageFragmentRoot[accumulatedRoots.size()]; @@ -1852,7 +1858,7 @@ public class JavaProject switch (resource.getType()) { case IResource.FILE: if (org.eclipse.wst.jsdt.internal.compiler.util.Util.isArchiveFileName(resource.getName())) { -// return new JarPackageFragmentRoot(resource, this); + return new JarPackageFragmentRoot(resource, this); } else { return null; } @@ -1877,7 +1883,8 @@ public class JavaProject * no path canonicalization */ public IPackageFragmentRoot getPackageFragmentRoot0(IPath jarPath) { - + if (org.eclipse.wst.jsdt.internal.compiler.util.Util.isArchiveFileName(jarPath.lastSegment())) + return new JarPackageFragmentRoot(jarPath, this); return new LibraryFragmentRoot(jarPath, this); } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaProjectElementInfo.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaProjectElementInfo.java index e49853ea..9d599377 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaProjectElementInfo.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/JavaProjectElementInfo.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -249,7 +249,7 @@ class JavaProjectElementInfo extends OpenableElementInfo { IJavaScriptElement[] frags = null; try { if (!root.isOpen()) { - PackageFragmentRootInfo info = new PackageFragmentRootInfo(); + PackageFragmentRootInfo info = (PackageFragmentRootInfo) ((PackageFragmentRoot) root).createElementInfo(); ((PackageFragmentRoot) root).computeChildren(info, new HashMap()); frags = info.children; } else diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/Member.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/Member.java index 15d686a8..32658098 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/Member.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/Member.java @@ -227,9 +227,59 @@ public IJavaScriptElement getHandleFromMemento(String token, MementoTokenizer me if (!memento.hasMoreTokens()) return this; String typeSignature = memento.nextToken(); return new LocalVariable(this, varName, declarationStart, declarationEnd, nameStart, nameEnd, typeSignature); + case JEM_METHOD: + if (!memento.hasMoreTokens()) return this; + String selector = memento.nextToken(); + ArrayList params = new ArrayList(); + nextParam: while (memento.hasMoreTokens()) { + token = memento.nextToken(); + switch (token.charAt(0)) { + case JEM_TYPE: + case JEM_TYPE_PARAMETER: + break nextParam; +// case JEM_METHOD: +// if (!memento.hasMoreTokens()) return this; +// String param = memento.nextToken(); +// StringBuffer buffer = new StringBuffer(); +// while (param.length() == 1 && Signature.C_ARRAY == param.charAt(0)) { // backward compatible with 3.0 mementos +// buffer.append(Signature.C_ARRAY); +// if (!memento.hasMoreTokens()) return this; +// param = memento.nextToken(); +// } +// params.add(buffer.toString() + param); +// break; + default: + break nextParam; + } + } + String[] parameters = new String[params.size()]; + params.toArray(parameters); + JavaElement method = (JavaElement)getFunction(selector, parameters); + if (token.charAt(0) == JEM_COUNT) { + if (!memento.hasMoreTokens()) return method; + memento.nextToken(); // JEM_COUNT + if (!memento.hasMoreTokens()) return method; + token = memento.nextToken(); + } + switch (token.charAt(0)) { + case JEM_TYPE: + case JEM_TYPE_PARAMETER: + case JEM_LOCALVARIABLE: + return method.getHandleFromMemento(token, memento, workingCopyOwner); + case JEM_METHOD: + if (memento.hasMoreTokens()) + return method.getHandleFromMemento(token, memento, workingCopyOwner); + default: + return method; + } } return null; } + +public IFunction getFunction(String selector, String[] parameterTypeSignatures) { + return new SourceMethod(this, selector, parameterTypeSignatures); +} + /** * @see JavaElement#getHandleMemento() */ diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/MetadataFile.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/MetadataFile.java index a000d270..8c494ac7 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/MetadataFile.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/MetadataFile.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2011 IBM Corporation and others. + * Copyright (c) 2005, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -137,11 +137,11 @@ public class MetadataFile extends Openable implements IFile file = (IFile) getResource(); try { apis = MetadataReader.readAPIsFromStream(new InputSource(file.getContents()),file.getLocation().toOSString()); - apis.fileName=file.getFullPath().toOSString().toCharArray(); + apis.fileName=file.getFullPath().toPortableString().toCharArray(); } catch (Exception e) { Util.log(e, "error reading metadata"); apis=new LibraryAPIs(); - apis.fileName=file.getFullPath().toOSString().toCharArray(); + apis.fileName=file.getFullPath().toPortableString().toCharArray(); } } return apis; @@ -379,8 +379,7 @@ public class MetadataFile extends Openable implements public String getTypeName() { // Internal class file name doesn't contain ".class" file extension - int lastDollar = this.name.lastIndexOf('$'); - return lastDollar > -1 ? Util.localTypeName(this.name, lastDollar, this.name.length()) : this.name; + return this.name; } public boolean equals(Object o) { diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/NameLookup.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/NameLookup.java index aaf43abf..6ae3c1ea 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/NameLookup.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/NameLookup.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -307,7 +307,8 @@ public class NameLookup implements SuffixConstants { String path, AccessRestriction access) { if (excludePath!=null && path.equals(excludePath)) return false; - foundPaths.add(path); + if(!foundPaths.contains(path)) + foundPaths.add(path); return true; } /* (non-Javadoc) @@ -499,10 +500,6 @@ public class NameLookup implements SuffixConstants { cuName= qualifiedTypeName.substring(index + 1); } cuName=cuName.replace(CompilationUnitScope.FILENAME_DOT_SUBSTITUTION, '.'); - index= cuName.indexOf('$'); - if (index != -1) { - cuName= cuName.substring(0, index); - } Object value = this.packageFragments.get(pkgName); if (value != null) { if (value instanceof PackageFragmentRoot) { @@ -1463,7 +1460,6 @@ public class NameLookup implements SuffixConstants { // look in model switch (packageFlavor) { case IPackageFragmentRoot.K_BINARY : - matchName= matchName.replace('.', '$'); seekBindingsInBinaryPackage(matchName,Binding.TYPE, pkg, partialMatch, acceptFlags, requestor); break; case IPackageFragmentRoot.K_SOURCE : @@ -1511,7 +1507,6 @@ public class NameLookup implements SuffixConstants { // look in model switch (packageFlavor) { case IPackageFragmentRoot.K_BINARY : -// matchName= matchName.replace('.', '$'); seekBindingsInBinaryPackage(matchName, bindingType,pkg, partialMatch, acceptFlags, requestor); break; case IPackageFragmentRoot.K_SOURCE : @@ -1683,13 +1678,6 @@ public class NameLookup implements SuffixConstants { } } else { String unqualifiedName = name; - int index = name.lastIndexOf('$'); - if (index != -1) { - //the type name of the inner type - unqualifiedName = Util.localTypeName(name, index, name.length()); - // unqualifiedName is empty if the name ends with a '$' sign. - // See http://dev.eclipse.org/bugs/show_bug.cgi?id=14642 - } int matchLength = name.length(); for (int i = 0; i < length; i++) { if (requestor.isCanceled()) @@ -2145,6 +2133,9 @@ public class NameLookup implements SuffixConstants { Path excludePath= (exclude!=null)? new Path(exclude) : null; MyRequestor requestor=new MyRequestor(); + JavaElementRequestor elementRequestor = new JavaElementRequestor(); +// seekPackageFragments(packageName, false, elementRequestor); +// IPackageFragment[] packages= elementRequestor.getPackageFragments(); seekBindingsInWorkingCopies(bindingName, bindingType, -1, partialMatch, bindingName, acceptFlags, requestor); if (requestor.element != null) { diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/NamedMember.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/NamedMember.java index 08d7d862..17692f88 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/NamedMember.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/NamedMember.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2004, 2009 IBM Corporation and others. + * Copyright (c) 2004, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -112,15 +112,12 @@ public abstract class NamedMember extends Member { key.append(packageName.replace('.', '/')); if (packageName.length() > 0) key.append('/'); - String typeQualifiedName = type.getTypeQualifiedName('$'); + String typeQualifiedName = type.getTypeQualifiedName(); IJavaScriptUnit cu = (IJavaScriptUnit) type.getAncestor(IJavaScriptElement.JAVASCRIPT_UNIT); if (cu != null) { String cuName = cu.getElementName(); String mainTypeName = cuName.substring(0, cuName.lastIndexOf('.')); - int end = typeQualifiedName.indexOf('$'); - if (end == -1) - end = typeQualifiedName.length(); - String topLevelTypeName = typeQualifiedName.substring(0, end); + String topLevelTypeName = typeQualifiedName; if (!mainTypeName.equals(topLevelTypeName)) { key.append(mainTypeName); key.append('~'); @@ -171,14 +168,8 @@ public abstract class NamedMember extends Member { return this.name; case IJavaScriptElement.CLASS_FILE: String classFileName = this.parent.getElementName(); - String typeName; - if (classFileName.indexOf('$') == -1) { // top level class file: name of type is same as name of class file - typeName = this.name; - } else { - // anonymous or local class file - typeName = classFileName.substring(0, classFileName.lastIndexOf('.')); // remove .class - } + String typeName = this.name; if (showParameters) { StringBuffer buffer = new StringBuffer(typeName); return buffer.toString(); diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/PackageFragment.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/PackageFragment.java index 05465998..fb96415c 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/PackageFragment.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/PackageFragment.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -24,7 +24,6 @@ import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.Path; -import org.eclipse.osgi.util.NLS; import org.eclipse.wst.jsdt.core.IClassFile; import org.eclipse.wst.jsdt.core.IJavaScriptElement; import org.eclipse.wst.jsdt.core.IJavaScriptModelStatusConstants; @@ -185,12 +184,12 @@ public boolean exists() { } /** * @see IPackageFragment#getClassFile(String) - * @exception IllegalArgumentException if the name does not end with ".js" + * @exception IllegalArgumentException if the name does not end with ".class" */ public IClassFile getClassFile(String classFileName) { if (!org.eclipse.wst.jsdt.internal.compiler.util.Util.isClassFileName(classFileName) && !Util.isMetadataFileName(classFileName)) { - throw new IllegalArgumentException(NLS.bind(Messages.element_invalidClassFileName, classFileName)); + throw new IllegalArgumentException(Messages.element_invalidClassFileName); } // don't hold on the .class file extension to save memory // also make sure to not use substring as the resulting String may hold on the underlying char[] which might be much bigger than necessary @@ -198,7 +197,7 @@ public IClassFile getClassFile(String classFileName) { // char[] nameWithoutExtension = new char[length]; // classFileName.getChars(0, length, nameWithoutExtension, 0); String filename= ""; - if (this.getResource()!=null) + if (this.getResource()!=null && this.getResource().getLocation() != null) filename= this.getResource().getLocation().toOSString()+File.separator+classFileName; else filename=classFileName; diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/PackageFragmentRoot.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/PackageFragmentRoot.java index d610f15e..d352ccb7 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/PackageFragmentRoot.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/PackageFragmentRoot.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -187,7 +187,7 @@ protected boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, // check whether this pkg fragment root can be opened IStatus status = validateOnClasspath(); if (!status.isOK()) throw newJavaModelException(status); - if (!resourceExists()) throw newNotPresentException(); + if (!isExternal() && !resourceExists()) throw newNotPresentException(); ((PackageFragmentRootInfo) info).setRootKind(determineKind(underlyingResource)); return computeChildren(info, newElements); @@ -319,7 +319,7 @@ public void copy( } /** - * Returns a new element info for this element. + * Returns a new element info for this element. Subclasses MUST return a subclass of PackageFragmentRootInfo */ protected Object createElementInfo() { return new PackageFragmentRootInfo(); @@ -346,7 +346,7 @@ protected int determineKind(IResource underlyingResource) throws JavaScriptModel if (entry != null) { return entry.getContentKind(); } - return IPackageFragmentRoot.K_SOURCE; + return org.eclipse.wst.jsdt.internal.compiler.util.Util.isArchiveFileName(underlyingResource.getName()) ? IPackageFragmentRoot.K_BINARY : IPackageFragmentRoot.K_SOURCE; } /** diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ReconcileWorkingCopyOperation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ReconcileWorkingCopyOperation.java index 7fcf5b3e..4eff033c 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ReconcileWorkingCopyOperation.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/ReconcileWorkingCopyOperation.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2012 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -17,17 +17,17 @@ import java.util.Map; import org.eclipse.core.runtime.ISafeRunnable; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.SafeRunner; +import org.eclipse.wst.jsdt.core.IJavaScriptUnit; import org.eclipse.wst.jsdt.core.IJavaScriptElement; import org.eclipse.wst.jsdt.core.IJavaScriptModelStatus; import org.eclipse.wst.jsdt.core.IJavaScriptModelStatusConstants; import org.eclipse.wst.jsdt.core.IJavaScriptProject; -import org.eclipse.wst.jsdt.core.IJavaScriptUnit; import org.eclipse.wst.jsdt.core.IProblemRequestor; import org.eclipse.wst.jsdt.core.JavaScriptModelException; import org.eclipse.wst.jsdt.core.WorkingCopyOwner; import org.eclipse.wst.jsdt.core.compiler.CategorizedProblem; -import org.eclipse.wst.jsdt.core.compiler.ReconcileContext; import org.eclipse.wst.jsdt.core.compiler.ValidationParticipant; +import org.eclipse.wst.jsdt.core.compiler.ReconcileContext; import org.eclipse.wst.jsdt.core.dom.AST; import org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.wst.jsdt.internal.core.util.Messages; @@ -234,8 +234,8 @@ public class ReconcileWorkingCopyOperation extends JavaModelOperation { } finally { if (unit != null) { unit.cleanUp(); - if (unit.scope!=null) - unit.scope.cleanup(); + if (unit.scope!=null) + unit.scope.cleanup(); } } return this.ast; diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SearchableEnvironment.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SearchableEnvironment.java index 3dd28835..595bdf90 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SearchableEnvironment.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SearchableEnvironment.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -37,8 +37,11 @@ import org.eclipse.wst.jsdt.internal.compiler.env.NameEnvironmentAnswer; import org.eclipse.wst.jsdt.internal.compiler.impl.ITypeRequestor; import org.eclipse.wst.jsdt.internal.core.search.BasicSearchEngine; import org.eclipse.wst.jsdt.internal.core.search.IConstructorRequestor; +import org.eclipse.wst.jsdt.internal.core.search.IFunctionRequester; import org.eclipse.wst.jsdt.internal.core.search.IRestrictedAccessBindingRequestor; import org.eclipse.wst.jsdt.internal.core.search.IRestrictedAccessTypeRequestor; +import org.eclipse.wst.jsdt.internal.core.search.IVariableRequester; +import org.eclipse.wst.jsdt.internal.core.search.indexing.IIndexConstants; /** * This class provides a SearchableBuilderEnvironment for code @@ -76,13 +79,7 @@ public class SearchableEnvironment implements INameEnvironment, this.nameLookup = javaProject.newNameLookup(workingCopies); this.nameLookup.setRestrictedAccessRequestor(resolutionScope); // Create search scope with visible entry on the project's classpath - if (false){//this.checkAccessRestrictions) { - this.searchScope = BasicSearchEngine - .createJavaSearchScope(this.nameLookup.packageFragmentRoots ); - } else { - this.searchScope = BasicSearchEngine - .createJavaSearchScope(this.nameLookup.packageFragmentRoots); - } + this.searchScope = BasicSearchEngine.createJavaSearchScope(this.nameLookup.packageFragmentRoots); this.nameLookup.searchScope=this.searchScope; } public SearchableEnvironment(JavaProject project, @@ -168,16 +165,10 @@ public class SearchableEnvironment implements INameEnvironment, 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) + //check that the index is in bounds (see Bug 62861) + if (!otherType.equals(topLevelType) && index < length) { sourceTypes[index++] = otherType; + } } return new NameEnvironmentAnswer(sourceTypes, answer.restriction); @@ -231,8 +222,6 @@ public class SearchableEnvironment implements INameEnvironment, System.arraycopy(elements, 0, units, 0, elements.length); return new NameEnvironmentAnswer(units,answer.restriction); } - // return new NameEnvironmentAnswer((IBinaryType) ((BinaryType) - // answer.type).getElementInfo(), answer.restriction); } return null; } @@ -278,35 +267,8 @@ public class SearchableEnvironment implements INameEnvironment, excludePath = null; } - IProgressMonitor progressMonitor = new IProgressMonitor() { - boolean isCanceled = false; - public void beginTask(String n, int totalWork) { - // implements interface method - } - public void done() { - // implements interface method - } - public void internalWorked(double work) { - // implements interface method - } - public boolean isCanceled() { - return isCanceled; - } - public void setCanceled(boolean value) { - isCanceled = value; - } - public void setTaskName(String n) { - // implements interface method - } - public void subTask(String n) { - // implements interface method - } - public void worked(int work) { - // implements interface method - } - }; IRestrictedAccessTypeRequestor typeRequestor = new IRestrictedAccessTypeRequestor() { - public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path, AccessRestriction access) { + public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] superTypeNames, char[][] enclosingTypeNames, String path, AccessRestriction access) { if (excludePath != null && excludePath.equals(path)) return; if (!findMembers && enclosingTypeNames != null && enclosingTypeNames.length > 0) @@ -316,15 +278,12 @@ public class SearchableEnvironment implements INameEnvironment, }; try { new BasicSearchEngine(this.workingCopies).searchAllTypeNames( - null, - SearchPattern.R_EXACT_MATCH, name, SearchPattern.R_EXACT_MATCH, - searchFor, this.searchScope, typeRequestor, CANCEL_IF_NOT_READY_TO_SEARCH, - progressMonitor); + new CancelableProgressMonitor()); } catch (OperationCanceledException e) { findExactTypes( new String(name), @@ -433,72 +392,10 @@ public class SearchableEnvironment implements INameEnvironment, } else { excludePath = null; } - - //int lastDotIndex = CharOperation.lastIndexOf('.', prefix); - // just use the simple name field to hold the full type name - char[] qualification, simpleName; - qualification = null; - if (camelCaseMatch) { - simpleName = prefix; - } else { - simpleName = CharOperation.toLowerCase(prefix); - } - -// if (lastDotIndex < 0 || true) { -// 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; - - public void beginTask(String name, int totalWork) { - // implements interface method - } - public void done() { - // implements interface method - } - - public void internalWorked(double work) { - // implements interface method - } - - public boolean isCanceled() { - return isCanceled; - } - - public void setCanceled(boolean value) { - isCanceled = value; - } - - public void setTaskName(String name) { - // implements interface method - } - - public void subTask(String name) { - // implements interface method - } - - public void worked(int work) { - // implements interface method - } - }; + IProgressMonitor progressMonitor = new CancelableProgressMonitor(); IRestrictedAccessTypeRequestor typeRequestor = new IRestrictedAccessTypeRequestor() { - public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path, AccessRestriction access) { + public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] superTypeNames, char[][] enclosingTypeNames, String path, AccessRestriction access) { if (excludePath != null && excludePath.equals(path)) return; if (!findMembers && enclosingTypeNames != null && enclosingTypeNames.length > 0) @@ -507,15 +404,15 @@ public class SearchableEnvironment implements INameEnvironment, } }; try { - int matchRule = SearchPattern.R_PREFIX_MATCH; - if (camelCaseMatch) + //set the match rule + int matchRule = SearchPattern.R_PREFIX_MATCH ; + if (camelCaseMatch) { matchRule |= SearchPattern.R_CAMELCASE_MATCH; + } + new BasicSearchEngine(this.workingCopies).searchAllTypeNames( - qualification, - SearchPattern.R_EXACT_MATCH, - simpleName, + prefix, matchRule, // not case sensitive - searchFor, this.searchScope, typeRequestor, CANCEL_IF_NOT_READY_TO_SEARCH, progressMonitor); @@ -527,8 +424,6 @@ public class SearchableEnvironment implements INameEnvironment, } } - - /** * Find the top-level types (classes and interfaces) that are defined in the * current environment and whose name starts with the given prefix. The @@ -586,41 +481,8 @@ public class SearchableEnvironment implements INameEnvironment, } } - IProgressMonitor progressMonitor = new IProgressMonitor() { - boolean isCanceled = false; - - public void beginTask(String name, int totalWork) { - // implements interface method - } - - public void done() { - // implements interface method - } - - public void internalWorked(double work) { - // implements interface method - } - - public boolean isCanceled() { - return isCanceled; - } - - public void setCanceled(boolean value) { - isCanceled = value; - } - - public void setTaskName(String name) { - // implements interface method - } - - public void subTask(String name) { - // implements interface method - } - - public void worked(int work) { - // implements interface method - } - }; + IProgressMonitor progressMonitor = new CancelableProgressMonitor(); + IRestrictedAccessBindingRequestor bindingRequestor = new IRestrictedAccessBindingRequestor() { String exclude; public boolean acceptBinding(int type,int modifiers, char[] packageName, @@ -674,6 +536,138 @@ public class SearchableEnvironment implements INameEnvironment, findTypes(new String(prefix), storage, NameLookup.ACCEPT_ALL); } } + + /** + *

Used to find all functions in the environment using the given information.

+ * + *

NOTE: this function will currently ignore any results either from the index + * or working copies from the {@link #unitToSkip}.

+ * + * @param selectorPrefix prefix to the selector to search for functions matches for, or + * null to search for functions with any selector. The null + * option is useful when searching for all functions on a given type. + * @param declaringTypeName fully qualified type name that any function results should be + * defined on, or null if the function results should not be defined on any type + * @param searchRequester search requester to return any search results too + */ + public void findFunctions(char[] selectorPrefix, char[][] declaringTypeNames, boolean camelCaseMatch, final ISearchRequestor searchRequester) { + //calculate the exclude path + final String excludePath; + if (this.unitToSkip != null && this.unitToSkip instanceof IJavaScriptElement) { + excludePath = ((IJavaScriptElement)this.unitToSkip).getPath().toString(); + } else { + excludePath = null; + } + + //create the requester + IFunctionRequester functionRequestor = new IFunctionRequester() { + public void acceptFunction(char[] signature, + char[][] parameterFullyQualifiedTypeNames, + char[][] parameterNames, + char[] returnQualification, char[] returnSimpleName, + char[] declaringQualification, char[] declaringSimpleName, + int modifiers, + String path) { + + if (excludePath == null || !excludePath.equals(path)) { + searchRequester.acceptFunction(signature, parameterFullyQualifiedTypeNames, parameterNames, + returnQualification, returnSimpleName, declaringQualification, declaringSimpleName, modifiers, path); + } + } + }; + + /* if selector specified then search for any selector with the given selector as a prefix + * else search for any selector + */ + char[] selectorPattern; + int selectorPatternMatchRule; + if(selectorPrefix != null) { + selectorPattern = selectorPrefix; + selectorPatternMatchRule = SearchPattern.R_PREFIX_MATCH; + } else { + selectorPattern = new char[] {'*'}; + selectorPatternMatchRule = SearchPattern.R_PATTERN_MATCH; + } + + + if (camelCaseMatch) + selectorPatternMatchRule |= SearchPattern.R_CAMELCASE_MATCH; + + //do the search + new BasicSearchEngine(this.workingCopies).searchAllFunctions( + functionRequestor, + selectorPattern, + declaringTypeNames, + selectorPatternMatchRule, + this.searchScope, + WAIT_UNTIL_READY_TO_SEARCH, + new CancelableProgressMonitor()); + } + + /** + *

Used to find all varaibles in the environment using the given information.

+ * + *

NOTE: this function will currently ignore any results either from the index + * or working copies from the {@link #unitToSkip}.

+ * + * @param variablePrefix prefix to the variable to search for matches,, or + * null to search for variables with any selector. The null + * option is useful when searching for all variables on a given type. + * @param declaringTypeName fully qualified type name that any variable results should be + * defined on, or null if the function results should not be defined on any type + * @param searchRequester search requester to return any search results too + */ + public void findVariables(char[] variablePrefix, char[][] declaringTypeNames, boolean camelCaseMatch, final ISearchRequestor searchRequester) { + //calculate the exclude path + final String excludePath; + if (this.unitToSkip != null && this.unitToSkip instanceof IJavaScriptElement) { + excludePath = ((IJavaScriptElement)this.unitToSkip).getPath().toString(); + } else { + excludePath = null; + } + + //create the requester + IVariableRequester variableRequestor = new IVariableRequester() { + public void acceptVariable(char[] signature, + char[] typeQualification, char[] typeSimpleName, + char[] declaringQualification, char[] declaringSimpleName, + int modifiers, + String path) { + + if (excludePath == null || !excludePath.equals(path)) { + searchRequester.acceptVariable(signature, typeQualification, typeSimpleName, + declaringQualification, declaringSimpleName, modifiers, path); + } + } + }; + + /* if selector specified then search for any selector with the given selector as a prefix + * else search for any selector + */ + char[] variablePattern; + int variablePatternMatchRule; + if(variablePrefix != null) { + variablePattern = variablePrefix; + variablePatternMatchRule = SearchPattern.R_PREFIX_MATCH; + } else { + variablePattern = new char[] {'*'}; + variablePatternMatchRule = SearchPattern.R_PATTERN_MATCH; + } + + + if (camelCaseMatch) + variablePatternMatchRule |= SearchPattern.R_CAMELCASE_MATCH; + + //do the search + new BasicSearchEngine(this.workingCopies).searchAllVariables( + variableRequestor, + variablePattern, + declaringTypeNames, + variablePatternMatchRule, + this.searchScope, + WAIT_UNTIL_READY_TO_SEARCH, + new CancelableProgressMonitor()); + } /** *

The progress monitor is used to be able to cancel completion operations

@@ -689,7 +683,7 @@ public class SearchableEnvironment implements INameEnvironment, * @param prefix to use in the search * @param storage to report constructor declarations matching the given prefix to */ - public void findConstructorDeclarations(char[] prefix, final ISearchRequestor storage) { + public void findConstructorDeclarations(char[] prefix, boolean camelCaseMatch, final ISearchRequestor storage) { final String excludePath; if (this.unitToSkip != null && this.unitToSkip instanceof IJavaScriptElement) { excludePath = ((IJavaScriptElement) this.unitToSkip).getPath().toString(); @@ -697,33 +691,7 @@ public class SearchableEnvironment implements INameEnvironment, excludePath = null; } - IProgressMonitor progressMonitor = new IProgressMonitor() { - boolean isCanceled = false; - public void beginTask(String name, int totalWork) { - // implements interface method - } - public void done() { - // implements interface method - } - public void internalWorked(double work) { - // implements interface method - } - public boolean isCanceled() { - return this.isCanceled; - } - public void setCanceled(boolean value) { - this.isCanceled = value; - } - public void setTaskName(String name) { - // implements interface method - } - public void subTask(String name) { - // implements interface method - } - public void worked(int work) { - // implements interface method - } - }; + IProgressMonitor progressMonitor = new CancelableProgressMonitor(); IConstructorRequestor constructorRequestor = new IConstructorRequestor() { /** @@ -745,7 +713,6 @@ public class SearchableEnvironment implements INameEnvironment, storage.acceptConstructor( modifiers, typeName, - parameterCount, parameterTypes, parameterNames, path, @@ -753,21 +720,15 @@ public class SearchableEnvironment implements INameEnvironment, } }; - /* when matching on "Test|" will match on - * Test - * TestBar - * foo.Test - * foo.TestBar - * test.foo.Bar - */ - int matchRule = SearchPattern.R_REGEXP_MATCH; - String escapedPrefix = new String(prefix); - escapedPrefix.replaceAll("\\.", "\\."); //replace all "." with "\." - String regex = "(.*\\." + escapedPrefix + "[^\\.]*)|(" + escapedPrefix + ".*)"; + //set the match rule + int matchRule = SearchPattern.R_PREFIX_MATCH ; + if (camelCaseMatch) { + matchRule |= SearchPattern.R_CAMELCASE_MATCH; + } try { new BasicSearchEngine(this.workingCopies).searchAllConstructorDeclarations( - regex.toCharArray(), + prefix, matchRule, this.searchScope, constructorRequestor, @@ -817,21 +778,84 @@ public class SearchableEnvironment implements INameEnvironment, this.nameLookup.seekBindings(prefix, bindingType,null, true, type, requestor); } else { throw new UnimplementedException("shouldnt get here"); //$NON-NLS-1$ -// 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); -// } } } + + public ArrayList findSuperTypes(char[] typeName) { + final ArrayList superTypes = new ArrayList(); + final ArrayList queue = new ArrayList(); + final ArrayList alreadySearched = new ArrayList(); + + /* + * if (true){ findTypes(new String(prefix), storage, + * NameLookup.ACCEPT_CLASSES | NameLookup.ACCEPT_INTERFACES); return; + * } + */ + try { + final String excludePath; + if (this.unitToSkip != null) { + excludePath = ((IJavaScriptElement) this.unitToSkip).getPath().toString(); + } + else { + excludePath = null; + } + + // int lastDotIndex = CharOperation.lastIndexOf('.', prefix); + // just use the simple name field to hold the full type name + char[] qualification, simpleName; + qualification = null; + + simpleName = CharOperation.toLowerCase(typeName); + + queue.add(simpleName); + IRestrictedAccessTypeRequestor typeRequestor = new IRestrictedAccessTypeRequestor() { + public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] superTypeNames, char[][] enclosingTypeNames, String path, AccessRestriction access) { + if (excludePath != null && excludePath.equals(path)) + return; + boolean doAdd = true; + for (int i = 0; i < superTypes.size(); i++) { + if (CharOperation.equals(superTypeNames[0], (char[]) superTypes.get(i))) { + doAdd = false; + break; + } + } + if (doAdd) + superTypes.add(superTypeNames[0]); + queue.add(superTypeNames[0]); + } + }; + try { + while (!queue.isEmpty()) { + char[] nextSearch = (char[]) queue.get(0); + boolean doSearch = true; + if (CharOperation.equals(nextSearch, IIndexConstants.OBJECT)) + doSearch = false; + + for (int i = 0; doSearch && i < alreadySearched.size(); i++) { + if (CharOperation.equals(nextSearch, (char[]) alreadySearched.get(i))) { + doSearch = false; + } + } + if (doSearch) { + alreadySearched.add(nextSearch); + new BasicSearchEngine(this.workingCopies).searchAllTypeNames(qualification, nextSearch, SearchPattern.R_EXACT_MATCH, //not case sensitive + this.searchScope, typeRequestor, WAIT_UNTIL_READY_TO_SEARCH, new CancelableProgressMonitor()); + + } + queue.remove(0); + doSearch = true; + } + } + catch (OperationCanceledException e) { + } + } + catch (JavaScriptModelException e) { + } + return superTypes; + } + + + /** * @see org.eclipse.wst.jsdt.internal.compiler.env.INameEnvironment#isPackage(char[][], * char[]) @@ -877,4 +901,35 @@ public class SearchableEnvironment implements INameEnvironment, { nameLookup.setScriptFile(file); } + + /** + *

A cancelable progress monitor

+ */ + private static class CancelableProgressMonitor implements IProgressMonitor { + boolean isCanceled = false; + public void beginTask(String name, int totalWork) { + // implements interface method + } + public void done() { + // implements interface method + } + public void internalWorked(double work) { + // implements interface method + } + public boolean isCanceled() { + return this.isCanceled; + } + public void setCanceled(boolean value) { + this.isCanceled = value; + } + public void setTaskName(String name) { + // implements interface method + } + public void subTask(String name) { + // implements interface method + } + public void worked(int work) { + // implements interface method + } + } } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SelectionRequestor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SelectionRequestor.java index 7f7d7297..d505c867 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SelectionRequestor.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SelectionRequestor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -387,7 +387,7 @@ public void acceptLocalVariable(LocalVariableBinding binding) { parent=resolveCompilationUnit(packageName, fileName); if(parent==null) { - parent=resolveCompilationUnit(new char[0], fileName); + parent=resolveCompilationUnit(CharOperation.NO_CHAR, fileName); } } else parent = findLocalElement(local.sourceStart); // findLocalElement() cannot find local variable @@ -822,7 +822,7 @@ protected IType resolveType(char[] packageName, char[] fileName, char[] typeName if (this.openable != null && this.openable.getParent().getElementName().equals(pName)) { // look inside the type in which we are resolving in String tName= new String(typeName); - tName = tName.replace('.','$'); +// tName = tName.replace('.','$'); IType[] allTypes= null; try { ArrayList list = this.openable.getChildrenOfType(IJavaScriptElement.TYPE); @@ -983,7 +983,7 @@ protected IType resolveTypeByLocation(char[] packageName, char[] typeName, int a if (this.openable != null && this.openable.getParent().getElementName().equals(pName)) { // look inside the type in which we are resolving in String tName= new String(typeName); - tName = tName.replace('.','$'); +// tName = tName.replace('.','$'); IType[] allTypes= null; try { ArrayList list = this.openable.getChildrenOfType(IJavaScriptElement.TYPE); diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceConstructorInfo.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceConstructorInfo.java index 6372ebb9..96e2acc3 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceConstructorInfo.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceConstructorInfo.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2004, 2007 IBM Corporation and others. + * Copyright (c) 2004, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceMapper.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceMapper.java index 8872389d..c52b1e57 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceMapper.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceMapper.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -1057,23 +1057,23 @@ public class SourceMapper * fully qualified so that the correct source is found. */ protected IJavaScriptElement[] getUnqualifiedMethodHandle(IFunction method, boolean noDollar) { - boolean hasDollar = false; +// boolean hasDollar = false; String[] qualifiedParameterTypes = method.getParameterTypes(); String[] unqualifiedParameterTypes = new String[qualifiedParameterTypes.length]; for (int i = 0; i < qualifiedParameterTypes.length; i++) { StringBuffer unqualifiedTypeSig = new StringBuffer(); getUnqualifiedTypeSignature(qualifiedParameterTypes[i], 0/*start*/, qualifiedParameterTypes[i].length(), unqualifiedTypeSig, noDollar); unqualifiedParameterTypes[i] = unqualifiedTypeSig.toString(); - hasDollar |= unqualifiedParameterTypes[i].lastIndexOf('$') != -1; +// hasDollar |= unqualifiedParameterTypes[i].lastIndexOf('$') != -1; } IJavaScriptElement[] result = new IJavaScriptElement[2]; result[0] = ((IType) method.getParent()).getFunction( method.getElementName(), unqualifiedParameterTypes); - if(hasDollar) { - result[1] = result[0]; - } +// if(hasDollar) { +// result[1] = result[0]; +// } return result; } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceMethod.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceMethod.java index 4d6dafc4..d48a89f9 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceMethod.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceMethod.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -153,10 +153,6 @@ public int hashCode() { * @see IFunction */ public boolean isConstructor() throws JavaScriptModelException { - if (!this.getElementName().equals(this.parent.getElementName())) { - // faster than reaching the info - return false; - } SourceMethodElementInfo info = (SourceMethodElementInfo) getElementInfo(); return info.isConstructor(); } @@ -274,4 +270,11 @@ public IFunction getFunction(String selector, String[] parameterTypeSignatures) } +public String getDisplayName() { + String displayName = super.getDisplayName(); + if (displayName.equals("___anonymous")) //$NON-NLS-1$ + displayName = ""; //$NON-NLS-1$ + return displayName; +} + } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceMethodInfo.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceMethodInfo.java index bd255c9c..24fd34df 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceMethodInfo.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceMethodInfo.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2004, 2007 IBM Corporation and others. + * Copyright (c) 2004, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceType.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceType.java index 50b00db2..b9797247 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceType.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceType.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -32,6 +32,7 @@ import org.eclipse.wst.jsdt.core.Signature; import org.eclipse.wst.jsdt.core.WorkingCopyOwner; import org.eclipse.wst.jsdt.core.compiler.CategorizedProblem; import org.eclipse.wst.jsdt.core.compiler.CharOperation; +import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants; import org.eclipse.wst.jsdt.core.search.SearchEngine; import org.eclipse.wst.jsdt.internal.codeassist.CompletionEngine; import org.eclipse.wst.jsdt.internal.codeassist.ISelectionRequestor; @@ -46,702 +47,872 @@ import org.eclipse.wst.jsdt.internal.core.util.Util; /** * Handle for a source type. Info object is a SourceTypeElementInfo. - * + * * Note: Parent is either an IClassFile, an IJavaScriptUnit or an IType. - * + * * @see IType */ public class SourceType extends NamedMember implements IType { -protected SourceType(JavaElement parent, String name) { - super(parent, name); -} -/** - * @see IType - */ -public void codeComplete(char[] snippet,int insertion,int position,char[][] localVariableTypeNames,char[][] localVariableNames,int[] localVariableModifiers,boolean isStatic,CompletionRequestor requestor) throws JavaScriptModelException { - codeComplete(snippet, insertion, position, localVariableTypeNames, localVariableNames, localVariableModifiers, isStatic, requestor, DefaultWorkingCopyOwner.PRIMARY); -} -/** - * @see IType - */ -public void codeComplete(char[] snippet,int insertion,int position,char[][] localVariableTypeNames,char[][] localVariableNames,int[] localVariableModifiers,boolean isStatic,CompletionRequestor requestor, WorkingCopyOwner owner) throws JavaScriptModelException { - if (requestor == null) { - throw new IllegalArgumentException("Completion requestor cannot be null"); //$NON-NLS-1$ + /** + *

+ * true if this type is anonymous. + *

+ *

+ * NOTE: Even if this is false {@link #isAnonymous()} can still return true + * based don the name of the type. The purpose of this is for when a type should be considered + * anonymous not based on its name. + *

+ */ + private final boolean fIsAnonymous; + + protected SourceType(JavaElement parent, String name) { + super(parent, name); + this.fIsAnonymous = false; } - JavaProject project = (JavaProject) getJavaScriptProject(); - SearchableEnvironment environment = newSearchableNameEnvironment(owner); - CompletionEngine engine = new CompletionEngine(environment, requestor, project.getOptions(true), project); + protected SourceType(JavaElement parent, String name, boolean isAnonymous) { + super(parent, name); + this.fIsAnonymous = isAnonymous; + } + + /** + * @see IType + */ + public void codeComplete(char[] snippet, int insertion, int position, char[][] localVariableTypeNames, + char[][] localVariableNames, int[] localVariableModifiers, boolean isStatic, CompletionRequestor requestor) + throws JavaScriptModelException { + codeComplete(snippet, insertion, position, localVariableTypeNames, localVariableNames, localVariableModifiers, + isStatic, requestor, DefaultWorkingCopyOwner.PRIMARY); + } + + /** + * @see IType + */ + public void codeComplete(char[] snippet, int insertion, int position, char[][] localVariableTypeNames, + char[][] localVariableNames, int[] localVariableModifiers, boolean isStatic, CompletionRequestor requestor, + WorkingCopyOwner owner) throws JavaScriptModelException { + if(requestor == null) { + throw new IllegalArgumentException("Completion requestor cannot be null"); //$NON-NLS-1$ + } - String source = getJavaScriptUnit().getSource(); - if (source != null && insertion > -1 && insertion < source.length()) { + JavaProject project = (JavaProject) getJavaScriptProject(); + SearchableEnvironment environment = newSearchableNameEnvironment(owner); + CompletionEngine engine = new CompletionEngine(environment, requestor, project.getOptions(true), project); - char[] prefix = CharOperation.concat(source.substring(0, insertion).toCharArray(), new char[]{'{'}); - char[] suffix = CharOperation.concat(new char[]{'}'}, source.substring(insertion).toCharArray()); - char[] fakeSource = CharOperation.concat(prefix, snippet, suffix); + String source = getJavaScriptUnit().getSource(); + if(source != null && insertion > -1 && insertion < source.length()) { - BasicCompilationUnit cu = - new BasicCompilationUnit( - fakeSource, - null, - getElementName(), - getParent()); + char[] prefix = CharOperation.concat(source.substring(0, insertion).toCharArray(), new char[] { '{' }); + char[] suffix = CharOperation.concat(new char[] { '}' }, source.substring(insertion).toCharArray()); + char[] fakeSource = CharOperation.concat(prefix, snippet, suffix); - engine.complete(cu, prefix.length + position, prefix.length); - } else { - engine.complete(this, snippet, position, localVariableTypeNames, localVariableNames, localVariableModifiers, isStatic); + BasicCompilationUnit cu = new BasicCompilationUnit(fakeSource, null, getElementName(), getParent()); + + engine.complete(cu, prefix.length + position, prefix.length); + } else { + engine.complete(this, snippet, position, localVariableTypeNames, localVariableNames, + localVariableModifiers, isStatic); + } + if(NameLookup.VERBOSE) { + System.out.println(Thread.currentThread() + + " TIME SPENT in NameLoopkup#seekTypesInSourcePackage: " + environment.nameLookup.timeSpentInSeekTypesInSourcePackage + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ + System.out.println(Thread.currentThread() + + " TIME SPENT in NameLoopkup#seekTypesInBinaryPackage: " + environment.nameLookup.timeSpentInSeekTypesInBinaryPackage + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ + } } - if (NameLookup.VERBOSE) { - System.out.println(Thread.currentThread() + " TIME SPENT in NameLoopkup#seekTypesInSourcePackage: " + environment.nameLookup.timeSpentInSeekTypesInSourcePackage + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ - System.out.println(Thread.currentThread() + " TIME SPENT in NameLoopkup#seekTypesInBinaryPackage: " + environment.nameLookup.timeSpentInSeekTypesInBinaryPackage + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ + + /** + * @see IType + */ + public IField createField(String contents, IJavaScriptElement sibling, boolean force, IProgressMonitor monitor) + throws JavaScriptModelException { + CreateFieldOperation op = new CreateFieldOperation(this, contents, force); + if(sibling != null) { + op.createBefore(sibling); + } + op.runOperation(monitor); + return (IField) op.getResultElements()[0]; } -} -/** - * @see IType - */ -public IField createField(String contents, IJavaScriptElement sibling, boolean force, IProgressMonitor monitor) throws JavaScriptModelException { - CreateFieldOperation op = new CreateFieldOperation(this, contents, force); - if (sibling != null) { - op.createBefore(sibling); + + /** + * @see IType + */ + public IFunction createMethod(String contents, IJavaScriptElement sibling, boolean force, IProgressMonitor monitor) + throws JavaScriptModelException { + CreateMethodOperation op = new CreateMethodOperation(this, contents, force); + if(sibling != null) { + op.createBefore(sibling); + } + op.runOperation(monitor); + return (IFunction) op.getResultElements()[0]; } - op.runOperation(monitor); - return (IField) op.getResultElements()[0]; -} -/** - * @see IType - */ -public IFunction createMethod(String contents, IJavaScriptElement sibling, boolean force, IProgressMonitor monitor) throws JavaScriptModelException { - CreateMethodOperation op = new CreateMethodOperation(this, contents, force); - if (sibling != null) { - op.createBefore(sibling); + /** + * @see IType + */ + public IType createType(String contents, IJavaScriptElement sibling, boolean force, IProgressMonitor monitor) + throws JavaScriptModelException { + CreateTypeOperation op = new CreateTypeOperation(this, contents, force); + if(sibling != null) { + op.createBefore(sibling); + } + op.runOperation(monitor); + return (IType) op.getResultElements()[0]; } - op.runOperation(monitor); - return (IFunction) op.getResultElements()[0]; -} -/** - * @see IType - */ -public IType createType(String contents, IJavaScriptElement sibling, boolean force, IProgressMonitor monitor) throws JavaScriptModelException { - CreateTypeOperation op = new CreateTypeOperation(this, contents, force); - if (sibling != null) { - op.createBefore(sibling); + + public boolean equals(Object o) { + if(!(o instanceof SourceType)) + return false; + return super.equals(o); } - op.runOperation(monitor); - return (IType) op.getResultElements()[0]; -} -public boolean equals(Object o) { - if (!(o instanceof SourceType)) return false; - return super.equals(o); -} -/* - * @see IType - */ -public IFunction[] findMethods(IFunction method) { - try { - return findMethods(method, getFunctions()); - } catch (JavaScriptModelException e) { - // if type doesn't exist, no matching method can exist - return null; + + /* @see IType */ + public IFunction[] findMethods(IFunction method) { + try { + return findMethods(method, getFunctions()); + } catch(JavaScriptModelException e) { + // if type doesn't exist, no matching method can exist + return null; + } } -} -public IJavaScriptElement[] getChildrenForCategory(String category) throws JavaScriptModelException { - IJavaScriptElement[] children = getChildren(); - int length = children.length; - if (length == 0) return NO_ELEMENTS; - SourceTypeElementInfo info = (SourceTypeElementInfo) getElementInfo(); - HashMap categories = info.getCategories(); - if (categories == null) return NO_ELEMENTS; - IJavaScriptElement[] result = new IJavaScriptElement[length]; - int index = 0; - for (int i = 0; i < length; i++) { - IJavaScriptElement child = children[i]; - String[] elementCategories = (String[]) categories.get(child); - if (elementCategories != null) - for (int j = 0, length2 = elementCategories.length; j < length2; j++) { - if (elementCategories[j].equals(category)) - result[index++] = child; - } + + public IJavaScriptElement[] getChildrenForCategory(String category) throws JavaScriptModelException { + IJavaScriptElement[] children = getChildren(); + int length = children.length; + if(length == 0) + return NO_ELEMENTS; + SourceTypeElementInfo info = (SourceTypeElementInfo) getElementInfo(); + HashMap categories = info.getCategories(); + if(categories == null) + return NO_ELEMENTS; + IJavaScriptElement[] result = new IJavaScriptElement[length]; + int index = 0; + for(int i = 0; i < length; i++) { + IJavaScriptElement child = children[i]; + String[] elementCategories = (String[]) categories.get(child); + if(elementCategories != null) + for(int j = 0, length2 = elementCategories.length; j < length2; j++) { + if(elementCategories[j].equals(category)) + result[index++] = child; + } + } + if(index == 0) + return NO_ELEMENTS; + if(index < length) + System.arraycopy(result, 0, result = new IJavaScriptElement[index], 0, index); + return result; } - if (index == 0) return NO_ELEMENTS; - if (index < length) - System.arraycopy(result, 0, result = new IJavaScriptElement[index], 0, index); - return result; -} -/** - * @see IMember - */ -public IType getDeclaringType() { - IJavaScriptElement parentElement = getParent(); - while (parentElement != null) { - if (parentElement.getElementType() == IJavaScriptElement.TYPE) { - return (IType) parentElement; - } else - if (parentElement instanceof IMember) { + + /** + * @see IMember + */ + public IType getDeclaringType() { + IJavaScriptElement parentElement = getParent(); + while(parentElement != null) { + if(parentElement.getElementType() == IJavaScriptElement.TYPE) { + return (IType) parentElement; + } else if(parentElement instanceof IMember) { parentElement = parentElement.getParent(); } else { return null; } - } - return null; -} -/** - * @see IJavaScriptElement - */ -public int getElementType() { - return TYPE; -} -/** - * @see IType#getField - */ -public IField getField(String fieldName) { - return new SourceField(this, fieldName); -} -/** - * @see IType - */ -public IField[] getFields() throws JavaScriptModelException { - ArrayList list = getChildrenOfType(FIELD); - IField[] array= new IField[list.size()]; - list.toArray(array); - return array; -} -/** - * @see IType#getFullyQualifiedName() - */ -public String getFullyQualifiedName() { - return this.getFullyQualifiedName('$'); -} -/** - * @see IType#getFullyQualifiedName(char) - */ -public String getFullyQualifiedName(char enclosingTypeSeparator) { - try { - return getFullyQualifiedName(enclosingTypeSeparator, false/*don't show parameters*/); - } catch (JavaScriptModelException e) { - // exception thrown only when showing parameters + } return null; } -} -/* - * @see IType#getFullyQualifiedParameterizedName() - */ -public String getFullyQualifiedParameterizedName() throws JavaScriptModelException { - return getFullyQualifiedName('.', true/*show parameters*/); -} -/* - * @see JavaElement - */ -public IJavaScriptElement getHandleFromMemento(String token, MementoTokenizer memento, WorkingCopyOwner workingCopyOwner) { - switch (token.charAt(0)) { - case JEM_COUNT: - return getHandleUpdatingCountFromMemento(memento, workingCopyOwner); - case JEM_FIELD: - if (!memento.hasMoreTokens()) return this; - String fieldName = memento.nextToken(); - JavaElement field = (JavaElement)getField(fieldName); - return field.getHandleFromMemento(memento, workingCopyOwner); - case JEM_INITIALIZER: - if (!memento.hasMoreTokens()) return this; - String count = memento.nextToken(); - JavaElement initializer = (JavaElement)getInitializer(Integer.parseInt(count)); - return initializer.getHandleFromMemento(memento, workingCopyOwner); - case JEM_METHOD: - if (!memento.hasMoreTokens()) return this; - String selector = memento.nextToken(); - ArrayList params = new ArrayList(); - nextParam: while (memento.hasMoreTokens()) { - token = memento.nextToken(); - switch (token.charAt(0)) { + + /** + * @see IJavaScriptElement + */ + public int getElementType() { + return TYPE; + } + + /** + * @see IType#getField + */ + public IField getField(String fieldName) { + return new SourceField(this, fieldName); + } + + /** + * @see IType + */ + public IField[] getFields() throws JavaScriptModelException { + ArrayList list = getChildrenOfType(FIELD); + IField[] array = new IField[list.size()]; + list.toArray(array); + return array; + } + + /** + * @see IType#getFullyQualifiedName() + */ + public String getFullyQualifiedName() { + return this.getFullyQualifiedName('$'); + } + + /** + * @see IType#getFullyQualifiedName(char) + */ + public String getFullyQualifiedName(char enclosingTypeSeparator) { + try { + return getFullyQualifiedName(enclosingTypeSeparator, false/* don't show parameters */); + } catch(JavaScriptModelException e) { + // exception thrown only when showing parameters + return null; + } + } + + /* @see IType#getFullyQualifiedParameterizedName() */ + public String getFullyQualifiedParameterizedName() throws JavaScriptModelException { + return getFullyQualifiedName('.', true/* show parameters */); + } + + /* @see JavaElement */ + public IJavaScriptElement getHandleFromMemento(String token, MementoTokenizer memento, + WorkingCopyOwner workingCopyOwner) { + switch(token.charAt(0)) { + case JEM_COUNT: + return getHandleUpdatingCountFromMemento(memento, workingCopyOwner); + case JEM_FIELD: + if(!memento.hasMoreTokens()) + return this; + String fieldName = memento.nextToken(); + JavaElement field = (JavaElement) getField(fieldName); + return field.getHandleFromMemento(memento, workingCopyOwner); + case JEM_INITIALIZER: + if(!memento.hasMoreTokens()) + return this; + String count = memento.nextToken(); + JavaElement initializer = (JavaElement) getInitializer(Integer.parseInt(count)); + return initializer.getHandleFromMemento(memento, workingCopyOwner); + case JEM_METHOD: + if(!memento.hasMoreTokens()) + return this; + String selector = memento.nextToken(); + ArrayList params = new ArrayList(); + nextParam: while(memento.hasMoreTokens()) { + token = memento.nextToken(); + switch(token.charAt(0)) { + case JEM_TYPE: + case JEM_TYPE_PARAMETER: + break nextParam; + case JEM_METHOD: + if(!memento.hasMoreTokens()) + return this; + String param = memento.nextToken(); + StringBuffer buffer = new StringBuffer(); + while(param.length() == 1 && Signature.C_ARRAY == param.charAt(0)) { // backward + // compatible + // with + // 3.0 + // mementos + buffer.append(Signature.C_ARRAY); + if(!memento.hasMoreTokens()) + return this; + param = memento.nextToken(); + } + params.add(buffer.toString() + param); + break; + default: + break nextParam; + } + } + String[] parameters = new String[params.size()]; + params.toArray(parameters); + JavaElement method = (JavaElement) getFunction(selector, parameters); + switch(token.charAt(0)) { case JEM_TYPE: case JEM_TYPE_PARAMETER: - break nextParam; - case JEM_METHOD: - if (!memento.hasMoreTokens()) return this; - String param = memento.nextToken(); - StringBuffer buffer = new StringBuffer(); - while (param.length() == 1 && Signature.C_ARRAY == param.charAt(0)) { // backward compatible with 3.0 mementos - buffer.append(Signature.C_ARRAY); - if (!memento.hasMoreTokens()) return this; - param = memento.nextToken(); - } - params.add(buffer.toString() + param); - break; + case JEM_LOCALVARIABLE: + return method.getHandleFromMemento(token, memento, workingCopyOwner); default: - break nextParam; + return method; } - } - String[] parameters = new String[params.size()]; - params.toArray(parameters); - JavaElement method = (JavaElement)getFunction(selector, parameters); - switch (token.charAt(0)) { - case JEM_TYPE: - case JEM_TYPE_PARAMETER: - case JEM_LOCALVARIABLE: - return method.getHandleFromMemento(token, memento, workingCopyOwner); - default: - return method; - } - case JEM_TYPE: - String typeName; - if (memento.hasMoreTokens()) { - typeName = memento.nextToken(); - char firstChar = typeName.charAt(0); - if (firstChar == JEM_FIELD || firstChar == JEM_INITIALIZER || firstChar == JEM_METHOD || firstChar == JEM_TYPE || firstChar == JEM_COUNT) { - token = typeName; - typeName = ""; //$NON-NLS-1$ + case JEM_TYPE: + String typeName; + if(memento.hasMoreTokens()) { + typeName = memento.nextToken(); + char firstChar = typeName.charAt(0); + if(firstChar == JEM_FIELD || firstChar == JEM_INITIALIZER || firstChar == JEM_METHOD + || firstChar == JEM_TYPE || firstChar == JEM_COUNT) { + token = typeName; + typeName = ""; //$NON-NLS-1$ + } else { + token = null; + } } else { + typeName = ""; //$NON-NLS-1$ token = null; } - } else { - typeName = ""; //$NON-NLS-1$ - token = null; - } - JavaElement type = (JavaElement)getType(typeName); - if (token == null) { - return type.getHandleFromMemento(memento, workingCopyOwner); - } else { - return type.getHandleFromMemento(token, memento, workingCopyOwner); - } + JavaElement type = (JavaElement) getType(typeName); + if(token == null) { + return type.getHandleFromMemento(memento, workingCopyOwner); + } else { + return type.getHandleFromMemento(token, memento, workingCopyOwner); + } - } - return null; -} -/** - * @see IType - */ -public IInitializer getInitializer(int count) { - return new Initializer(this, count); -} -/** - * @see IType - */ -public IInitializer[] getInitializers() throws JavaScriptModelException { - ArrayList list = getChildrenOfType(INITIALIZER); - IInitializer[] array= new IInitializer[list.size()]; - list.toArray(array); - return array; -} -/* (non-Javadoc) - * @see org.eclipse.wst.jsdt.core.IType#getKey() - */ -public String getKey() { - try { - return getKey(this, false/*don't open*/); - } catch (JavaScriptModelException e) { - // happen only if force open is true - return null; - } -} -/** - * @see IType#getMethod - */ -public IFunction getFunction(String selector, String[] parameterTypeSignatures) { - return new SourceMethod(this, selector, parameterTypeSignatures); -} -/** - * @see IType - */ -public IFunction[] getFunctions() throws JavaScriptModelException { - ArrayList list = getChildrenOfType(METHOD); - IFunction[] array= new IFunction[list.size()]; - list.toArray(array); - return array; -} -/** - * @see IType - */ -public IPackageFragment getPackageFragment() { - IJavaScriptElement parentElement = this.parent; - while (parentElement != null) { - if (parentElement.getElementType() == IJavaScriptElement.PACKAGE_FRAGMENT) { - return (IPackageFragment)parentElement; } - else { - parentElement = parentElement.getParent(); - } - } - Assert.isTrue(false); // should not happen - return null; -} -/* - * @see JavaElement#getPrimaryElement(boolean) - */ -public IJavaScriptElement getPrimaryElement(boolean checkOwner) { - if (checkOwner) { - CompilationUnit cu = (CompilationUnit)getAncestor(JAVASCRIPT_UNIT); - if (cu.isPrimary()) return this; - } - IJavaScriptElement primaryParent = this.parent.getPrimaryElement(false); - switch (primaryParent.getElementType()) { - case IJavaScriptElement.JAVASCRIPT_UNIT: - return ((IJavaScriptUnit)primaryParent).getType(this.name); - case IJavaScriptElement.TYPE: - return ((IType)primaryParent).getType(this.name); - case IJavaScriptElement.FIELD: - case IJavaScriptElement.INITIALIZER: - case IJavaScriptElement.METHOD: - return ((IMember)primaryParent).getType(this.name, this.occurrenceCount); - } - return this; -} -/** - * @see IType - */ -public String getSuperclassName() throws JavaScriptModelException { - SourceTypeElementInfo info = (SourceTypeElementInfo) getElementInfo(); - char[] superclassName= info.getSuperclassName(); - if (superclassName == null) { return null; } - return new String(superclassName); -} -/** - * @see IType#getSuperclassTypeSignature() - * @since 3.0 - */ -public String getSuperclassTypeSignature() throws JavaScriptModelException { - SourceTypeElementInfo info = (SourceTypeElementInfo) getElementInfo(); - char[] superclassName= info.getSuperclassName(); - if (superclassName == null) { - return null; + /** + * @see IType + */ + public IInitializer getInitializer(int count) { + return new Initializer(this, count); } - return new String(Signature.createTypeSignature(superclassName, false)); -} - -/** - * @see IType - */ -public IType getType(String typeName) { - return new SourceType(this, typeName); -} -/** - * @see IType#getTypeQualifiedName() - */ -public String getTypeQualifiedName() { - return this.getTypeQualifiedName('$'); -} -/** - * @see IType#getTypeQualifiedName(char) - */ -public String getTypeQualifiedName(char enclosingTypeSeparator) { - try { - return getTypeQualifiedName(enclosingTypeSeparator, false/*don't show parameters*/); - } catch (JavaScriptModelException e) { - // exception thrown only when showing parameters - return null; + /** + * @see IType + */ + public IInitializer[] getInitializers() throws JavaScriptModelException { + ArrayList list = getChildrenOfType(INITIALIZER); + IInitializer[] array = new IInitializer[list.size()]; + list.toArray(array); + return array; } -} -/** - * @see IType - */ -public IType[] getTypes() throws JavaScriptModelException { - ArrayList list= getChildrenOfType(TYPE); - IType[] array= new IType[list.size()]; - list.toArray(array); - return array; -} -/** - * @see IType#isAnonymous() - */ -public boolean isAnonymous() { - return this.name.length() == 0 || this.name.startsWith(Util.ANONYMOUS_MARKER); -} + /* (non-Javadoc) + * + * @see org.eclipse.wst.jsdt.core.IType#getKey() */ + public String getKey() { + try { + return getKey(this, false/* don't open */); + } catch(JavaScriptModelException e) { + // happen only if force open is true + return null; + } + } -/** - * @see IType - */ -public boolean isClass() throws JavaScriptModelException { - SourceTypeElementInfo info = (SourceTypeElementInfo) getElementInfo(); - return TypeDeclaration.kind(info.getModifiers()) == TypeDeclaration.CLASS_DECL; -} + /** + * @see IType#getMethod + */ + public IFunction getFunction(String selector, String[] parameterTypeSignatures) { + return new SourceMethod(this, selector, parameterTypeSignatures); + } -/** - * @see IType#isLocal() - */ -public boolean isLocal() { - switch (this.parent.getElementType()) { - case IJavaScriptElement.METHOD: - case IJavaScriptElement.INITIALIZER: - case IJavaScriptElement.FIELD: - return true; - default: - return false; + /** + * @see IType + */ + public IFunction[] getFunctions() throws JavaScriptModelException { + ArrayList list = getChildrenOfType(METHOD); + IFunction[] array = new IFunction[list.size()]; + list.toArray(array); + return array; } -} -/** - * @see IType#isMember() - */ -public boolean isMember() { - return getDeclaringType() != null; -} -/* (non-Javadoc) - * @see org.eclipse.wst.jsdt.core.IType#isResolved() - */ -public boolean isResolved() { - return false; -} -/** - * @see IType - */ -public ITypeHierarchy loadTypeHierachy(InputStream input, IProgressMonitor monitor) throws JavaScriptModelException { - return loadTypeHierachy(input, DefaultWorkingCopyOwner.PRIMARY, monitor); -} -/** - * NOTE: This method is not part of the API has it is not clear clients would easily use it: they would need to - * first make sure all working copies for the given owner exist before calling it. This is especially har at startup - * time. - * In case clients want this API, here is how it should be specified: - *

- * Loads a previously saved ITypeHierarchy from an input stream. A type hierarchy can - * be stored using ITypeHierachy#store(OutputStream). A compilation unit of a - * loaded type has the given owner if such a working copy exists, otherwise the type's - * compilation unit is a primary compilation unit. - * - * Only hierarchies originally created by the following methods can be loaded: - *

    - *
  • IType#newSupertypeHierarchy(IProgressMonitor)
  • - *
  • IType#newSupertypeHierarchy(WorkingCopyOwner, IProgressMonitor)
  • - *
  • IType#newTypeHierarchy(IJavaScriptProject, IProgressMonitor)
  • - *
  • IType#newTypeHierarchy(IJavaScriptProject, WorkingCopyOwner, IProgressMonitor)
  • - *
  • IType#newTypeHierarchy(IProgressMonitor)
  • - *
  • IType#newTypeHierarchy(WorkingCopyOwner, IProgressMonitor)
  • - * - * - * @param input stream where hierarchy will be read - * @param monitor the given progress monitor - * @return the stored hierarchy - * @exception JavaScriptModelException if the hierarchy could not be restored, reasons include: - * - type is not the focus of the hierarchy or - * - unable to read the input stream (wrong format, IOException during reading, ...) - * @see ITypeHierarchy#store(java.io.OutputStream, IProgressMonitor) - * @since 3.0 - */ -public ITypeHierarchy loadTypeHierachy(InputStream input, WorkingCopyOwner owner, IProgressMonitor monitor) throws JavaScriptModelException { - // TODO monitor should be passed to TypeHierarchy.load(...) - return TypeHierarchy.load(this, input, owner); -} -/** - * @see IType - */ -public ITypeHierarchy newSupertypeHierarchy(IProgressMonitor monitor) throws JavaScriptModelException { - return this.newSupertypeHierarchy(DefaultWorkingCopyOwner.PRIMARY, monitor); -} -/* - * @see IType#newSupertypeHierarchy(IJavaScriptUnit[], IProgressMonitor) - */ -public ITypeHierarchy newSupertypeHierarchy( - IJavaScriptUnit[] workingCopies, - IProgressMonitor monitor) - throws JavaScriptModelException { - - CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation(this, workingCopies, SearchEngine.createWorkspaceScope(), false); - op.runOperation(monitor); - return op.getResult(); -} -/** - * @see IType#newSupertypeHierarchy(WorkingCopyOwner, IProgressMonitor) - */ -public ITypeHierarchy newSupertypeHierarchy( - WorkingCopyOwner owner, - IProgressMonitor monitor) - throws JavaScriptModelException { - - IJavaScriptUnit[] workingCopies = JavaModelManager.getJavaModelManager().getWorkingCopies(owner, true/*add primary working copies*/); - CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation(this, workingCopies, SearchEngine.createWorkspaceScope(), false); - op.runOperation(monitor); - return op.getResult(); -} -/** - * @see IType - */ -public ITypeHierarchy newTypeHierarchy(IJavaScriptProject project, IProgressMonitor monitor) throws JavaScriptModelException { - return newTypeHierarchy(project, DefaultWorkingCopyOwner.PRIMARY, monitor); -} -/** - * @see IType#newTypeHierarchy(IJavaScriptProject, WorkingCopyOwner, IProgressMonitor) - */ -public ITypeHierarchy newTypeHierarchy(IJavaScriptProject project, WorkingCopyOwner owner, IProgressMonitor monitor) throws JavaScriptModelException { - if (project == null) { - throw new IllegalArgumentException(Messages.hierarchy_nullProject); - } - IJavaScriptUnit[] workingCopies = JavaModelManager.getJavaModelManager().getWorkingCopies(owner, true/*add primary working copies*/); - IJavaScriptUnit[] projectWCs = null; - if (workingCopies != null) { - int length = workingCopies.length; - projectWCs = new IJavaScriptUnit[length]; - int index = 0; - for (int i = 0; i < length; i++) { - IJavaScriptUnit wc = workingCopies[i]; - if (project.equals(wc.getJavaScriptProject())) { - projectWCs[index++] = wc; + + /** + * @see IType + */ + public IPackageFragment getPackageFragment() { + IJavaScriptElement parentElement = this.parent; + while(parentElement != null) { + if(parentElement.getElementType() == IJavaScriptElement.PACKAGE_FRAGMENT) { + return (IPackageFragment) parentElement; + } else { + parentElement = parentElement.getParent(); } } - if (index != length) { - System.arraycopy(projectWCs, 0, projectWCs = new IJavaScriptUnit[index], 0, index); - } + Assert.isTrue(false); // should not happen + return null; } - CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation( - this, - projectWCs, - project, - true); - op.runOperation(monitor); - return op.getResult(); -} -/** - * @see IType - */ -public ITypeHierarchy newTypeHierarchy(IProgressMonitor monitor) throws JavaScriptModelException { - CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation(this, null, SearchEngine.createWorkspaceScope(), true); - op.runOperation(monitor); - return op.getResult(); -} -/* - * @see IType#newTypeHierarchy(IJavaScriptUnit[], IProgressMonitor) - */ -public ITypeHierarchy newTypeHierarchy( - IJavaScriptUnit[] workingCopies, - IProgressMonitor monitor) - throws JavaScriptModelException { - - CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation(this, workingCopies, SearchEngine.createWorkspaceScope(), true); - op.runOperation(monitor); - return op.getResult(); -} -/** - * @see IType#newTypeHierarchy(WorkingCopyOwner, IProgressMonitor) - */ -public ITypeHierarchy newTypeHierarchy( - WorkingCopyOwner owner, - IProgressMonitor monitor) - throws JavaScriptModelException { - - IJavaScriptUnit[] workingCopies = JavaModelManager.getJavaModelManager().getWorkingCopies(owner, true/*add primary working copies*/); - CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation(this, workingCopies, SearchEngine.createWorkspaceScope(), true); - op.runOperation(monitor); - return op.getResult(); -} -public JavaElement resolved(Binding binding) { - SourceRefElement resolvedHandle = new ResolvedSourceType(this.parent, this.name, new String(binding.computeUniqueKey())); - resolvedHandle.occurrenceCount = this.occurrenceCount; - return resolvedHandle; -} -/** - * @see IType#resolveType(String) - */ -public String[][] resolveType(String typeName) throws JavaScriptModelException { - return resolveType(typeName, DefaultWorkingCopyOwner.PRIMARY); -} -/** - * @see IType#resolveType(String, WorkingCopyOwner) - */ -public String[][] resolveType(String typeName, WorkingCopyOwner owner) throws JavaScriptModelException { - ISourceType info = (ISourceType) getElementInfo(); - JavaProject project = (JavaProject) getJavaScriptProject(); - SearchableEnvironment environment = newSearchableNameEnvironment(owner); - - class TypeResolveRequestor implements ISelectionRequestor { - String[][] answers = null; - public void acceptType(char[] packageName, char[] fileName, char[] tName, int modifiers, boolean isDeclaration, char[] uniqueKey, int start, int end) { - String[] answer = new String[] {new String(packageName), new String(tName) }; - if (this.answers == null) { - this.answers = new String[][]{ answer }; - } else { - // grow - int length = this.answers.length; - System.arraycopy(this.answers, 0, this.answers = new String[length+1][], 0, length); - this.answers[length] = answer; - } + + /* @see JavaElement#getPrimaryElement(boolean) */ + public IJavaScriptElement getPrimaryElement(boolean checkOwner) { + if(checkOwner) { + CompilationUnit cu = (CompilationUnit) getAncestor(JAVASCRIPT_UNIT); + if(cu.isPrimary()) + return this; } - public void acceptError(CategorizedProblem error) { - // ignore + IJavaScriptElement primaryParent = this.parent.getPrimaryElement(false); + switch(primaryParent.getElementType()) { + case IJavaScriptElement.JAVASCRIPT_UNIT: + return ((IJavaScriptUnit) primaryParent).getType(this.name); + case IJavaScriptElement.TYPE: + return ((IType) primaryParent).getType(this.name); + case IJavaScriptElement.FIELD: + case IJavaScriptElement.INITIALIZER: + case IJavaScriptElement.METHOD: + return ((IMember) primaryParent).getType(this.name, this.occurrenceCount); } - public void acceptField(char[] declaringTypePackageName, char[] fileName, char[] declaringTypeName, char[] fieldName, boolean isDeclaration, char[] uniqueKey, int start, int end) { - // ignore + return this; + } + + /** + * @see IType + */ + public String getSuperclassName() throws JavaScriptModelException { + SourceTypeElementInfo info = (SourceTypeElementInfo) getElementInfo(); + char[] superclassName = info.getSuperclassName(); + if(superclassName == null) { + return null; + } + return new String(superclassName); + } + + /** + * @see IType#getSuperclassTypeSignature() + * @since 3.0 + */ + public String getSuperclassTypeSignature() throws JavaScriptModelException { + SourceTypeElementInfo info = (SourceTypeElementInfo) getElementInfo(); + char[] superclassName = info.getSuperclassName(); + if(superclassName == null) { + return null; } - public void acceptMethod(char[] declaringTypePackageName, char[] fileName, char[] declaringTypeName, String enclosingDeclaringTypeSignature, char[] selector, char[][] parameterPackageNames, char[][] parameterTypeNames, String[] parameterSignatures, char[][] typeParameterNames, char[][][] typeParameterBoundNames, boolean isConstructor, boolean isDeclaration, char[] uniqueKey, int start, int end) { - // ignore + return new String(Signature.createTypeSignature(superclassName, false)); + } + + /** + * @see IType + */ + public IType getType(String typeName) { + return new SourceType(this, typeName); + } + + /** + * @see IType#getTypeQualifiedName() + */ + public String getTypeQualifiedName() { + return this.getTypeQualifiedName('$'); + } + + /** + * @see IType#getTypeQualifiedName(char) + */ + public String getTypeQualifiedName(char enclosingTypeSeparator) { + try { + return getTypeQualifiedName(enclosingTypeSeparator, false/* don't show parameters */); + } catch(JavaScriptModelException e) { + // exception thrown only when showing parameters + return null; } - public void acceptPackage(char[] packageName){ - // ignore + } + + /** + * @see IType + */ + public IType[] getTypes() throws JavaScriptModelException { + ArrayList list = getChildrenOfType(TYPE); + IType[] array = new IType[list.size()]; + list.toArray(array); + return array; + } + + /** + * @see IType#isAnonymous() + */ + public boolean isAnonymous() { + return this.fIsAnonymous || this.name.length() == 0 || this.name.startsWith(Util.ANONYMOUS_MARKER); + } + + /** + * @see IType + */ + public boolean isClass() throws JavaScriptModelException { + SourceTypeElementInfo info = (SourceTypeElementInfo) getElementInfo(); + return TypeDeclaration.kind(info.getModifiers()) == TypeDeclaration.CLASS_DECL; + } + + /** + * @see IType#isLocal() + */ + public boolean isLocal() { + switch(this.parent.getElementType()) { + case IJavaScriptElement.METHOD: + case IJavaScriptElement.INITIALIZER: + case IJavaScriptElement.FIELD: + return true; + default: + return false; } - public void acceptTypeParameter(char[] declaringTypePackageName, char[] fileName, char[] declaringTypeName, char[] typeParameterName, boolean isDeclaration, int start, int end) { - // ignore + } + + /** + * @see IType#isMember() + */ + public boolean isMember() { + return getDeclaringType() != null; + } + + /* (non-Javadoc) + * + * @see org.eclipse.wst.jsdt.core.IType#isResolved() */ + public boolean isResolved() { + return false; + } + + /** + * @see IType + */ + public ITypeHierarchy loadTypeHierachy(InputStream input, IProgressMonitor monitor) throws JavaScriptModelException { + return loadTypeHierachy(input, DefaultWorkingCopyOwner.PRIMARY, monitor); + } + + /** + * NOTE: This method is not part of the API has it is not clear clients would easily use it: + * they would need to + * first make sure all working copies for the given owner exist before calling it. This is + * especially har at startup + * time. + * In case clients want this API, here is how it should be specified: + *

    + * Loads a previously saved ITypeHierarchy from an input stream. A type hierarchy can be stored + * using ITypeHierachy#store(OutputStream). A compilation unit of a loaded type has the given + * owner if such a working copy exists, otherwise the type's compilation unit is a primary + * compilation unit. + * + * Only hierarchies originally created by the following methods can be loaded: + *

      + *
    • IType#newSupertypeHierarchy(IProgressMonitor)
    • + *
    • IType#newSupertypeHierarchy(WorkingCopyOwner, IProgressMonitor)
    • + *
    • IType#newTypeHierarchy(IJavaScriptProject, IProgressMonitor)
    • + *
    • IType#newTypeHierarchy(IJavaScriptProject, WorkingCopyOwner, IProgressMonitor)
    • + *
    • IType#newTypeHierarchy(IProgressMonitor)
    • + *
    • IType#newTypeHierarchy(WorkingCopyOwner, IProgressMonitor)
    • + * + * @param input + * stream where hierarchy will be read + * @param monitor + * the given progress monitor + * @return the stored hierarchy + * @exception JavaScriptModelException + * if the hierarchy could not be restored, reasons include: - type is not the + * focus of the hierarchy or - unable to read the input stream (wrong format, + * IOException during reading, ...) + * @see ITypeHierarchy#store(java.io.OutputStream, IProgressMonitor) + * @since 3.0 + */ + public ITypeHierarchy loadTypeHierachy(InputStream input, WorkingCopyOwner owner, IProgressMonitor monitor) + throws JavaScriptModelException { + // TODO monitor should be passed to TypeHierarchy.load(...) + return TypeHierarchy.load(this, input, owner); + } + + /** + * @see IType + */ + public ITypeHierarchy newSupertypeHierarchy(IProgressMonitor monitor) throws JavaScriptModelException { + return this.newSupertypeHierarchy(DefaultWorkingCopyOwner.PRIMARY, monitor); + } + + /* @see IType#newSupertypeHierarchy(IJavaScriptUnit[], IProgressMonitor) */ + public ITypeHierarchy newSupertypeHierarchy(IJavaScriptUnit[] workingCopies, IProgressMonitor monitor) + throws JavaScriptModelException { + + CreateTypeHierarchyOperation op = + new CreateTypeHierarchyOperation(this, workingCopies, SearchEngine.createWorkspaceScope(), false); + op.runOperation(monitor); + return op.getResult(); + } + + /** + * @see IType#newSupertypeHierarchy(WorkingCopyOwner, IProgressMonitor) + */ + public ITypeHierarchy newSupertypeHierarchy(WorkingCopyOwner owner, IProgressMonitor monitor) + throws JavaScriptModelException { + + IJavaScriptUnit[] workingCopies = + JavaModelManager.getJavaModelManager().getWorkingCopies(owner, true/* add primary + * working + * copies */); + CreateTypeHierarchyOperation op = + new CreateTypeHierarchyOperation(this, workingCopies, SearchEngine.createWorkspaceScope(), false); + op.runOperation(monitor); + return op.getResult(); + } + + /** + * @see IType + */ + public ITypeHierarchy newTypeHierarchy(IJavaScriptProject project, IProgressMonitor monitor) + throws JavaScriptModelException { + return newTypeHierarchy(project, DefaultWorkingCopyOwner.PRIMARY, monitor); + } + + /** + * @see IType#newTypeHierarchy(IJavaScriptProject, WorkingCopyOwner, IProgressMonitor) + */ + public ITypeHierarchy newTypeHierarchy(IJavaScriptProject project, WorkingCopyOwner owner, IProgressMonitor monitor) + throws JavaScriptModelException { + if(project == null) { + throw new IllegalArgumentException(Messages.hierarchy_nullProject); } - public void acceptMethodTypeParameter(char[] declaringTypePackageName, char[] fileName, char[] declaringTypeName, char[] selector, int selectorStart, int selcetorEnd, char[] typeParameterName, boolean isDeclaration, int start, int end) { - // ignore + IJavaScriptUnit[] workingCopies = + JavaModelManager.getJavaModelManager().getWorkingCopies(owner, true/* add primary + * working + * copies */); + IJavaScriptUnit[] projectWCs = null; + if(workingCopies != null) { + int length = workingCopies.length; + projectWCs = new IJavaScriptUnit[length]; + int index = 0; + for(int i = 0; i < length; i++) { + IJavaScriptUnit wc = workingCopies[i]; + if(project.equals(wc.getJavaScriptProject())) { + projectWCs[index++] = wc; + } + } + if(index != length) { + System.arraycopy(projectWCs, 0, projectWCs = new IJavaScriptUnit[index], 0, index); + } } + CreateTypeHierarchyOperation op = new CreateTypeHierarchyOperation(this, projectWCs, project, true); + op.runOperation(monitor); + return op.getResult(); + } + /** + * @see IType + */ + public ITypeHierarchy newTypeHierarchy(IProgressMonitor monitor) throws JavaScriptModelException { + CreateTypeHierarchyOperation op = + new CreateTypeHierarchyOperation(this, null, SearchEngine.createWorkspaceScope(), true); + op.runOperation(monitor); + return op.getResult(); } - TypeResolveRequestor requestor = new TypeResolveRequestor(); - SelectionEngine engine = - new SelectionEngine(environment, requestor, project.getOptions(true)); - IType[] topLevelTypes = getJavaScriptUnit().getTypes(); - int length = topLevelTypes.length; - SourceTypeElementInfo[] topLevelInfos = new SourceTypeElementInfo[length]; - for (int i = 0; i < length; i++) { - topLevelInfos[i] = (SourceTypeElementInfo) ((SourceType)topLevelTypes[i]).getElementInfo(); + /* @see IType#newTypeHierarchy(IJavaScriptUnit[], IProgressMonitor) */ + public ITypeHierarchy newTypeHierarchy(IJavaScriptUnit[] workingCopies, IProgressMonitor monitor) + throws JavaScriptModelException { + + CreateTypeHierarchyOperation op = + new CreateTypeHierarchyOperation(this, workingCopies, SearchEngine.createWorkspaceScope(), true); + op.runOperation(monitor); + return op.getResult(); } - engine.selectType(info, typeName.toCharArray(), topLevelInfos, false); - if (NameLookup.VERBOSE) { - System.out.println(Thread.currentThread() + " TIME SPENT in NameLoopkup#seekTypesInSourcePackage: " + environment.nameLookup.timeSpentInSeekTypesInSourcePackage + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ - System.out.println(Thread.currentThread() + " TIME SPENT in NameLoopkup#seekTypesInBinaryPackage: " + environment.nameLookup.timeSpentInSeekTypesInBinaryPackage + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ + /** + * @see IType#newTypeHierarchy(WorkingCopyOwner, IProgressMonitor) + */ + public ITypeHierarchy newTypeHierarchy(WorkingCopyOwner owner, IProgressMonitor monitor) + throws JavaScriptModelException { + + IJavaScriptUnit[] workingCopies = + JavaModelManager.getJavaModelManager().getWorkingCopies(owner, true/* add primary + * working + * copies */); + CreateTypeHierarchyOperation op = + new CreateTypeHierarchyOperation(this, workingCopies, SearchEngine.createWorkspaceScope(), true); + op.runOperation(monitor); + return op.getResult(); } - return requestor.answers; -} -/* - * @GINO: Anonymous ??? maybe don't need - */ -public String getDisplayName() { - if( isAnonymous() ) - return ""; //$NON-NLS-1$ - else - return super.getDisplayName(); -} -/** - * @private Debugging purposes - */ -protected void toStringInfo(int tab, StringBuffer buffer, Object info, boolean showResolvedInfo) { - buffer.append(tabString(tab)); - if (info == null) { - String elementName = getElementName(); - if (elementName.length() == 0) { - buffer.append(""); //$NON-NLS-1$ + public JavaElement resolved(Binding binding) { + String name = null; + char[] readableName = binding.readableName(); + if(readableName != null) { + name = new String(readableName); } else { - toStringName(buffer); + name = this.name; } - buffer.append(" (not open)"); //$NON-NLS-1$ - } else if (info == NO_INFO) { - String elementName = getElementName(); - if (elementName.length() == 0) { - buffer.append(""); //$NON-NLS-1$ - } else { - toStringName(buffer); + + SourceRefElement resolvedHandle = + new ResolvedSourceType(this.parent, name, new String(binding.computeUniqueKey())); + resolvedHandle.occurrenceCount = this.occurrenceCount; + return resolvedHandle; + } + + /** + * @see IType#resolveType(String) + */ + public String[][] resolveType(String typeName) throws JavaScriptModelException { + return resolveType(typeName, DefaultWorkingCopyOwner.PRIMARY); + } + + /** + * @see IType#resolveType(String, WorkingCopyOwner) + */ + public String[][] resolveType(String typeName, WorkingCopyOwner owner) throws JavaScriptModelException { + ISourceType info = (ISourceType) getElementInfo(); + JavaProject project = (JavaProject) getJavaScriptProject(); + SearchableEnvironment environment = newSearchableNameEnvironment(owner); + + class TypeResolveRequestor implements ISelectionRequestor { + String[][] answers = null; + + public void acceptType(char[] packageName, char[] fileName, char[] tName, int modifiers, + boolean isDeclaration, char[] uniqueKey, int start, int end) { + String[] answer = new String[] { new String(packageName), new String(tName) }; + if(this.answers == null) { + this.answers = new String[][] { answer }; + } else { + // grow + int length = this.answers.length; + System.arraycopy(this.answers, 0, this.answers = new String[length + 1][], 0, length); + this.answers[length] = answer; + } + } + + public void acceptError(CategorizedProblem error) { + // ignore + } + + public void acceptField(char[] declaringTypePackageName, char[] fileName, char[] declaringTypeName, + char[] fieldName, boolean isDeclaration, char[] uniqueKey, int start, int end) { + // ignore + } + + public void acceptMethod(char[] declaringTypePackageName, char[] fileName, char[] declaringTypeName, + String enclosingDeclaringTypeSignature, char[] selector, char[][] parameterPackageNames, + char[][] parameterTypeNames, String[] parameterSignatures, char[][] typeParameterNames, + char[][][] typeParameterBoundNames, boolean isConstructor, boolean isDeclaration, char[] uniqueKey, + int start, int end) { + // ignore + } + + public void acceptPackage(char[] packageName) { + // ignore + } + + public void acceptTypeParameter(char[] declaringTypePackageName, char[] fileName, char[] declaringTypeName, + char[] typeParameterName, boolean isDeclaration, int start, int end) { + // ignore + } + + public void acceptMethodTypeParameter(char[] declaringTypePackageName, char[] fileName, + char[] declaringTypeName, char[] selector, int selectorStart, int selcetorEnd, + char[] typeParameterName, boolean isDeclaration, int start, int end) { + // ignore + } + + } + TypeResolveRequestor requestor = new TypeResolveRequestor(); + SelectionEngine engine = new SelectionEngine(environment, requestor, project.getOptions(true)); + + IType[] topLevelTypes = getJavaScriptUnit().getTypes(); + int length = topLevelTypes.length; + SourceTypeElementInfo[] topLevelInfos = new SourceTypeElementInfo[length]; + for(int i = 0; i < length; i++) { + topLevelInfos[i] = (SourceTypeElementInfo) ((SourceType) topLevelTypes[i]).getElementInfo(); + } + + engine.selectType(info, typeName.toCharArray(), topLevelInfos, false); + if(NameLookup.VERBOSE) { + System.out.println(Thread.currentThread() + + " TIME SPENT in NameLoopkup#seekTypesInSourcePackage: " + environment.nameLookup.timeSpentInSeekTypesInSourcePackage + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ + System.out.println(Thread.currentThread() + + " TIME SPENT in NameLoopkup#seekTypesInBinaryPackage: " + environment.nameLookup.timeSpentInSeekTypesInBinaryPackage + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ + } + return requestor.answers; + } + + /* @GINO: Anonymous ??? maybe don't need */ + public String getDisplayName() { + if(isAnonymous()) + return ""; //$NON-NLS-1$ + else + return super.getDisplayName(); + } + + /** + *

      + * This implementation will search for info for this types synonyms if + * info for this type can not be found. + *

      + * + * @see org.eclipse.wst.jsdt.internal.core.JavaElement#getElementInfo(org.eclipse.core.runtime.IProgressMonitor) + */ + public Object getElementInfo(IProgressMonitor monitor) throws JavaScriptModelException { + Object info = null; + + //try to find the element info using this types name + try { + info = super.getElementInfo(monitor); + } catch(JavaScriptModelException e) { + //ignore, means it could not be found + } + + // if could not find info using this type name try using synonym names + if(info == null) { + char[][] synonyms = SearchEngine.getAllSynonyms(this.name.toCharArray(), + SearchEngine.createJavaSearchScope(new IJavaScriptElement[] { this.getJavaScriptProject() }), + IJavaScriptSearchConstants.FORCE_IMMEDIATE_SEARCH, monitor); + + /* for each synonym see if its info can be found, return the first one that can be found + * skip the first one because the first one is the original name */ + for(int i = 1; i < synonyms.length && info == null; ++i) { + try { + SourceType synonymType = new SourceType(this.parent, new String(synonyms[i])); + info = synonymType.getElementInfo(monitor, false); + } catch(JavaScriptModelException e) { + //ignore, means it could not be found + } + } } - } else { - buffer.append("class "); //$NON-NLS-1$ - String elementName = getElementName(); - if (elementName.length() == 0) { - buffer.append(""); //$NON-NLS-1$ + //really could not find it, expected thing to do in that case is throw an exception + if(info == null) { + throw newNotPresentException(); + } + + return info; + } + + /** + *

      + * Gets the element info for this type with the option to use the types + * synonyms or not. + *

      + * + * @param monitor + * {@link IProgressMonitor} to track the progress of getting + * the element info + * @param searchSynonyms + * true to use the types synonyms if info can not + * be found for this type false otherwise + * + * @return element info for this type, or possibly one of its synonyms if + * info for this type can not be found and + * searchSynonyms is true + * + * @throws JavaScriptModelException + * if element info can not be found + * + * @see #getElementInfo(IProgressMonitor) + */ + private Object getElementInfo(IProgressMonitor monitor, boolean searchSynonyms) throws JavaScriptModelException { + return searchSynonyms ? this.getElementInfo(monitor) : super.getElementInfo(monitor); + } + + /** + * @private Debugging purposes + */ + protected void toStringInfo(int tab, StringBuffer buffer, Object info, boolean showResolvedInfo) { + buffer.append(tabString(tab)); + if(info == null) { + String elementName = getElementName(); + if(elementName.length() == 0) { + buffer.append(""); //$NON-NLS-1$ + } else { + toStringName(buffer); + } + buffer.append(" (not open)"); //$NON-NLS-1$ + } else if(info == NO_INFO) { + String elementName = getElementName(); + if(elementName.length() == 0) { + buffer.append(""); //$NON-NLS-1$ + } else { + toStringName(buffer); + } } else { - toStringName(buffer); + buffer.append("class "); //$NON-NLS-1$ + + String elementName = getElementName(); + if(elementName.length() == 0) { + buffer.append(""); //$NON-NLS-1$ + } else { + toStringName(buffer); + } } } } -} diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceTypeElementInfo.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceTypeElementInfo.java index ee700f9a..1f9c06be 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceTypeElementInfo.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/SourceTypeElementInfo.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -300,6 +300,6 @@ public char[][] getPackageName() { ISourceType enclosingType = getEnclosingType(); if (enclosingType!=null) return enclosingType.getPackageName(); - return new char[0][]; + return CharOperation.NO_CHAR_CHAR; } } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/AbstractImageBuilder.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/AbstractImageBuilder.java index ac003d36..71b8713b 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/AbstractImageBuilder.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/AbstractImageBuilder.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/BatchImageBuilder.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/BatchImageBuilder.java index f99af0c4..73726076 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/BatchImageBuilder.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/BatchImageBuilder.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ICompilationUnitLocator.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ICompilationUnitLocator.java index 687ed952..bc45ca4e 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ICompilationUnitLocator.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ICompilationUnitLocator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007 BEA Systems, Inc. + * Copyright (c) 2007, 2008 BEA Systems, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/IncrementalImageBuilder.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/IncrementalImageBuilder.java index 03234b17..eddbd082 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/IncrementalImageBuilder.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/IncrementalImageBuilder.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -229,9 +229,6 @@ protected void addDependentsOf(IPath path, boolean isStructuralChange) { String packageName = path.removeLastSegments(1).toString(); qualifiedStrings.add(packageName); String typeName = path.lastSegment(); - int memberIndex = typeName.indexOf('$'); - if (memberIndex > 0) - typeName = typeName.substring(0, memberIndex); if (simpleStrings.add(typeName) && JavaBuilder.DEBUG) System.out.println(" will look for dependents of " //$NON-NLS-1$ + typeName + " in " + packageName); //$NON-NLS-1$ diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ValidationParticipantResult.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ValidationParticipantResult.java index 15178bb3..b2f9f4d9 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ValidationParticipantResult.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/builder/ValidationParticipantResult.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2008 IBM Corporation and others. + * Copyright (c) 2005, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java index 950f0df8..122e18a4 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/ASTRewriteAnalyzer.java @@ -1101,6 +1101,21 @@ public final class ASTRewriteAnalyzer extends ASTVisitor { } return pos; } + + /* + * Next token is a left bracket '['. Returns the offset after the bracket. For incomplete code, return the start offset. + */ + private int getPosAfterLeftBracket(int pos) { + try { + int nextToken= getScanner().readNext(pos, true); + if (nextToken == ITerminalSymbols.TokenNameLBRACKET) { + return getScanner().getCurrentEndOffset(); + } + } catch (CoreException e) { + handleException(e); + } + return pos; + } final int getIndent(int offset) { return this.formatter.computeIndentUnits(getIndentOfLine(offset)); @@ -1802,7 +1817,7 @@ public final class ASTRewriteAnalyzer extends ASTVisitor { return doVisitUnchangedChildren(node); } - int startPos= getPosAfterLeftBrace(node.getStartPosition()); + int startPos= getPosAfterLeftBracket(node.getStartPosition()); rewriteNodeList(node, ArrayInitializer.EXPRESSIONS_PROPERTY, startPos, "", ", "); //$NON-NLS-1$ //$NON-NLS-2$ return false; } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/ASTRewriteFlattener.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/ASTRewriteFlattener.java index 81caabc2..0210356e 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/ASTRewriteFlattener.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/dom/rewrite/ASTRewriteFlattener.java @@ -499,7 +499,7 @@ public class ASTRewriteFlattener extends ASTVisitor { */ public boolean visit(ExpressionStatement node) { getChildNode(node, ExpressionStatement.EXPRESSION_PROPERTY).accept(this); - if (node.getParent().getNodeType()!=ASTNode.FOR_IN_STATEMENT) + if (node.getParent() == null || node.getParent().getNodeType()!=ASTNode.FOR_IN_STATEMENT) this.result.append(';'); return false; } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/HierarchyBinaryType.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/HierarchyBinaryType.java index abc8c2b7..263fa6ed 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/HierarchyBinaryType.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/HierarchyBinaryType.java @@ -131,7 +131,7 @@ public boolean isMember() { public void recordSuperType(char[] superTypeName, char[] superQualification){ // index encoding of p.A$B was B/p.A$, rebuild the proper name - if (superQualification != null){ + if (superQualification != null && superQualification.length > 0){ int length = superQualification.length; if (superQualification[length-1] == '$'){ char[] enclosingSuperName = CharOperation.lastSegment(superQualification, '.'); diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/HierarchyBuilder.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/HierarchyBuilder.java index b0b517da..f22aee5a 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/HierarchyBuilder.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/HierarchyBuilder.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -99,7 +99,7 @@ public abstract class HierarchyBuilder { new DefaultProblemFactory()); } this.infoToHandle = new HashMap(5); - this.focusQualifiedName = focusType == null ? null : focusType.getFullyQualifiedName(); + this.focusQualifiedName = focusType == null ? null : focusType.getTypeQualifiedName(); } public abstract void build(boolean computeSubtypes) @@ -182,6 +182,9 @@ public abstract class HierarchyBuilder { this.infoToHandle.put(genericType, handle); } return handle; + } else if (genericType instanceof SourceTypeElementInfo) { + IType handle = ((SourceTypeElementInfo) genericType).getHandle(); + return (IType) ((JavaElement) handle).resolved(binding); } else if (genericType.isBinaryType()) { ClassFile classFile = (ClassFile) this.infoToHandle.get(genericType); // if it's null, it's from outside the region, so do lookup @@ -194,12 +197,10 @@ public abstract class HierarchyBuilder { classFile = (ClassFile) handle.getParent(); this.infoToHandle.put(genericType, classFile); } - return new ResolvedBinaryType(classFile, classFile.getTypeName(), new String(binding.computeUniqueKey())); - } else if (genericType instanceof SourceTypeElementInfo) { - IType handle = ((SourceTypeElementInfo) genericType).getHandle(); - return (IType) ((JavaElement) handle).resolved(binding); - } else + return new ResolvedBinaryType(classFile, new String(binding.readableName()), new String(binding.computeUniqueKey())); + } else { return null; + } } protected IType getType() { return this.hierarchy.getType(); diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/HierarchyResolver.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/HierarchyResolver.java index bec60ac9..1af1b929 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/HierarchyResolver.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/HierarchyResolver.java @@ -1,851 +1,897 @@ -/******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.jsdt.internal.core.hierarchy; - -/** - * This is the public entry point to resolve type hierarchies. - * - * When requesting additional types from the name environment, the resolver - * accepts all forms (binary, source & compilation unit) for additional types. - * - * Side notes: Binary types already know their resolved supertypes so this - * only makes sense for source types. Even though the compiler finds all binary - * types to complete the hierarchy of a given source type, is there any reason - * why the requestor should be informed that binary type X subclasses Y & - * implements I & J? - */ - -import java.util.HashSet; -import java.util.Map; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.OperationCanceledException; -import org.eclipse.wst.jsdt.core.IType; -import org.eclipse.wst.jsdt.core.JavaScriptModelException; -import org.eclipse.wst.jsdt.core.compiler.CharOperation; -import org.eclipse.wst.jsdt.core.infer.InferredType; -import org.eclipse.wst.jsdt.internal.compiler.CompilationResult; -import org.eclipse.wst.jsdt.internal.compiler.DefaultErrorHandlingPolicies; -import org.eclipse.wst.jsdt.internal.compiler.IErrorHandlingPolicy; -import org.eclipse.wst.jsdt.internal.compiler.IProblemFactory; -import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode; -import org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration; -import org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration; -import org.eclipse.wst.jsdt.internal.compiler.ast.TypeReference; -import org.eclipse.wst.jsdt.internal.compiler.env.AccessRestriction; -import org.eclipse.wst.jsdt.internal.compiler.env.IBinaryType; -import org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit; -import org.eclipse.wst.jsdt.internal.compiler.env.IGenericType; -import org.eclipse.wst.jsdt.internal.compiler.env.INameEnvironment; -import org.eclipse.wst.jsdt.internal.compiler.env.ISourceType; -import org.eclipse.wst.jsdt.internal.compiler.impl.CompilerOptions; -import org.eclipse.wst.jsdt.internal.compiler.impl.ITypeRequestor; -import org.eclipse.wst.jsdt.internal.compiler.impl.ITypeRequestor2; -import org.eclipse.wst.jsdt.internal.compiler.lookup.BinaryTypeBinding; -import org.eclipse.wst.jsdt.internal.compiler.lookup.ClassScope; -import org.eclipse.wst.jsdt.internal.compiler.lookup.LookupEnvironment; -import org.eclipse.wst.jsdt.internal.compiler.lookup.PackageBinding; -import org.eclipse.wst.jsdt.internal.compiler.lookup.ProblemReasons; -import org.eclipse.wst.jsdt.internal.compiler.lookup.ProblemReferenceBinding; -import org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding; -import org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding; -import org.eclipse.wst.jsdt.internal.compiler.lookup.TagBits; -import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding; -import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeConstants; -import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeIds; -import org.eclipse.wst.jsdt.internal.compiler.parser.Parser; -import org.eclipse.wst.jsdt.internal.compiler.parser.SourceTypeConverter; -import org.eclipse.wst.jsdt.internal.compiler.problem.AbortCompilation; -import org.eclipse.wst.jsdt.internal.compiler.problem.ProblemReporter; -import org.eclipse.wst.jsdt.internal.compiler.util.HashtableOfObject; -import org.eclipse.wst.jsdt.internal.core.ClassFile; -import org.eclipse.wst.jsdt.internal.core.CompilationUnit; -import org.eclipse.wst.jsdt.internal.core.JavaElement; -import org.eclipse.wst.jsdt.internal.core.Member; -import org.eclipse.wst.jsdt.internal.core.Openable; -import org.eclipse.wst.jsdt.internal.core.SourceTypeElementInfo; -import org.eclipse.wst.jsdt.internal.core.util.ASTNodeFinder; -import org.eclipse.wst.jsdt.internal.oaametadata.LibraryAPIs; - -public class HierarchyResolver implements ITypeRequestor, ITypeRequestor2 { - - private ReferenceBinding focusType; - private boolean superTypesOnly; - private boolean hasMissingSuperClass; - LookupEnvironment lookupEnvironment; - private CompilerOptions options; - HierarchyBuilder builder; - private ReferenceBinding[] typeBindings; - - HashtableOfObject parsedUnits; - HashSet processedUnits=new HashSet(); - - private int typeIndex; - private IGenericType[] typeModels; - -public HierarchyResolver(INameEnvironment nameEnvironment, Map settings, HierarchyBuilder builder, IProblemFactory problemFactory) { - // create a problem handler with the 'exit after all problems' handling policy - this.options = new CompilerOptions(settings); - IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.exitAfterAllProblems(); - ProblemReporter problemReporter = new ProblemReporter(policy, this.options, problemFactory); - - this.setEnvironment( - new LookupEnvironment(this, this.options, problemReporter, nameEnvironment), - builder); -} -public HierarchyResolver(LookupEnvironment lookupEnvironment, HierarchyBuilder builder) { - this.setEnvironment(lookupEnvironment, builder); -} - -/** - * Add an additional binary type - * @param binaryType - * @param packageBinding - */ -public void accept(IBinaryType binaryType, PackageBinding packageBinding, AccessRestriction accessRestriction) { -// IProgressMonitor progressMonitor = this.builder.hierarchy.progressMonitor; -// if (progressMonitor != null && progressMonitor.isCanceled()) -// throw new OperationCanceledException(); -// BinaryTypeBinding typeBinding = this.lookupEnvironment.createBinaryTypeFrom(binaryType, packageBinding, accessRestriction); -// try { -// this.remember(binaryType, typeBinding); -// } catch (AbortCompilation e) { -// // ignore -// } -} - -/** - * Add an additional compilation unit. - * @param sourceUnit - */ -public void accept(ICompilationUnit sourceUnit, AccessRestriction accessRestriction) { - accept(sourceUnit, new char[0][0], accessRestriction); -} - - public void accept(ICompilationUnit sourceUnit, char[][] typeNames, - AccessRestriction accessRestriction) { - // System.out.println("Cannot accept compilation units inside the HierarchyResolver."); - // this.lookupEnvironment.problemReporter.abortDueToInternalError( - // new StringBuffer(Messages.accept_cannot) - // .append(sourceUnit.getFileName()) - // .toString()); - if (typeNames.length == 0 && this.processedUnits.contains(sourceUnit)) - return; - - CompilationResult result = new CompilationResult(sourceUnit, 1, 1, - this.options.maxProblemsPerUnit); - - if (parsedUnits == null) - parsedUnits = new HashtableOfObject(); - CompilationUnitDeclaration parsedUnit = (CompilationUnitDeclaration) parsedUnits.get(sourceUnit.getFileName()); - if (parsedUnit == null) { - if (typeNames.length == 0) - this.processedUnits.add(sourceUnit); - Parser parser = new Parser(this.lookupEnvironment.problemReporter, true); - parsedUnit = parser.dietParse(sourceUnit, result); - parser.inferTypes(parsedUnit, this.options); - parsedUnits.put(sourceUnit.getFileName(), parsedUnit); - } - if (parsedUnit != null) { - try { - this.lookupEnvironment.buildTypeBindings(parsedUnit, typeNames, accessRestriction); - // org.eclipse.wst.jsdt.core.IJavaScriptUnit cu = - // ((SourceTypeElementInfo)sourceType).getHandle().getCompilationUnit(); - rememberAllTypes(parsedUnit, sourceUnit, false); - - this.lookupEnvironment.completeTypeBindings(parsedUnit, typeNames, true/* - * build constructor - * only - */); - } catch (AbortCompilation e) { - // missing 'java.lang' package: ignore - } - } - - } - - -public void accept(LibraryAPIs libraryMetaData) -{ - lookupEnvironment.buildTypeBindings(libraryMetaData); - -} - -/** - * Add additional source types - * @param sourceTypes - * @param packageBinding - */ -public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding, AccessRestriction accessRestriction) { - // find most enclosing type first (needed when explicit askForType(...) is done - // with a member type (e.g. p.A$B)) - IProgressMonitor progressMonitor = this.builder.hierarchy.progressMonitor; - if (progressMonitor != null && progressMonitor.isCanceled()) - throw new OperationCanceledException(); - ISourceType sourceType = sourceTypes[0]; - while (sourceType.getEnclosingType() != null) - sourceType = sourceType.getEnclosingType(); - - // build corresponding compilation unit - CompilationResult result = new CompilationResult(sourceType.getFileName(), sourceType.getPackageName(), 1, 1, this.options.maxProblemsPerUnit); - CompilationUnitDeclaration unit = - SourceTypeConverter.buildCompilationUnit( - new ISourceType[] {sourceType}, // ignore secondary types, to improve laziness - SourceTypeConverter.MEMBER_TYPE, // need member types - // no need for field initialization - this.lookupEnvironment.problemReporter, - result); - - // build bindings - if (unit != null) { - try { - this.lookupEnvironment.buildTypeBindings(unit, accessRestriction); - - org.eclipse.wst.jsdt.core.IJavaScriptUnit cu = ((SourceTypeElementInfo)sourceType).getHandle().getJavaScriptUnit(); - rememberAllTypes(unit, cu, false); - - this.lookupEnvironment.completeTypeBindings(unit, true/*build constructor only*/); - } catch (AbortCompilation e) { - // missing 'java.lang' package: ignore - } - } -} -/* - * Creates the super class handle of the given type. - * Returns null if the type has no super class. - * Adds the simple name to the hierarchy missing types if the class is not found and returns null. - */ -private IType findSuperClass(IGenericType type, ReferenceBinding typeBinding) { - ReferenceBinding superBinding = typeBinding.superclass(); - - - if (superBinding != null) { - if (typeBinding.isHierarchyInconsistent()) { - if (superBinding.problemId() == ProblemReasons.NotFound) { - this.hasMissingSuperClass = true; - this.builder.hierarchy.missingTypes.add(new String(superBinding.sourceName)); // note: this could be Map$Entry - return null; - } else if ((superBinding.id == TypeIds.T_JavaLangObject)) { - char[] superclassName; - char separator; - if (type instanceof IBinaryType) { - superclassName = ((IBinaryType)type).getSuperclassName(); - separator = '/'; - } else if (type instanceof ISourceType) { - superclassName = ((ISourceType)type).getSuperclassName(); - separator = '.'; - } else if (type instanceof HierarchyType) { - superclassName = ((HierarchyType)type).superclassName; - separator = '.'; - } else { - return null; - } - - if (superclassName != null) { // check whether subclass of Object due to broken hierarchy (as opposed to explicitly extending it) - int lastSeparator = CharOperation.lastIndexOf(separator, superclassName); - char[] simpleName = lastSeparator == -1 ? superclassName : CharOperation.subarray(superclassName, lastSeparator+1, superclassName.length); - if (!CharOperation.equals(simpleName, TypeConstants.OBJECT)) { - this.hasMissingSuperClass = true; - this.builder.hierarchy.missingTypes.add(new String(simpleName)); - return null; - } - } - } - } - for (int t = this.typeIndex; t >= 0; t--) { - if (this.typeBindings[t] == superBinding) { - return this.builder.getHandle(this.typeModels[t], superBinding); - } - } - } - - return null; -} - -private void fixSupertypeBindings() { - for (int current = this.typeIndex; current >= 0; current--) { - ReferenceBinding typeBinding = this.typeBindings[current]; - - - if (typeBinding instanceof SourceTypeBinding) { - ClassScope scope = (ClassScope)((SourceTypeBinding) typeBinding).scope; - if (scope != null) { - TypeDeclaration typeDeclaration = scope.referenceContext; - TypeReference superclassRef = typeDeclaration == null ? null : typeDeclaration.superclass; - TypeBinding superclass = superclassRef == null ? null : superclassRef.resolvedType; - if (superclass instanceof ProblemReferenceBinding) { - superclass = ((ProblemReferenceBinding) superclass).closestMatch(); - } - if (superclass != null) - ((SourceTypeBinding) typeBinding).superclass = (ReferenceBinding) superclass; - } - } else if (typeBinding instanceof BinaryTypeBinding) { - try { - typeBinding.superclass(); - } catch (AbortCompilation e) { - // allow subsequent call to superclass() to succeed so that we don't have to catch AbortCompilation everywhere - ((BinaryTypeBinding) typeBinding).tagBits &= ~TagBits.HasUnresolvedSuperclass; - this.builder.hierarchy.missingTypes.add(new String(typeBinding.superclass().sourceName())); - this.hasMissingSuperClass = true; - } - } - } -} - -private void remember(IGenericType suppliedType, ReferenceBinding typeBinding) { - if (typeBinding == null) return; - - if (++this.typeIndex == this.typeModels.length) { - System.arraycopy(this.typeModels, 0, this.typeModels = new IGenericType[this.typeIndex * 2], 0, this.typeIndex); - System.arraycopy(this.typeBindings, 0, this.typeBindings = new ReferenceBinding[this.typeIndex * 2], 0, this.typeIndex); - } - this.typeModels[this.typeIndex] = suppliedType; - this.typeBindings[this.typeIndex] = typeBinding; -} -private void remember(IType type, ReferenceBinding typeBinding) { - if (((CompilationUnit)type.getJavaScriptUnit()).isOpen()) { - try { - IGenericType genericType = (IGenericType)((JavaElement)type).getElementInfo(); - remember(genericType, typeBinding); - } catch (JavaScriptModelException e) { - // cannot happen since element is open - return; - } - } else { - if (typeBinding == null) return; - - TypeDeclaration typeDeclaration = ((ClassScope)((SourceTypeBinding)typeBinding).scope).referenceType(); - - // simple super class name - char[] superclassName = null; - TypeReference superclass; - if ((typeDeclaration.bits & ASTNode.IsAnonymousType) != 0) { - superclass = typeDeclaration.allocation.type; - } else { - superclass = typeDeclaration.superclass; - } - if (superclass != null) { - char[][] typeName = superclass.getTypeName(); - superclassName = typeName == null ? null : typeName[typeName.length-1]; - } - - HierarchyType hierarchyType = new HierarchyType( - type, - typeDeclaration.name, - typeDeclaration.binding.modifiers, - superclassName); - remember(hierarchyType, typeDeclaration.binding); - } - -} - -private void rememberInferredType(InferredType inferredType, IType type, ReferenceBinding typeBinding) { - if (type.getJavaScriptUnit()!=null && ((CompilationUnit)type.getJavaScriptUnit()).isOpen()) { - try { - IGenericType genericType = (IGenericType)((JavaElement)type).getElementInfo(); - remember(genericType, typeBinding); - } catch (JavaScriptModelException e) { - // cannot happen since element is open - return; - } - } else { - if (typeBinding == null) return; - -// TypeDeclaration typeDeclaration = ((SourceTypeBinding)typeBinding).scope.referenceType(); - - // simple super class name - char[] superclassName = inferredType.getSuperClassName(); -// TypeReference superclass; -// if ((typeDeclaration.bits & ASTNode.IsAnonymousType) != 0) { -// superclass = typeDeclaration.allocation.type; -// } else { -// superclass = typeDeclaration.superclass; -// } -// if (superclass != null) { -// char[][] typeName = superclass.getTypeName(); -// superclassName = typeName == null ? null : typeName[typeName.length-1]; -// } - - HierarchyType hierarchyType = new HierarchyType( - type, - inferredType.getName(), - 0,//typeDeclaration.binding.modifiers, - superclassName); - remember(hierarchyType, inferredType.binding); - } - -} -/* - * Remembers all type bindings defined in the given parsed unit, adding local/anonymous types if specified. - */ -private void rememberAllTypes(CompilationUnitDeclaration parsedUnit, Object container, boolean includeLocalTypes) { - org.eclipse.wst.jsdt.core.IJavaScriptUnit cu=(container instanceof org.eclipse.wst.jsdt.core.IJavaScriptUnit)? (org.eclipse.wst.jsdt.core.IJavaScriptUnit)container:null; - org.eclipse.wst.jsdt.core.IClassFile classFile=(container instanceof org.eclipse.wst.jsdt.core.IClassFile)? (org.eclipse.wst.jsdt.core.IClassFile)container:null; - TypeDeclaration[] types = parsedUnit.types; - if (types != null) { - for (int i = 0, length = types.length; i < length; i++) { - TypeDeclaration type = types[i]; - IType typeHandle= (cu!=null) ? cu.getType(new String(type.name)) : classFile.getType(new String(type.name)); - rememberWithMemberTypes(type, typeHandle); - } - } - for (int i=0;i= 0; current--) { - ReferenceBinding typeBinding = this.typeBindings[current]; - - // java.lang.Object treated at the end - if (typeBinding.id == TypeIds.T_JavaLangObject) { - objectIndex = current; - continue; - } - - IGenericType suppliedType = this.typeModels[current]; - - if (!subOrSuperOfFocus(typeBinding)) { - continue; // ignore types outside of hierarchy - } - - IType superclass = findSuperClass(suppliedType, typeBinding); - - this.builder.connect(suppliedType, this.builder.getHandle(suppliedType, typeBinding), superclass); - } - // add java.lang.Object only if the super class is not missing - if (!this.hasMissingSuperClass && objectIndex > -1) { - IGenericType objectType = this.typeModels[objectIndex]; - this.builder.connect(objectType, this.builder.getHandle(objectType, this.typeBindings[objectIndex]), null); - } -} - - -private void reset(){ - this.lookupEnvironment.reset(); - - this.focusType = null; - this.superTypesOnly = false; - this.typeIndex = -1; - this.typeModels = new IGenericType[5]; - this.typeBindings = new ReferenceBinding[5]; - if(parsedUnits != null) - this.parsedUnits.clear(); -} - -/** - * Resolve the supertypes for the supplied source type. - * Inform the requestor of the resolved supertypes using: - * connect(ISourceType suppliedType, IGenericType superclass) - * @param suppliedType - */ -public void resolve(IGenericType suppliedType) { - try { - if (suppliedType.isBinaryType()) { - ReferenceBinding binaryTypeBinding = this.lookupEnvironment.cacheBinaryType((ISourceType) suppliedType, false/*don't need field and method (bug 125067)*/, null /*no access restriction*/); - remember(suppliedType, binaryTypeBinding); - // We still need to add superclasses binding (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=53095) - int startIndex = this.typeIndex; - for (int i = startIndex; i <= this.typeIndex; i++) { - IGenericType igType = this.typeModels[i]; - if (igType != null && igType.isBinaryType()) { - // fault in its hierarchy... - try { - ReferenceBinding typeBinding = this.typeBindings[i]; - typeBinding.superclass(); - } catch (AbortCompilation e) { - // classpath problem for this type: ignore - } - } - } - this.superTypesOnly = true; - reportHierarchy(this.builder.getType(), null, binaryTypeBinding); - } else { - org.eclipse.wst.jsdt.core.IJavaScriptUnit cu = ((SourceTypeElementInfo)suppliedType).getHandle().getJavaScriptUnit(); - HashSet localTypes = new HashSet(); - localTypes.add(cu.getPath().toString()); - this.superTypesOnly = true; - resolve(new Openable[] {(Openable)cu}, localTypes, null); - } - } catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object - } finally { - reset(); - } -} - -/** - * Resolve the supertypes for the types contained in the given openables (ICompilationUnits and/or IClassFiles). - * Inform the requestor of the resolved supertypes for each - * supplied source type using: - * connect(ISourceType suppliedType, IGenericType superclass) - * - * Also inform the requestor of the supertypes of each - * additional requested super type which is also a source type - * instead of a binary type. - * @param openables - * @param localTypes - * @param monitor - */ -public void resolve(Openable[] openables, HashSet localTypes, IProgressMonitor monitor) { - try { - int openablesLength = openables.length; - CompilationUnitDeclaration[] parsedUnits = new CompilationUnitDeclaration[openablesLength]; - boolean[] hasLocalType = new boolean[openablesLength]; - org.eclipse.wst.jsdt.core.IJavaScriptUnit[] cus = new org.eclipse.wst.jsdt.core.IJavaScriptUnit[openablesLength]; - int unitsIndex = 0; - - CompilationUnitDeclaration focusUnit = null; - ReferenceBinding focusBinaryBinding = null; - IType focus = this.builder.getType(); - Openable focusOpenable = null; - if (focus != null) { - if (focus.isBinary()) { - focusOpenable = (Openable)focus.getClassFile(); - } else { - focusOpenable = (Openable)focus.getJavaScriptUnit(); - } - } - - processedUnits=new HashSet(); - // build type bindings - Parser parser = new Parser(this.lookupEnvironment.problemReporter, true); - for (int i = 0; i < openablesLength; i++) { - Openable openable = openables[i]; - if (openable instanceof org.eclipse.wst.jsdt.core.IJavaScriptUnit) { - org.eclipse.wst.jsdt.core.IJavaScriptUnit cu = (org.eclipse.wst.jsdt.core.IJavaScriptUnit)openable; - - // contains a potential subtype as a local or anonymous type? - boolean containsLocalType = false; - if (localTypes == null) { // case of hierarchy on region - containsLocalType = true; - } else { - IPath path = cu.getPath(); - containsLocalType = localTypes.contains(path.toString()); - } - - // build parsed unit - CompilationUnitDeclaration parsedUnit = null; - if (cu.isOpen()) { - // create parsed unit from source element infos - CompilationResult result = new CompilationResult(((ICompilationUnit)cu).getFileName(), ((ICompilationUnit)cu).getPackageName(), i, openablesLength, this.options.maxProblemsPerUnit); - SourceTypeElementInfo[] typeInfos = null; - try { - IType[] topLevelTypes = cu.getTypes(); - int topLevelLength = topLevelTypes.length; - if (topLevelLength == 0) continue; // empty cu: no need to parse (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=65677) - typeInfos = new SourceTypeElementInfo[topLevelLength]; - for (int j = 0; j < topLevelLength; j++) { - IType topLevelType = topLevelTypes[j]; - typeInfos[j] = (SourceTypeElementInfo)((JavaElement)topLevelType).getElementInfo(); - } - } catch (JavaScriptModelException e) { - // types/cu exist since cu is opened - } - int flags = !containsLocalType - ? SourceTypeConverter.MEMBER_TYPE - : SourceTypeConverter.FIELD_AND_METHOD | SourceTypeConverter.MEMBER_TYPE | SourceTypeConverter.LOCAL_TYPE; - parsedUnit = - SourceTypeConverter.buildCompilationUnit( - typeInfos, - flags, - this.lookupEnvironment.problemReporter, - result); - if (containsLocalType) parsedUnit.bits |= ASTNode.HasAllMethodBodies; - } else { - // create parsed unit from file - IFile file = (IFile) cu.getResource(); - ICompilationUnit sourceUnit = this.builder.createCompilationUnitFromPath(openable, file); - - CompilationResult unitResult = new CompilationResult(sourceUnit, i, openablesLength, this.options.maxProblemsPerUnit); - parsedUnit = parser.dietParse(sourceUnit, unitResult); - } - - if (parsedUnit != null) { - parser.inferTypes(parsedUnit, this.options); - hasLocalType[unitsIndex] = containsLocalType; - cus[unitsIndex] = cu; - parsedUnits[unitsIndex++] = parsedUnit; - try { - if (!processedUnits.contains(openable)) - this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/); - processedUnits.add(openable); - if (openable.equals(focusOpenable)) { - focusUnit = parsedUnit; - } - } catch (AbortCompilation e) { - // classpath problem for this type: ignore - } - } - } else { - // cache binary type binding - ClassFile classFile = (ClassFile)openable; - org.eclipse.wst.jsdt.internal.compiler.batch.CompilationUnit sourceUnit = - new org.eclipse.wst.jsdt.internal.compiler.batch.CompilationUnit(null,new String(classFile.getFileName()),this.options.defaultEncoding); - //sourceUnit.packageName=Util.toCharArrays(new String[]{classFile.getParent().getElementName()}); - CompilationResult unitResult = new CompilationResult(sourceUnit, i, openablesLength, this.options.maxProblemsPerUnit); - CompilationUnitDeclaration parsedUnit = parser.dietParse(sourceUnit, unitResult); - if (parsedUnit != null) { - parser.inferTypes(parsedUnit, this.options); - hasLocalType[unitsIndex] = true; - cus[unitsIndex] = null; - parsedUnits[unitsIndex++] = parsedUnit; - try { - this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/); - if (openable.equals(focusOpenable)) { - focusUnit = parsedUnit; - } - } catch (AbortCompilation e) { - // classpath problem for this type: ignore - } - } - - // ISourceType binaryType = null; -// if (classFile.isOpen()) { -// // create binary type from info -// IType type = classFile.getType(); -// try { -// binaryType = (ISourceType)((JavaElement)type).getElementInfo(); -// } catch (JavaScriptModelException e) { -// // type exists since class file is opened -// } -// } else { -// // create binary type from file -// if (classFile.getPackageFragmentRoot().isArchive()) { -// binaryType = this.builder.createInfoFromClassFileInJar(classFile); -// } else { -// IResource file = classFile.getResource(); -// binaryType = this.builder.createInfoFromClassFile(classFile, file); -// } -// } -// if (binaryType != null) { -// try { -// BinaryTypeBinding binaryTypeBinding = this.lookupEnvironment.cacheBinaryType(binaryType, false/*don't need field and method (bug 125067)*/, null /*no access restriction*/); -// remember(binaryType, binaryTypeBinding); -// if (openable.equals(focusOpenable)) { -// focusBinaryBinding = binaryTypeBinding; -// } -// } catch (AbortCompilation e) { -// // classpath problem for this type: ignore -// } -// } - } - } - - for (int i = 0; i <= this.typeIndex; i++) { - IGenericType suppliedType = this.typeModels[i]; - if (suppliedType != null && suppliedType.isBinaryType()) { - // fault in its hierarchy... - try { - ReferenceBinding typeBinding = this.typeBindings[i]; - typeBinding.superclass(); - } catch (AbortCompilation e) { - // classpath problem for this type: ignore - } - } - } - - // complete type bindings (ie. connect super types) - for (int i = 0; i < unitsIndex; i++) { - CompilationUnitDeclaration parsedUnit = parsedUnits[i]; - if (parsedUnit != null) { - try { - boolean containsLocalType = hasLocalType[i]; - if (containsLocalType) { // NB: no-op if method bodies have been already parsed - parser.getMethodBodies(parsedUnit); - } - // complete type bindings and build fields and methods only for local types - // (in this case the constructor is needed when resolving local types) - // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=145333) - this.lookupEnvironment.completeTypeBindings(parsedUnit, containsLocalType); - } catch (AbortCompilation e) { - // classpath problem for this type: don't try to resolve (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=49809) - hasLocalType[i] = false; - } - } - worked(monitor, 1); - } - - // remember type bindings - for (int i = 0; i < unitsIndex; i++) { - CompilationUnitDeclaration parsedUnit = parsedUnits[i]; - if (parsedUnit != null) { - boolean containsLocalType = hasLocalType[i]; - if (containsLocalType) { - parsedUnit.scope.faultInTypes(); - parsedUnit.resolve(); - } - - rememberAllTypes(parsedUnit, openables[i], containsLocalType); - } - } - - // if no potential subtype was a real subtype of the binary focus type, no need to go further - // (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=54043) - if (focus != null && focus.isBinary()) { - char [] typeName=focus.getElementName().toCharArray(); - char [] pkgName=focus.getPackageFragment().getElementName().toCharArray(); - char [][]qualifiedName=new char[][]{pkgName,typeName}; - focusBinaryBinding = this.lookupEnvironment.getCachedType(qualifiedName); - if (focusBinaryBinding == null) { - qualifiedName=new char[][]{typeName}; - focusBinaryBinding = this.lookupEnvironment.getCachedType(qualifiedName); - } - if (focusBinaryBinding == null) - return; - } - - reportHierarchy(focus, focusUnit, focusBinaryBinding); - - } catch (ClassCastException e){ // work-around for 1GF5W1S - can happen in case duplicates are fed to the hierarchy with binaries hiding sources - } catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object - if (TypeHierarchy.DEBUG) - e.printStackTrace(); - } finally { - reset(); - } -} -private void setEnvironment(LookupEnvironment lookupEnvironment, HierarchyBuilder builder) { - this.lookupEnvironment = lookupEnvironment; - this.builder = builder; - - this.typeIndex = -1; - this.typeModels = new IGenericType[5]; - this.typeBindings = new ReferenceBinding[5]; -} - -/* - * Set the focus type (ie. the type that this resolver is computing the hierarch for. - * Returns the binding of this focus type or null if it could not be found. - */ -public ReferenceBinding setFocusType(char[][] compoundName) { - if (compoundName == null || this.lookupEnvironment == null) return null; - this.focusType = this.lookupEnvironment.getCachedType(compoundName); - if (this.focusType == null) { - this.focusType = this.lookupEnvironment.askForType(compoundName); - } - if (this.focusType==null) - { - char [][] singleName= {CharOperation.concatWith(compoundName, '.')}; - this.focusType = this.lookupEnvironment.getCachedType(singleName); - if (this.focusType == null) { - this.focusType = this.lookupEnvironment.askForType(singleName); - } - } - return this.focusType; -} -public boolean subOrSuperOfFocus(ReferenceBinding typeBinding) { - if (this.focusType == null) return true; // accept all types (case of hierarchy in a region) - try { - if (this.subTypeOfType(this.focusType, typeBinding)) return true; - if (!this.superTypesOnly && this.subTypeOfType(typeBinding, this.focusType)) return true; - } catch (AbortCompilation e) { - // unresolved superclass -> ignore - } - return false; -} -private boolean subTypeOfType(ReferenceBinding subType, ReferenceBinding typeBinding) { - if (typeBinding == null || subType == null) return false; - if (subType == typeBinding) return true; - ReferenceBinding superclass = subType.superclass(); - if (superclass != null && superclass.id == TypeIds.T_JavaLangObject && subType.isHierarchyInconsistent()) return false; - if (this.subTypeOfType(superclass, typeBinding)) return true; - return false; -} -protected void worked(IProgressMonitor monitor, int work) { - if (monitor != null) { - if (monitor.isCanceled()) { - throw new OperationCanceledException(); - } else { - monitor.worked(work); - } - } -} -public CompilationUnitDeclaration doParse(ICompilationUnit sourceUnit, AccessRestriction accessRestriction) { - Parser parser = new Parser(this.lookupEnvironment.problemReporter, true); - CompilationResult unitResult = - new CompilationResult(sourceUnit, 1, 1, this.options.maxProblemsPerUnit); - CompilationUnitDeclaration declaration = parser.dietParse(sourceUnit, unitResult); - parser.inferTypes(declaration,this.options); - return declaration; -} -} +/******************************************************************************* + * Copyright (c) 2000, 2013 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.wst.jsdt.internal.core.hierarchy; + +/** + * This is the public entry point to resolve type hierarchies. + * + * When requesting additional types from the name environment, the resolver + * accepts all forms (binary, source & compilation unit) for additional types. + * + * Side notes: Binary types already know their resolved supertypes so this + * only makes sense for source types. Even though the compiler finds all binary + * types to complete the hierarchy of a given source type, is there any reason + * why the requestor should be informed that binary type X subclasses Y & + * implements I & J? + */ + +import java.util.HashSet; +import java.util.Map; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.OperationCanceledException; +import org.eclipse.wst.jsdt.core.IType; +import org.eclipse.wst.jsdt.core.JavaScriptModelException; +import org.eclipse.wst.jsdt.core.compiler.CharOperation; +import org.eclipse.wst.jsdt.core.infer.InferredType; +import org.eclipse.wst.jsdt.internal.compiler.CompilationResult; +import org.eclipse.wst.jsdt.internal.compiler.DefaultErrorHandlingPolicies; +import org.eclipse.wst.jsdt.internal.compiler.IErrorHandlingPolicy; +import org.eclipse.wst.jsdt.internal.compiler.IProblemFactory; +import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode; +import org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration; +import org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration; +import org.eclipse.wst.jsdt.internal.compiler.ast.TypeReference; +import org.eclipse.wst.jsdt.internal.compiler.env.AccessRestriction; +import org.eclipse.wst.jsdt.internal.compiler.env.IBinaryType; +import org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit; +import org.eclipse.wst.jsdt.internal.compiler.env.IGenericType; +import org.eclipse.wst.jsdt.internal.compiler.env.INameEnvironment; +import org.eclipse.wst.jsdt.internal.compiler.env.ISourceType; +import org.eclipse.wst.jsdt.internal.compiler.impl.CompilerOptions; +import org.eclipse.wst.jsdt.internal.compiler.impl.ITypeRequestor; +import org.eclipse.wst.jsdt.internal.compiler.impl.ITypeRequestor2; +import org.eclipse.wst.jsdt.internal.compiler.lookup.BinaryTypeBinding; +import org.eclipse.wst.jsdt.internal.compiler.lookup.ClassScope; +import org.eclipse.wst.jsdt.internal.compiler.lookup.LookupEnvironment; +import org.eclipse.wst.jsdt.internal.compiler.lookup.PackageBinding; +import org.eclipse.wst.jsdt.internal.compiler.lookup.ProblemReasons; +import org.eclipse.wst.jsdt.internal.compiler.lookup.ProblemReferenceBinding; +import org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding; +import org.eclipse.wst.jsdt.internal.compiler.lookup.SourceTypeBinding; +import org.eclipse.wst.jsdt.internal.compiler.lookup.TagBits; +import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding; +import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeConstants; +import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeIds; +import org.eclipse.wst.jsdt.internal.compiler.parser.Parser; +import org.eclipse.wst.jsdt.internal.compiler.parser.SourceTypeConverter; +import org.eclipse.wst.jsdt.internal.compiler.problem.AbortCompilation; +import org.eclipse.wst.jsdt.internal.compiler.problem.ProblemReporter; +import org.eclipse.wst.jsdt.internal.compiler.util.HashtableOfObject; +import org.eclipse.wst.jsdt.internal.core.ClassFile; +import org.eclipse.wst.jsdt.internal.core.CompilationUnit; +import org.eclipse.wst.jsdt.internal.core.JavaElement; +import org.eclipse.wst.jsdt.internal.core.Logger; +import org.eclipse.wst.jsdt.internal.core.Member; +import org.eclipse.wst.jsdt.internal.core.Openable; +import org.eclipse.wst.jsdt.internal.core.SourceTypeElementInfo; +import org.eclipse.wst.jsdt.internal.core.util.ASTNodeFinder; +import org.eclipse.wst.jsdt.internal.oaametadata.LibraryAPIs; + +public class HierarchyResolver implements ITypeRequestor, ITypeRequestor2 { + + private ReferenceBinding focusType; + private boolean superTypesOnly; + private boolean hasMissingSuperClass; + LookupEnvironment lookupEnvironment; + private CompilerOptions options; + HierarchyBuilder builder; + private ReferenceBinding[] typeBindings; + + HashtableOfObject parsedUnits; + HashSet processedUnits = new HashSet(); + + private int typeIndex; + private IGenericType[] typeModels; + + public HierarchyResolver(INameEnvironment nameEnvironment, Map settings, HierarchyBuilder builder, IProblemFactory problemFactory) { + // create a problem handler with the 'exit after all problems' handling policy + this.options = new CompilerOptions(settings); + IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.exitAfterAllProblems(); + ProblemReporter problemReporter = new ProblemReporter(policy, this.options, problemFactory); + + this.setEnvironment(new LookupEnvironment(this, this.options, problemReporter, nameEnvironment), builder); + } + + public HierarchyResolver(LookupEnvironment lookupEnvironment, HierarchyBuilder builder) { + this.setEnvironment(lookupEnvironment, builder); + } + + /** + * @see org.eclipse.wst.jsdt.internal.compiler.impl.ITypeRequestor#accept(org.eclipse.wst.jsdt.internal.compiler.env.IBinaryType, org.eclipse.wst.jsdt.internal.compiler.lookup.PackageBinding, org.eclipse.wst.jsdt.internal.compiler.env.AccessRestriction) + */ + public void accept(IBinaryType binaryType, PackageBinding packageBinding, AccessRestriction accessRestriction) { + //do nothing + } + + /** + * Add an additional compilation unit. + * + * @param sourceUnit + */ + public void accept(ICompilationUnit sourceUnit, AccessRestriction accessRestriction) { + accept(sourceUnit, CharOperation.NO_CHAR_CHAR, accessRestriction); + } + + public void accept(ICompilationUnit sourceUnit, char[][] typeNames, AccessRestriction accessRestriction) { + if (typeNames.length == 0 && this.processedUnits.contains(sourceUnit)) { + return; + } + + CompilationResult result = new CompilationResult(sourceUnit, 1, 1, this.options.maxProblemsPerUnit); + + if (parsedUnits == null) { + parsedUnits = new HashtableOfObject(); + } + + CompilationUnitDeclaration parsedUnit = (CompilationUnitDeclaration) parsedUnits.get(sourceUnit.getFileName()); + if (parsedUnit == null) { + if (typeNames.length == 0) { + this.processedUnits.add(sourceUnit); + } + Parser parser = new Parser(this.lookupEnvironment.problemReporter, true); + parsedUnit = parser.dietParse(sourceUnit, result); + parser.inferTypes(parsedUnit, this.options); + parsedUnits.put(sourceUnit.getFileName(), parsedUnit); + } + if (parsedUnit != null) { + try { + this.lookupEnvironment.buildTypeBindings(parsedUnit, typeNames, accessRestriction); + rememberAllTypes(parsedUnit, sourceUnit, false); + + this.lookupEnvironment.completeTypeBindings(parsedUnit, typeNames, true); + } + catch (AbortCompilation e) { + // missing 'java.lang' package: ignore + } + } + + } + + public void accept(LibraryAPIs libraryMetaData) { + lookupEnvironment.buildTypeBindings(libraryMetaData); + } + + /** + * Add additional source types + * + * @param sourceTypes + * @param packageBinding + */ + public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding, AccessRestriction accessRestriction) { + /* find most enclosing type first (needed when explicit askForType(...) is done + * with a member type (e.g. p.A$B)) */ + IProgressMonitor progressMonitor = this.builder.hierarchy.progressMonitor; + if (progressMonitor != null && progressMonitor.isCanceled()) { + throw new OperationCanceledException(); + } + ISourceType sourceType = sourceTypes[0]; + while (sourceType.getEnclosingType() != null) { + sourceType = sourceType.getEnclosingType(); + } + + // build corresponding compilation unit + CompilationResult result = new CompilationResult(sourceType.getFileName(), sourceType.getPackageName(), 1, 1, this.options.maxProblemsPerUnit); + + // ignore secondary types, to improve laziness + CompilationUnitDeclaration unit = SourceTypeConverter.buildCompilationUnit(new ISourceType[]{sourceType}, + SourceTypeConverter.MEMBER_TYPE, // need member types no need for field initialization + this.lookupEnvironment.problemReporter, result); + + // build bindings + if (unit != null) { + try { + this.lookupEnvironment.buildTypeBindings(unit, accessRestriction); + + org.eclipse.wst.jsdt.core.IJavaScriptUnit cu = ((SourceTypeElementInfo) sourceType).getHandle().getJavaScriptUnit(); + rememberAllTypes(unit, cu, false); + + this.lookupEnvironment.completeTypeBindings(unit, true); + } + catch (AbortCompilation e) { + // missing 'java.lang' package: ignore + } + } + } + + /** + *

      + * Creates the super class handle of the given type. Returns null if the type + * has no super class. Adds the simple name to the hierarchy missing types if + * the class is not found and returns null. + *

      + */ + private IType findSuperClass(IGenericType type, ReferenceBinding typeBinding) { + ReferenceBinding superBinding = typeBinding.getSuperBinding(); + + if (superBinding != null) { + if (typeBinding.isHierarchyInconsistent()) { + if (superBinding.problemId() == ProblemReasons.NotFound) { + this.hasMissingSuperClass = true; + + // note: this could be Map$Entry + this.builder.hierarchy.missingTypes.add(new String(superBinding.sourceName)); + return null; + } + else if ((superBinding.id == TypeIds.T_JavaLangObject)) { + char[] superclassName; + char separator; + if (type instanceof IBinaryType) { + superclassName = ((IBinaryType) type).getSuperclassName(); + separator = '/'; + } + else if (type instanceof ISourceType) { + superclassName = ((ISourceType) type).getSuperclassName(); + separator = '.'; + } + else if (type instanceof HierarchyType) { + superclassName = ((HierarchyType) type).superclassName; + separator = '.'; + } + else { + return null; + } + + // check whether subclass of Object due to broken hierarchy (as opposed to explicitly extending it) + if (superclassName != null) { + int lastSeparator = CharOperation.lastIndexOf(separator, superclassName); + char[] simpleName = lastSeparator == -1 ? + superclassName : CharOperation.subarray(superclassName, lastSeparator + 1, superclassName.length); + + if (!CharOperation.equals(simpleName, TypeConstants.OBJECT)) { + this.hasMissingSuperClass = true; + this.builder.hierarchy.missingTypes.add(new String(simpleName)); + return null; + } + } + } + } + char[] readableName = superBinding.readableName(); + for (int t = this.typeIndex; t >= 0; t--) { + /* For the purpose of the hierarchy, two types are equivalent if + * they have the same readable name + * + * this is instead of using TypeBinding#isEquivlant on purpose + * because then a type with multiple names would + * only show up in the hierarchy once. */ + + if (CharOperation.equals( + readableName, + this.typeBindings[t].readableName())) { + + return this.builder.getHandle(this.typeModels[t], superBinding); + } + } + } + + return null; + } + + private void fixSupertypeBindings() { + for (int current = this.typeIndex; current >= 0; current--) { + ReferenceBinding typeBinding = this.typeBindings[current]; + + if (typeBinding instanceof SourceTypeBinding) { + ClassScope scope = (ClassScope) ((SourceTypeBinding) typeBinding).scope; + if (scope != null) { + TypeDeclaration typeDeclaration = scope.referenceContext; + TypeReference superclassRef = typeDeclaration == null ? null : typeDeclaration.superclass; + TypeBinding superclass = superclassRef == null ? null : superclassRef.resolvedType; + if (superclass instanceof ProblemReferenceBinding) { + superclass = ((ProblemReferenceBinding) superclass).closestMatch(); + } + if (superclass != null) { + ((SourceTypeBinding) typeBinding).setSuperBinding((ReferenceBinding) superclass); + } + } + } + else if (typeBinding instanceof BinaryTypeBinding) { + try { + typeBinding.getSuperBinding(); + } + catch (AbortCompilation e) { + /* allow subsequent call to superclass() to succeed so that + * we don't have to catch AbortCompilation everywhere */ + ((BinaryTypeBinding) typeBinding).tagBits &= ~TagBits.HasUnresolvedSuperclass; + this.builder.hierarchy.missingTypes.add(new String(typeBinding.getSuperBinding().sourceName())); + this.hasMissingSuperClass = true; + } + } + } + } + + private void remember(IGenericType suppliedType, ReferenceBinding typeBinding) { + if (typeBinding == null) { + return; + } + + //check if this type is a duplicate of one already being remembered + boolean isDuplicate = false; + int i; + for(i = 0; i <= this.typeIndex && !isDuplicate; ++i) { + /* For the purpose of the hierarchy, two types are equivalent if + * they have the same readable name and are defined in the same file */ + isDuplicate = CharOperation.equals(typeBinding.getFileName(), this.typeBindings[i].getFileName()) && + CharOperation.equals( + typeBinding.readableName(), + this.typeBindings[i].readableName()); + } + + if(!isDuplicate) { + if (++this.typeIndex == this.typeModels.length) { + System.arraycopy(this.typeModels, 0, this.typeModels = new IGenericType[this.typeIndex * 2], 0, this.typeIndex); + System.arraycopy(this.typeBindings, 0, this.typeBindings = new ReferenceBinding[this.typeIndex * 2], 0, this.typeIndex); + } + + this.typeModels[this.typeIndex] = suppliedType; + this.typeBindings[this.typeIndex] = typeBinding; + } + } + + private void remember(IType type, ReferenceBinding typeBinding) { + if (((CompilationUnit) type.getJavaScriptUnit()).isOpen()) { + try { + IGenericType genericType = (IGenericType) ((JavaElement) type).getElementInfo(); + remember(genericType, typeBinding); + } + catch (JavaScriptModelException e) { + // cannot happen since element is open + return; + } + } + else { + if (typeBinding == null) { + return; + } + + TypeDeclaration typeDeclaration = ((ClassScope) ((SourceTypeBinding) typeBinding).scope).referenceType(); + + // simple super class name + char[] superclassName = null; + TypeReference superclass; + if ((typeDeclaration.bits & ASTNode.IsAnonymousType) != 0) { + superclass = typeDeclaration.allocation.type; + } + else { + superclass = typeDeclaration.superclass; + } + if (superclass != null) { + char[][] typeName = superclass.getTypeName(); + superclassName = typeName == null ? null : typeName[typeName.length - 1]; + } + + HierarchyType hierarchyType = new HierarchyType(type, typeDeclaration.name, typeDeclaration.binding.modifiers, superclassName); + remember(hierarchyType, typeDeclaration.binding); + } + + } + + private void rememberInferredType(InferredType inferredType, IType type, ReferenceBinding typeBinding) { + if (type.getJavaScriptUnit() != null && ((CompilationUnit) type.getJavaScriptUnit()).isOpen()) { + try { + IGenericType genericType = (IGenericType) ((JavaElement) type).getElementInfo(); + remember(genericType, typeBinding); + } + catch (JavaScriptModelException e) { + // cannot happen since element is open + return; + } + } + else { + if (typeBinding == null) { + return; + } + + // simple super class name + char[] superclassName = null; + ReferenceBinding superBinding = typeBinding.getSuperBinding(); + if(superBinding != null) { + superclassName = superBinding.qualifiedSourceName(); + } + + HierarchyType hierarchyType = new HierarchyType(type, inferredType.getName(), 0, superclassName); + remember(hierarchyType, inferredType.binding); + } + + } + + /** + *

      + * Remembers all type bindings defined in the given parsed unit, adding + * local/anonymous types if specified. + *

      + * + * @param parsedUnit + * @param container + * @param includeLocalTypes + */ + private void rememberAllTypes(CompilationUnitDeclaration parsedUnit, Object container, boolean includeLocalTypes) { + org.eclipse.wst.jsdt.core.IJavaScriptUnit cu = (container instanceof org.eclipse.wst.jsdt.core.IJavaScriptUnit) ? (org.eclipse.wst.jsdt.core.IJavaScriptUnit) container : null; + org.eclipse.wst.jsdt.core.IClassFile classFile = (container instanceof org.eclipse.wst.jsdt.core.IClassFile) ? (org.eclipse.wst.jsdt.core.IClassFile) container : null; + TypeDeclaration[] types = parsedUnit.types; + if (types != null) { + for (int i = 0, length = types.length; i < length; i++) { + TypeDeclaration type = types[i]; + IType typeHandle = (cu != null) ? cu.getType(new String(type.name)) : classFile.getType(new String(type.name)); + rememberWithMemberTypes(type, typeHandle); + } + } + for (int i = 0; i < parsedUnit.numberInferredTypes; i++) { + InferredType inferredType = parsedUnit.inferredTypes[i]; + + if (inferredType.isDefinition()) { + IType typeHandle = (cu != null) ? cu.getType(new String(inferredType.getName())) : classFile.getType(new String(inferredType.getName())); + rememberInferredType(inferredType, typeHandle, inferredType.binding); + } + } + } + + private void rememberWithMemberTypes(TypeDeclaration typeDecl, IType typeHandle) { + remember(typeHandle, typeDecl.binding); + + TypeDeclaration[] memberTypes = typeDecl.memberTypes; + if (memberTypes != null) { + for (int i = 0, length = memberTypes.length; i < length; i++) { + TypeDeclaration memberType = memberTypes[i]; + rememberWithMemberTypes(memberType, typeHandle.getType(new String(memberType.name))); + } + } + } + + /** + *

      + * Reports the hierarchy from the remembered bindings. Note that + * 'binaryTypeBinding' is null if focus type is a source type. + *

      + * + * @param focus + * @param parsedUnit + * @param binaryTypeBinding + */ + private void reportHierarchy(IType focus, CompilationUnitDeclaration parsedUnit, ReferenceBinding binaryTypeBinding) { + // set focus type binding + if (focus != null) { + if (binaryTypeBinding != null) { + // binary type + this.focusType = binaryTypeBinding; + } + else { + // source type + Member declaringMember = ((Member) focus).getOuterMostLocalContext(); + if (declaringMember == null) { + // top level or member type + char[] fullyQualifiedName = focus.getElementName().toCharArray(); + setFocusType(CharOperation.splitOn('.', fullyQualifiedName)); + } + else { + // anonymous or local type + if (parsedUnit != null) { + ASTNodeFinder nodeFinder = new ASTNodeFinder(parsedUnit); + InferredType inferredType = nodeFinder.findInferredType(focus); + if (inferredType != null) + this.focusType = inferredType.binding; + else { + TypeDeclaration typeDecl = nodeFinder.findType(focus); + if (typeDecl != null) { + this.focusType = typeDecl.binding; + } + } + } + } + } + } + // be resilient and fix super type bindings + fixSupertypeBindings(); + + int objectIndex = -1; + for (int current = this.typeIndex; current >= 0; current--) { + ReferenceBinding typeBinding = this.typeBindings[current]; + + // java.lang.Object treated at the end + if (typeBinding.id == TypeIds.T_JavaLangObject) { + objectIndex = current; + continue; + } + + IGenericType suppliedType = this.typeModels[current]; + + if (!subOrSuperOfFocus(typeBinding)) { + continue; // ignore types outside of hierarchy + } + + IType superclass = findSuperClass(suppliedType, typeBinding); + + this.builder.connect(suppliedType, this.builder.getHandle(suppliedType, typeBinding), superclass); + } + // add java.lang.Object only if the super class is not missing + if (!this.hasMissingSuperClass && objectIndex > -1) { + IGenericType objectType = this.typeModels[objectIndex]; + this.builder.connect(objectType, this.builder.getHandle(objectType, this.typeBindings[objectIndex]), null); + } + } + + + private void reset() { + this.lookupEnvironment.reset(); + + this.focusType = null; + this.superTypesOnly = false; + this.typeIndex = -1; + this.typeModels = new IGenericType[5]; + this.typeBindings = new ReferenceBinding[5]; + if (parsedUnits != null) { + this.parsedUnits.clear(); + } + } + + /** + * Resolve the supertypes for the supplied source type. Inform the + * requestor of the resolved supertypes using: connect(ISourceType + * suppliedType, IGenericType superclass) + * + * @param suppliedType + */ + public void resolve(IGenericType suppliedType) { + try { + if (suppliedType.isBinaryType()) { + ReferenceBinding binaryTypeBinding = + this.lookupEnvironment.cacheBinaryType((ISourceType) suppliedType, false, null ); + + remember(suppliedType, binaryTypeBinding); + + // We still need to add superclasses binding (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=53095) + int startIndex = this.typeIndex; + for (int i = startIndex; i <= this.typeIndex; i++) { + IGenericType igType = this.typeModels[i]; + if (igType != null && igType.isBinaryType()) { + // fault in its hierarchy... + try { + ReferenceBinding typeBinding = this.typeBindings[i]; + typeBinding.getSuperBinding(); + } + catch (AbortCompilation e) { + // classpath problem for this type: ignore + } + } + } + this.superTypesOnly = true; + reportHierarchy(this.builder.getType(), null, binaryTypeBinding); + } + else { + org.eclipse.wst.jsdt.core.IJavaScriptUnit cu = ((SourceTypeElementInfo) suppliedType).getHandle().getJavaScriptUnit(); + HashSet localTypes = new HashSet(); + localTypes.add(cu.getPath().toString()); + this.superTypesOnly = true; + resolve(new Openable[]{(Openable) cu}, localTypes, null); + } + } + catch (AbortCompilation e) { + // ignore this exception for now since it typically means we cannot find java.lang.Object + } + finally { + reset(); + } + } + + /** + * Resolve the supertypes for the types contained in the given openables + * (ICompilationUnits and/or IClassFiles). Inform the requestor of the + * resolved supertypes for each supplied source type using: + * connect(ISourceType suppliedType, IGenericType superclass) + * + * Also inform the requestor of the supertypes of each additional + * requested super type which is also a source type instead of a binary + * type. + * + * @param openables + * @param localTypes + * @param monitor + */ + public void resolve(Openable[] openables, HashSet localTypes, IProgressMonitor monitor) { + try { + int openablesLength = openables.length; + CompilationUnitDeclaration[] parsedUnits = new CompilationUnitDeclaration[openablesLength]; + boolean[] hasLocalType = new boolean[openablesLength]; + org.eclipse.wst.jsdt.core.IJavaScriptUnit[] cus = new org.eclipse.wst.jsdt.core.IJavaScriptUnit[openablesLength]; + int unitsIndex = 0; + + CompilationUnitDeclaration focusUnit = null; + ReferenceBinding focusBinaryBinding = null; + IType focus = this.builder.getType(); + Openable focusOpenable = null; + if (focus != null) { + if (focus.isBinary()) { + focusOpenable = (Openable) focus.getClassFile(); + } + else { + focusOpenable = (Openable) focus.getJavaScriptUnit(); + } + } + + processedUnits = new HashSet(); + // build type bindings + Parser parser = new Parser(this.lookupEnvironment.problemReporter, true); + for (int i = 0; i < openablesLength; i++) { + Openable openable = openables[i]; + if (openable instanceof org.eclipse.wst.jsdt.core.IJavaScriptUnit) { + org.eclipse.wst.jsdt.core.IJavaScriptUnit cu = (org.eclipse.wst.jsdt.core.IJavaScriptUnit) openable; + + // contains a potential subtype as a local or anonymous type? + boolean containsLocalType = false; + + // case of hierarchy on region + if (localTypes == null) { + containsLocalType = true; + } + else { + IPath path = cu.getPath(); + containsLocalType = localTypes.contains(path.toString()); + } + + // build parsed unit + CompilationUnitDeclaration parsedUnit = null; + if (cu.isOpen()) { + // create parsed unit from source element infos + CompilationResult result = new CompilationResult(((ICompilationUnit) cu).getFileName(), ((ICompilationUnit) cu).getPackageName(), i, openablesLength, this.options.maxProblemsPerUnit); + SourceTypeElementInfo[] typeInfos = null; + try { + IType[] topLevelTypes = cu.getTypes(); + int topLevelLength = topLevelTypes.length; + + // empty cu: no need to parse (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=65677) + if (topLevelLength == 0) { + unitsIndex++; + continue; + } + typeInfos = new SourceTypeElementInfo[topLevelLength]; + for (int j = 0; j < topLevelLength; j++) { + IType topLevelType = topLevelTypes[j]; + typeInfos[j] = (SourceTypeElementInfo) ((JavaElement) topLevelType).getElementInfo(); + } + } + catch (JavaScriptModelException e) { + // types/cu exist since cu is opened + } + int flags = !containsLocalType ?SourceTypeConverter.MEMBER_TYPE : SourceTypeConverter.FIELD_AND_METHOD | SourceTypeConverter.MEMBER_TYPE | SourceTypeConverter.LOCAL_TYPE; + parsedUnit = SourceTypeConverter.buildCompilationUnit(typeInfos, flags, this.lookupEnvironment.problemReporter, result); + if (containsLocalType) { + parsedUnit.bits |= ASTNode.HasAllMethodBodies; + } + } + else { + // create parsed unit from file + IFile file = (IFile) cu.getResource(); + ICompilationUnit sourceUnit = this.builder.createCompilationUnitFromPath(openable, file); + + CompilationResult unitResult = new CompilationResult(sourceUnit, i, openablesLength, this.options.maxProblemsPerUnit); + parsedUnit = parser.dietParse(sourceUnit, unitResult); + } + + if (parsedUnit != null) { + parser.inferTypes(parsedUnit, this.options); + hasLocalType[unitsIndex] = containsLocalType; + cus[unitsIndex] = cu; + parsedUnits[unitsIndex++] = parsedUnit; + try { + if (!processedUnits.contains(openable)) { + this.lookupEnvironment.buildTypeBindings(parsedUnit, null); + } + + processedUnits.add(openable); + if (openable.equals(focusOpenable)) { + focusUnit = parsedUnit; + } + } + catch (AbortCompilation e) { + // classpath problem for this type: ignore + } + } + } + else { + // cache binary type binding + ClassFile classFile = (ClassFile) openable; + org.eclipse.wst.jsdt.internal.compiler.batch.CompilationUnit sourceUnit = new org.eclipse.wst.jsdt.internal.compiler.batch.CompilationUnit(null, new String(classFile.getFileName()), this.options.defaultEncoding); + + CompilationResult unitResult = new CompilationResult(sourceUnit, i, openablesLength, this.options.maxProblemsPerUnit); + CompilationUnitDeclaration parsedUnit = parser.dietParse(sourceUnit, unitResult); + if (parsedUnit != null) { + parser.inferTypes(parsedUnit, this.options); + hasLocalType[unitsIndex] = true; + cus[unitsIndex] = null; + parsedUnits[unitsIndex++] = parsedUnit; + try { + this.lookupEnvironment.buildTypeBindings(parsedUnit, null); + if (openable.equals(focusOpenable)) { + focusUnit = parsedUnit; + } + } + catch (AbortCompilation e) { + // classpath problem for this type: ignore + } + } + } + } + + for (int i = 0; i <= this.typeIndex; i++) { + IGenericType suppliedType = this.typeModels[i]; + if (suppliedType != null && suppliedType.isBinaryType()) { + // fault in its hierarchy... + try { + ReferenceBinding typeBinding = this.typeBindings[i]; + typeBinding.getSuperBinding(); + } + catch (AbortCompilation e) { + // classpath problem for this type: ignore + } + } + } + + // complete type bindings (ie. connect super types) + for (int i = 0; i < unitsIndex; i++) { + CompilationUnitDeclaration parsedUnit = parsedUnits[i]; + if (parsedUnit != null) { + try { + boolean containsLocalType = hasLocalType[i]; + + // NB: no-op if method bodies have been already parsed + if (containsLocalType) { + parser.getMethodBodies(parsedUnit); + } + /* complete type bindings and build fields and methods only for local types + * (in this case the constructor is needed when resolving local types) + * (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=145333) */ + this.lookupEnvironment.completeTypeBindings(parsedUnit, containsLocalType); + } + catch (AbortCompilation e) { + /* classpath problem for this type: don't try to + * resolve (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=49809) */ + hasLocalType[i] = false; + } + } + worked(monitor, 1); + } + + // remember type bindings + for (int i = 0; i < unitsIndex; i++) { + CompilationUnitDeclaration parsedUnit = parsedUnits[i]; + if (parsedUnit != null) { + boolean containsLocalType = hasLocalType[i]; + if (containsLocalType) { + // parsedUnit.scope.faultInTypes(); + // parsedUnit.resolve(); + } + + rememberAllTypes(parsedUnit, openables[i], containsLocalType); + } + } + + /* if no potential subtype was a real subtype of the binary focus type, no need to go further + * (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=54043) */ + if (focus != null && focus.isBinary()) { + char[] typeName = focus.getElementName().toCharArray(); + char[] pkgName = focus.getPackageFragment().getElementName().toCharArray(); + char[][] qualifiedName = new char[][]{pkgName, typeName}; + focusBinaryBinding = this.lookupEnvironment.getCachedType(qualifiedName); + if (focusBinaryBinding == null) { + qualifiedName = new char[][]{typeName}; + focusBinaryBinding = this.lookupEnvironment.getCachedType(qualifiedName); + } + + if (focusBinaryBinding == null) { + return; + } + } + + reportHierarchy(focus, focusUnit, focusBinaryBinding); + } + catch (ClassCastException e) { + Logger.logException("Error while resolving hierarchy.", e); //$NON-NLS-1$ + } + catch (AbortCompilation e) { + // ignore this exception for now since it typically means we cannot find java.lang.Object + if (TypeHierarchy.DEBUG) { + Logger.logException("Error while resolving hierarchy.", e); //$NON-NLS-1$ + } + } + finally { + reset(); + } + } + + private void setEnvironment(LookupEnvironment lookupEnvironment, HierarchyBuilder builder) { + this.lookupEnvironment = lookupEnvironment; + this.builder = builder; + + this.typeIndex = -1; + this.typeModels = new IGenericType[5]; + this.typeBindings = new ReferenceBinding[5]; + } + + /** + *

      + * Set the focus type (ie. the type that this resolver is computing the + * hierarch for. Returns the binding of this focus type or null if it could + * not be found. + *

      + * + * @param compoundName + * @return + */ + public ReferenceBinding setFocusType(char[][] compoundName) { + if (compoundName == null || this.lookupEnvironment == null) { + return null; + } + + this.focusType = this.lookupEnvironment.getCachedType(compoundName); + if (this.focusType == null) { + this.focusType = this.lookupEnvironment.askForType(compoundName); + } + + if (this.focusType == null) { + char[][] singleName = {CharOperation.concatWith(compoundName, '.')}; + this.focusType = this.lookupEnvironment.getCachedType(singleName); + if (this.focusType == null) { + this.focusType = this.lookupEnvironment.askForType(singleName); + } + } + return this.focusType; + } + + public boolean subOrSuperOfFocus(ReferenceBinding typeBinding) { + if (this.focusType == null) { + // accept all types (case of hierarchy in a region) + return true; + } + + try { + //check if given is the same as focus + if(this.focusType.isEquivalentTo(typeBinding)) { + return true; + } + + //check if given is a sub type of the focus + if (!this.superTypesOnly && this.focusType.isSuperclassOf(typeBinding)) { + return true; + } + + //check if given is a super of the focus + if (typeBinding.isSuperclassOf(this.focusType)) { + return true; + } + } + catch (AbortCompilation e) { + // unresolved superclass -> ignore + } + + return false; + } + + protected void worked(IProgressMonitor monitor, int work) { + if (monitor != null) { + if (monitor.isCanceled()) { + throw new OperationCanceledException(); + } + else { + monitor.worked(work); + } + } + } + + public CompilationUnitDeclaration doParse(ICompilationUnit sourceUnit, AccessRestriction accessRestriction) { + Parser parser = new Parser(this.lookupEnvironment.problemReporter, true); + CompilationResult unitResult = new CompilationResult(sourceUnit, 1, 1, this.options.maxProblemsPerUnit); + CompilationUnitDeclaration declaration = parser.dietParse(sourceUnit, unitResult); + parser.inferTypes(declaration, this.options); + return declaration; + } +} \ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/IndexBasedHierarchyBuilder.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/IndexBasedHierarchyBuilder.java index 4c7f56b8..16e4760f 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/IndexBasedHierarchyBuilder.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/IndexBasedHierarchyBuilder.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -21,6 +21,7 @@ import java.util.Map; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.wst.jsdt.core.IJavaScriptElement; import org.eclipse.wst.jsdt.core.IJavaScriptProject; @@ -31,8 +32,10 @@ import org.eclipse.wst.jsdt.core.JavaScriptModelException; import org.eclipse.wst.jsdt.core.compiler.CharOperation; import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants; import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope; +import org.eclipse.wst.jsdt.core.search.SearchEngine; import org.eclipse.wst.jsdt.core.search.SearchParticipant; import org.eclipse.wst.jsdt.core.search.SearchPattern; +import org.eclipse.wst.jsdt.internal.compiler.env.AccessRestriction; import org.eclipse.wst.jsdt.internal.compiler.env.AccessRuleSet; import org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit; import org.eclipse.wst.jsdt.internal.compiler.problem.DefaultProblemFactory; @@ -46,23 +49,28 @@ import org.eclipse.wst.jsdt.internal.core.Member; import org.eclipse.wst.jsdt.internal.core.Openable; import org.eclipse.wst.jsdt.internal.core.PackageFragment; import org.eclipse.wst.jsdt.internal.core.SearchableEnvironment; +import org.eclipse.wst.jsdt.internal.core.search.BasicSearchEngine; +import org.eclipse.wst.jsdt.internal.core.search.IRestrictedAccessTypeRequestor; import org.eclipse.wst.jsdt.internal.core.search.IndexQueryRequestor; import org.eclipse.wst.jsdt.internal.core.search.JavaSearchParticipant; +import org.eclipse.wst.jsdt.internal.core.search.PatternSearchJob; import org.eclipse.wst.jsdt.internal.core.search.SubTypeSearchJob; import org.eclipse.wst.jsdt.internal.core.search.indexing.IIndexConstants; import org.eclipse.wst.jsdt.internal.core.search.indexing.IndexManager; import org.eclipse.wst.jsdt.internal.core.search.matching.MatchLocator; import org.eclipse.wst.jsdt.internal.core.search.matching.SuperTypeReferencePattern; +import org.eclipse.wst.jsdt.internal.core.search.matching.TypeDeclarationPattern; import org.eclipse.wst.jsdt.internal.core.util.HandleFactory; import org.eclipse.wst.jsdt.internal.core.util.Util; public class IndexBasedHierarchyBuilder extends HierarchyBuilder implements SuffixConstants { - public static final int MAXTICKS = 800; // heuristic so that there still progress for deep hierachies + /** heuristic so that there still progress for deep hierarchies */ + public static final int MAXTICKS = 800; + /** - * A temporary cache of compilation units to handles to speed info - * to handle translation - it only contains the entries - * for the types in the region (in other words, it contains no supertypes outside - * the region). + * A temporary cache of compilation units to handles to speed info to + * handle translation - it only contains the entries for the types in the + * region (in other words, it contains no supertypes outside the region). */ protected Map cuToHandle; @@ -71,11 +79,6 @@ public class IndexBasedHierarchyBuilder extends HierarchyBuilder implements Suff */ protected IJavaScriptSearchScope scope; - /** - * Cache used to record binaries recreated from index matches - */ - protected Map binariesFromIndexMatches; - /** * Collection used to queue subtype index queries */ @@ -83,448 +86,589 @@ public class IndexBasedHierarchyBuilder extends HierarchyBuilder implements Suff public char[][] names = new char[10][]; public int start = 0; public int end = -1; - public void add(char[] name){ - if (++this.end == this.names.length){ + + public void add(char[] name) { + if (++this.end == this.names.length) { this.end -= this.start; - System.arraycopy(this.names, this.start, this.names = new char[this.end*2][], 0, this.end); + System.arraycopy(this.names, this.start, this.names = new char[this.end * 2][], 0, this.end); this.start = 0; } this.names[this.end] = name; } - public char[] retrieve(){ - if (this.start > this.end) return null; // none + + public char[] retrieve() { + if (this.start > this.end) { + return null; // none + } char[] name = this.names[this.start++]; - if (this.start > this.end){ + if (this.start > this.end) { this.start = 0; this.end = -1; } return name; } - public String toString(){ + + /** + *

      + * Determines if the queue contains the given needle. + *

      + * + * @param needle + * determine if this needle is in the queue + * @return true if the given needle is in the queue, + * false otherwise + */ + public boolean contains(char[] needle) { + boolean contains = false; + + if(this.start <= this.end) { + for(int i = this.start; i <= this.end && !contains; ++i) { + contains = CharOperation.equals(needle, this.names[i]); + } + } + + return contains; + } + + public String toString() { StringBuffer buffer = new StringBuffer("Queue:\n"); //$NON-NLS-1$ - for (int i = this.start; i <= this.end; i++){ + for (int i = this.start; i <= this.end; i++) { buffer.append(this.names[i]).append('\n'); } return buffer.toString(); } } -public IndexBasedHierarchyBuilder(TypeHierarchy hierarchy, IJavaScriptSearchScope scope) throws JavaScriptModelException { - super(hierarchy); - this.cuToHandle = new HashMap(5); - this.binariesFromIndexMatches = new HashMap(10); - this.scope = scope; -} -public void build(boolean computeSubtypes) { - JavaModelManager manager = JavaModelManager.getJavaModelManager(); - try { - // optimize access to zip files while building hierarchy - manager.cacheZipFiles(); - - if (computeSubtypes) { - // Note by construction there always is a focus type here - IType focusType = getType(); - boolean focusIsObject = focusType.getElementName().equals(new String(IIndexConstants.OBJECT)); - int amountOfWorkForSubtypes = focusIsObject ? 5 : 80; // percentage of work needed to get possible subtypes - IProgressMonitor possibleSubtypesMonitor = - this.hierarchy.progressMonitor == null ? - null : - new SubProgressMonitor(this.hierarchy.progressMonitor, amountOfWorkForSubtypes); - HashSet localTypes = new HashSet(10); // contains the paths that have potential subtypes that are local/anonymous types - String[] allPossibleSubtypes; - if (((Member)focusType).getOuterMostLocalContext() == null) { - // top level or member type - allPossibleSubtypes = this.determinePossibleSubTypes(localTypes, possibleSubtypesMonitor); - } else { - // local or anonymous type - allPossibleSubtypes = CharOperation.NO_STRINGS; + + public IndexBasedHierarchyBuilder(TypeHierarchy hierarchy, IJavaScriptSearchScope scope) throws JavaScriptModelException { + super(hierarchy); + this.cuToHandle = new HashMap(5); + this.scope = scope; + } + + public void build(boolean computeSubtypes) { + JavaModelManager manager = JavaModelManager.getJavaModelManager(); + try { + // optimize access to zip files while building hierarchy + manager.cacheZipFiles(); + + if (computeSubtypes) { + // Note by construction there always is a focus type here + IType focusType = getType(); + boolean focusIsObject = focusType.getElementName().equals(new String(IIndexConstants.OBJECT)); + + // percentage of work needed to get possible subtypes + int amountOfWorkForSubtypes = focusIsObject ? 5 : 80; + IProgressMonitor possibleSubtypesMonitor = this.hierarchy.progressMonitor == null ? null : new SubProgressMonitor(this.hierarchy.progressMonitor, amountOfWorkForSubtypes); + + String[] allPossibleSubtypesPaths; + if (((Member) focusType).getOuterMostLocalContext() == null) { + // top level or member type + allPossibleSubtypesPaths = this.determinePossibleSubTypesFilePaths(possibleSubtypesMonitor); + } + else { + // local or anonymous type + allPossibleSubtypesPaths = CharOperation.NO_STRINGS; + } + + if (allPossibleSubtypesPaths != null) { + IProgressMonitor buildMonitor = this.hierarchy.progressMonitor == null ? null : new SubProgressMonitor(this.hierarchy.progressMonitor, 100 - amountOfWorkForSubtypes); + this.hierarchy.initialize(allPossibleSubtypesPaths.length); + this.buildFromPotentialSubtypeFilepaths(allPossibleSubtypesPaths, new HashSet(10), buildMonitor); + } } - if (allPossibleSubtypes != null) { - IProgressMonitor buildMonitor = - this.hierarchy.progressMonitor == null ? - null : - new SubProgressMonitor(this.hierarchy.progressMonitor, 100 - amountOfWorkForSubtypes); - this.hierarchy.initialize(allPossibleSubtypes.length); - buildFromPotentialSubtypes(allPossibleSubtypes, localTypes, buildMonitor); + else { + this.hierarchy.initialize(1); + this.buildSupertypes(); } - } else { - this.hierarchy.initialize(1); - this.buildSupertypes(); } - } finally { - manager.flushZipFiles(); - } -} -private void buildForProject(JavaProject project, ArrayList potentialSubtypes, org.eclipse.wst.jsdt.core.IJavaScriptUnit[] workingCopies, HashSet localTypes, IProgressMonitor monitor) throws JavaScriptModelException { - // resolve - int openablesLength = potentialSubtypes.size(); - if (openablesLength > 0) { - // copy vectors into arrays - Openable[] openables = new Openable[openablesLength]; - potentialSubtypes.toArray(openables); - - // sort in the order of roots and in reverse alphabetical order for .class file - // since requesting top level types in the process of caching an enclosing type is - // not supported by the lookup environment - IPackageFragmentRoot[] roots = project.getPackageFragmentRoots(); - int rootsLength = roots.length; - final HashtableOfObjectToInt indexes = new HashtableOfObjectToInt(openablesLength); - for (int i = 0; i < openablesLength; i++) { - IJavaScriptElement root = openables[i].getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT); - int index; - for (index = 0; index < rootsLength; index++) { - if (roots[index].equals(root)) - break; - } - indexes.put(openables[i], index); + finally { + manager.flushZipFiles(); } - Arrays.sort(openables, new Comparator() { - public int compare(Object a, Object b) { - int aIndex = indexes.get(a); - int bIndex = indexes.get(b); - if (aIndex != bIndex) - return aIndex - bIndex; - return ((Openable) b).getElementName().compareTo(((Openable) a).getElementName()); + } + + private void buildForProject(JavaProject project, ArrayList potentialSubtypes, org.eclipse.wst.jsdt.core.IJavaScriptUnit[] workingCopies, HashSet localTypes, IProgressMonitor monitor) throws JavaScriptModelException { + // resolve + int openablesLength = potentialSubtypes.size(); + if (openablesLength > 0) { + // copy vectors into arrays + Openable[] openables = new Openable[openablesLength]; + potentialSubtypes.toArray(openables); + + /* sort in the order of roots and in reverse alphabetical order for .class file + * since requesting top level types in the process of caching an enclosing type is */ + // not supported by the lookup environment + IPackageFragmentRoot[] roots = project.getPackageFragmentRoots(); + int rootsLength = roots.length; + final HashtableOfObjectToInt indexes = new HashtableOfObjectToInt(openablesLength); + for (int i = 0; i < openablesLength; i++) { + IJavaScriptElement root = openables[i].getAncestor(IJavaScriptElement.PACKAGE_FRAGMENT_ROOT); + int index; + for (index = 0; index < rootsLength; index++) { + if (roots[index].equals(root)) { + break; + } + } + indexes.put(openables[i], index); } - }); + Arrays.sort(openables, new Comparator() { + public int compare(Object a, Object b) { + int aIndex = indexes.get(a); + int bIndex = indexes.get(b); + if (aIndex != bIndex) { + return aIndex - bIndex; + } + return ((Openable) b).getElementName().compareTo(((Openable) a).getElementName()); + } + }); - IType focusType = this.getType(); - boolean inProjectOfFocusType = focusType != null && focusType.getJavaScriptProject().equals(project); - org.eclipse.wst.jsdt.core.IJavaScriptUnit[] unitsToLookInside = null; - if (inProjectOfFocusType) { - org.eclipse.wst.jsdt.core.IJavaScriptUnit unitToLookInside = focusType.getJavaScriptUnit(); - if (unitToLookInside != null) { - int wcLength = workingCopies == null ? 0 : workingCopies.length; - if (wcLength == 0) { - unitsToLookInside = new org.eclipse.wst.jsdt.core.IJavaScriptUnit[] {unitToLookInside}; - } else { - unitsToLookInside = new org.eclipse.wst.jsdt.core.IJavaScriptUnit[wcLength+1]; - unitsToLookInside[0] = unitToLookInside; - System.arraycopy(workingCopies, 0, unitsToLookInside, 1, wcLength); + IType focusType = this.getType(); + boolean inProjectOfFocusType = focusType != null && focusType.getJavaScriptProject().equals(project); + org.eclipse.wst.jsdt.core.IJavaScriptUnit[] unitsToLookInside = null; + if (inProjectOfFocusType) { + org.eclipse.wst.jsdt.core.IJavaScriptUnit unitToLookInside = focusType.getJavaScriptUnit(); + if (unitToLookInside != null) { + int wcLength = workingCopies == null ? 0 : workingCopies.length; + if (wcLength == 0) { + unitsToLookInside = new org.eclipse.wst.jsdt.core.IJavaScriptUnit[]{unitToLookInside}; + } + else { + unitsToLookInside = new org.eclipse.wst.jsdt.core.IJavaScriptUnit[wcLength + 1]; + unitsToLookInside[0] = unitToLookInside; + System.arraycopy(workingCopies, 0, unitsToLookInside, 1, wcLength); + } + } + else { + unitsToLookInside = workingCopies; } - } else { - unitsToLookInside = workingCopies; } - } - SearchableEnvironment searchableEnvironment = project.newSearchableNameEnvironment(unitsToLookInside); - this.nameLookup = searchableEnvironment.nameLookup; - Map options = project.getOptions(true); - // disable task tags to speed up parsing - options.put(JavaScriptCore.COMPILER_TASK_TAGS, ""); //$NON-NLS-1$ - this.hierarchyResolver = - new HierarchyResolver(searchableEnvironment, options, this, new DefaultProblemFactory()); - if (focusType != null) { - Member declaringMember = ((Member)focusType).getOuterMostLocalContext(); - if (declaringMember == null) { - // top level or member type - if (!inProjectOfFocusType) { - char[] typeQualifiedName = focusType.getTypeQualifiedName('.').toCharArray(); - String[] packageName = ((PackageFragment) focusType.getPackageFragment()).names; - if (searchableEnvironment.findType(typeQualifiedName, Util.toCharArrays(packageName),this.hierarchyResolver) == null) { - // focus type is not visible in this project: no need to go further - return; + SearchableEnvironment searchableEnvironment = project.newSearchableNameEnvironment(unitsToLookInside); + this.nameLookup = searchableEnvironment.nameLookup; + Map options = project.getOptions(true); + // disable task tags to speed up parsing + options.put(JavaScriptCore.COMPILER_TASK_TAGS, ""); //$NON-NLS-1$ + this.hierarchyResolver = new HierarchyResolver(searchableEnvironment, options, this, new DefaultProblemFactory()); + if (focusType != null) { + Member declaringMember = ((Member) focusType).getOuterMostLocalContext(); + if (declaringMember == null) { + // top level or member type + if (!inProjectOfFocusType) { + char[] typeQualifiedName = focusType.getTypeQualifiedName('.').toCharArray(); + String[] packageName = ((PackageFragment) focusType.getPackageFragment()).names; + if (searchableEnvironment.findType(typeQualifiedName, Util.toCharArrays(packageName), this.hierarchyResolver) == null) { + // focus type is not visible in this project: no need to go further + return; + } } } - } else { - // local or anonymous type - Openable openable; - if (declaringMember.isBinary()) { - openable = (Openable)declaringMember.getClassFile(); - } else { - openable = (Openable)declaringMember.getJavaScriptUnit(); + else { + // local or anonymous type + Openable openable; + if (declaringMember.isBinary()) { + openable = (Openable) declaringMember.getClassFile(); + } + else { + openable = (Openable) declaringMember.getJavaScriptUnit(); + } + localTypes = new HashSet(); + localTypes.add(openable.getPath().toString()); + this.hierarchyResolver.resolve(new Openable[]{openable}, localTypes, monitor); + return; } - localTypes = new HashSet(); - localTypes.add(openable.getPath().toString()); - this.hierarchyResolver.resolve(new Openable[] {openable}, localTypes, monitor); - return; } + this.hierarchyResolver.resolve(openables, localTypes, monitor); } - this.hierarchyResolver.resolve(openables, localTypes, monitor); } -} -/** - * Configure this type hierarchy based on the given potential subtypes. - */ -private void buildFromPotentialSubtypes(String[] allPotentialSubTypes, HashSet localTypes, IProgressMonitor monitor) { - IType focusType = this.getType(); - - // substitute compilation units with working copies - HashMap wcPaths = new HashMap(); // a map from path to working copies - int wcLength; - org.eclipse.wst.jsdt.core.IJavaScriptUnit[] workingCopies = this.hierarchy.workingCopies; - if (workingCopies != null && (wcLength = workingCopies.length) > 0) { - String[] newPaths = new String[wcLength]; - for (int i = 0; i < wcLength; i++) { - org.eclipse.wst.jsdt.core.IJavaScriptUnit workingCopy = workingCopies[i]; - String path = workingCopy.getPath().toString(); - wcPaths.put(path, workingCopy); - newPaths[i] = path; + + /** + * Configure this type hierarchy based on the given potential subtypes. + */ + private void buildFromPotentialSubtypeFilepaths(String[] allPotentialSubTypeFilePaths, HashSet localTypes, IProgressMonitor monitor) { + IType focusType = this.getType(); + + // substitute compilation units with working copies + HashMap wcPaths = new HashMap(); // a map from path to working copies + int wcLength; + org.eclipse.wst.jsdt.core.IJavaScriptUnit[] workingCopies = this.hierarchy.workingCopies; + if (workingCopies != null && (wcLength = workingCopies.length) > 0) { + String[] newPaths = new String[wcLength]; + for (int i = 0; i < wcLength; i++) { + org.eclipse.wst.jsdt.core.IJavaScriptUnit workingCopy = workingCopies[i]; + String path = workingCopy.getPath().toString(); + wcPaths.put(path, workingCopy); + newPaths[i] = path; + } + int potentialSubtypesLength = allPotentialSubTypeFilePaths.length; + System.arraycopy(allPotentialSubTypeFilePaths, 0, allPotentialSubTypeFilePaths = new String[potentialSubtypesLength + wcLength], 0, potentialSubtypesLength); + System.arraycopy(newPaths, 0, allPotentialSubTypeFilePaths, potentialSubtypesLength, wcLength); } - int potentialSubtypesLength = allPotentialSubTypes.length; - System.arraycopy(allPotentialSubTypes, 0, allPotentialSubTypes = new String[potentialSubtypesLength+wcLength], 0, potentialSubtypesLength); - System.arraycopy(newPaths, 0, allPotentialSubTypes, potentialSubtypesLength, wcLength); - } - int length = allPotentialSubTypes.length; - - // inject the compilation unit of the focus type (so that types in - // this cu have special visibility permission (this is also usefull - // when the cu is a working copy) - Openable focusCU = (Openable)focusType.getJavaScriptUnit(); - String focusPath = null; - if (focusCU != null) { - focusPath = focusCU.getPath().toString(); - if (length > 0) { - System.arraycopy(allPotentialSubTypes, 0, allPotentialSubTypes = new String[length+1], 0, length); - allPotentialSubTypes[length] = focusPath; - } else { - allPotentialSubTypes = new String[] {focusPath}; + int length = allPotentialSubTypeFilePaths.length; + + /* inject the compilation unit of the focus type (so that types in + * this cu have special visibility permission (this is also usefull + * when the cu is a working copy) */ + Openable focusCU = (Openable) focusType.getJavaScriptUnit(); + String focusPath = null; + if (focusCU != null) { + focusPath = focusCU.getPath().toString(); + if (length > 0) { + System.arraycopy(allPotentialSubTypeFilePaths, 0, allPotentialSubTypeFilePaths = new String[length + 1], 0, length); + allPotentialSubTypeFilePaths[length] = focusPath; + } + else { + allPotentialSubTypeFilePaths = new String[]{focusPath}; + } + length++; } - length++; - } - /* - * Sort in alphabetical order so that potential subtypes are grouped per project - */ - Arrays.sort(allPotentialSubTypes); - - ArrayList potentialSubtypes = new ArrayList(); - try { - // create element infos for subtypes - HandleFactory factory = new HandleFactory(); - IJavaScriptProject currentProject = null; - if (monitor != null) monitor.beginTask("", length*2 /* 1 for build binding, 1 for connect hierarchy*/); //$NON-NLS-1$ - for (int i = 0; i < length; i++) { - try { - String resourcePath = allPotentialSubTypes[i]; + // Sort in alphabetical order so that potential subtypes are grouped per project + Arrays.sort(allPotentialSubTypeFilePaths); - // skip duplicate paths (e.g. if focus path was injected when it was already a potential subtype) - if (i > 0 && resourcePath.equals(allPotentialSubTypes[i-1])) continue; + ArrayList potentialSubtypes = new ArrayList(); + try { + // create element infos for subtypes + HandleFactory factory = new HandleFactory(); + IJavaScriptProject currentProject = null; + if (monitor != null) + monitor.beginTask("", length * 2 /* 1 for build binding, 1 for connect hierarchy*/); //$NON-NLS-1$ + for (int i = 0; i < length; i++) { + try { + String resourcePath = allPotentialSubTypeFilePaths[i]; + + /* skip duplicate paths (e.g. if focus path was injected + * when it was already a potential subtype) */ + if (i > 0 && resourcePath.equals(allPotentialSubTypeFilePaths[i - 1])) { + continue; + } - Openable handle; - org.eclipse.wst.jsdt.core.IJavaScriptUnit workingCopy = (org.eclipse.wst.jsdt.core.IJavaScriptUnit)wcPaths.get(resourcePath); - if (workingCopy != null) { - handle = (Openable)workingCopy; - } else { - handle = - resourcePath.equals(focusPath) ? - focusCU : - factory.createOpenable(resourcePath, this.scope); - if (handle == null) continue; // match is outside classpath + Openable handle; + org.eclipse.wst.jsdt.core.IJavaScriptUnit workingCopy = (org.eclipse.wst.jsdt.core.IJavaScriptUnit) wcPaths.get(resourcePath); + if (workingCopy != null) { + handle = (Openable) workingCopy; + } + else { + handle = resourcePath.equals(focusPath) ? focusCU : factory.createOpenable(resourcePath, this.scope); + if (handle == null) { + continue; // match is outside classpath + } + } + + IJavaScriptProject project = handle.getJavaScriptProject(); + if (currentProject == null) { + currentProject = project; + potentialSubtypes = new ArrayList(5); + } + else if (!currentProject.equals(project)) { + // build current project + this.buildForProject((JavaProject) currentProject, potentialSubtypes, workingCopies, localTypes, monitor); + currentProject = project; + potentialSubtypes = new ArrayList(5); + } + + potentialSubtypes.add(handle); } + catch (JavaScriptModelException e) { + continue; + } + } - IJavaScriptProject project = handle.getJavaScriptProject(); + // build last project + try { if (currentProject == null) { - currentProject = project; - potentialSubtypes = new ArrayList(5); - } else if (!currentProject.equals(project)) { - // build current project - this.buildForProject((JavaProject)currentProject, potentialSubtypes, workingCopies, localTypes, monitor); - currentProject = project; - potentialSubtypes = new ArrayList(5); + // case of no potential subtypes + currentProject = focusType.getJavaScriptProject(); + if (focusType.isBinary()) { + potentialSubtypes.add(focusType.getClassFile()); + } + else { + potentialSubtypes.add(focusType.getJavaScriptUnit()); + } } + this.buildForProject((JavaProject) currentProject, potentialSubtypes, workingCopies, localTypes, monitor); + } + catch (JavaScriptModelException e) { + // ignore + } - potentialSubtypes.add(handle); - } catch (JavaScriptModelException e) { - continue; + // Add focus if not already in (case of a type with no explicit super type) + if (!this.hierarchy.contains(focusType)) { + this.hierarchy.addRootClass(focusType); } } + finally { + if (monitor != null) + monitor.done(); + } + } + + protected ICompilationUnit createCompilationUnitFromPath(Openable handle, IFile file) { + ICompilationUnit unit = super.createCompilationUnitFromPath(handle, file); + this.cuToHandle.put(unit, handle); + return unit; + } + + /** + * @param monitor used to track progress and monitor cancellation + * + * @return file paths to all of the files containing subtypes of the current focus type. + */ + private String[] determinePossibleSubTypesFilePaths(IProgressMonitor monitor) { + final HashSet paths = new HashSet(10); + IPathRequestor collector = new IPathRequestor() { + public void acceptPath(String path, boolean containsLocalTypes) { + paths.add(path); + } + }; - // build last project try { - if (currentProject == null) { - // case of no potential subtypes - currentProject = focusType.getJavaScriptProject(); - if (focusType.isBinary()) { - potentialSubtypes.add(focusType.getClassFile()); - } else { - potentialSubtypes.add(focusType.getJavaScriptUnit()); - } + if (monitor != null) { + monitor.beginTask("", MAXTICKS); //$NON-NLS-1$ + } + searchAllPossibleSubTypes(this.getType(), this.scope, collector, IJavaScriptSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, monitor); + } + finally { + if (monitor != null) { + monitor.done(); } - this.buildForProject((JavaProject)currentProject, potentialSubtypes, workingCopies, localTypes, monitor); - } catch (JavaScriptModelException e) { - // ignore } - // Compute hierarchy of focus type if not already done (case of a type with potential subtypes that are not real subtypes) -// if (!this.hierarchy.contains(focusType)) { -// try { -// currentProject = focusType.getJavaScriptProject(); -// potentialSubtypes = new ArrayList(); -// if (focusType.isBinary()) { -// potentialSubtypes.add(focusType.getClassFile()); -// } else { -// potentialSubtypes.add(focusType.getJavaScriptUnit()); -// } -// this.buildForProject((JavaProject)currentProject, potentialSubtypes, workingCopies, localTypes, monitor); -// } catch (JavaScriptModelException e) { -// // ignore -// } -// } - - // Add focus if not already in (case of a type with no explicit super type) - if (!this.hierarchy.contains(focusType)) { - this.hierarchy.addRootClass(focusType); + int length = paths.size(); + String[] result = new String[length]; + int count = 0; + for (Iterator iter = paths.iterator(); iter.hasNext();) { + result[count++] = (String) iter.next(); } - } finally { - if (monitor != null) monitor.done(); + return result; } -} -protected ICompilationUnit createCompilationUnitFromPath(Openable handle, IFile file) { - ICompilationUnit unit = super.createCompilationUnitFromPath(handle, file); - this.cuToHandle.put(unit, handle); - return unit; -} -/** - * Returns all of the possible subtypes of this type hierarchy. - * Returns null if they could not be determine. - */ -private String[] determinePossibleSubTypes(final HashSet localTypes, IProgressMonitor monitor) { - - class PathCollector implements IPathRequestor { - HashSet paths = new HashSet(10); - public void acceptPath(String path, boolean containsLocalTypes) { - this.paths.add(path); - if (containsLocalTypes) { - localTypes.add(path); - } + /** + * Find the set of candidate subtypes of a given type. + * + * The requestor is notified of super type references (with actual path of + * its occurrence) for all types which are potentially involved inside a + * particular hierarchy. The match locator is not used here to narrow down + * the results, the type hierarchy resolver is rather used to compute the + * whole hierarchy at once. + * + * @param type + * @param scope + * @param pathRequestor + * @param waitingPolicy + * @param progressMonitor + */ + public static void searchAllPossibleSubTypes(IType type, IJavaScriptSearchScope scope, + final IPathRequestor pathRequestor, + int waitingPolicy, IProgressMonitor progressMonitor) { + + //set up monitor + final IProgressMonitor monitor; + if(progressMonitor == null) { + monitor = new NullProgressMonitor(); + } else { + monitor = progressMonitor; } - } - PathCollector collector = new PathCollector(); - - try { - if (monitor != null) monitor.beginTask("", MAXTICKS); //$NON-NLS-1$ - searchAllPossibleSubTypes( - this.getType(), - this.scope, - this.binariesFromIndexMatches, - collector, - IJavaScriptSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, - monitor); - } finally { - if (monitor != null) monitor.done(); - } - HashSet paths = collector.paths; - int length = paths.size(); - String[] result = new String[length]; - int count = 0; - for (Iterator iter = paths.iterator(); iter.hasNext();) { - result[count++] = (String) iter.next(); - } - return result; -} + // embed constructs inside arrays so as to pass them to (inner) collector + final Queue parentTypeNames = new Queue(); + final HashtableOfObject foundSuperNames = new HashtableOfObject(5); + + IndexManager indexManager = JavaModelManager.getJavaModelManager().getIndexManager(); + + // use a special collector to collect paths and queue new subtype names + IndexQueryRequestor subTypeSearchRequestor = new IndexQueryRequestor() { + /** + * @see org.eclipse.wst.jsdt.internal.core.search.IndexQueryRequestor#acceptIndexMatch(java.lang.String, org.eclipse.wst.jsdt.core.search.SearchPattern, org.eclipse.wst.jsdt.core.search.SearchParticipant, org.eclipse.wst.jsdt.internal.compiler.env.AccessRuleSet) + */ + public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant, AccessRuleSet access) { + SuperTypeReferencePattern record = (SuperTypeReferencePattern) indexRecord; + pathRequestor.acceptPath(documentPath, false); + char[] typeName = record.typeName; + + //add to list of type names to search for children for + if (!foundSuperNames.containsKey(typeName)) { + foundSuperNames.put(typeName, typeName); + parentTypeNames.add(typeName); + } + return true; + } + }; + + //create initial pattern + SuperTypeReferencePattern superTypeRefPattern = new SuperTypeReferencePattern(null, SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE); + MatchLocator.setFocus(superTypeRefPattern, type); + + //create the job used for searching for the sub types + SearchParticipant participant = new JavaSearchParticipant(); + SubTypeSearchJob subTypeSearchJob = new SubTypeSearchJob(superTypeRefPattern, participant, scope, subTypeSearchRequestor); + + //queue of parent type names + parentTypeNames.add(type.getElementName().toCharArray()); + + //monitor used just to track cancellation + IProgressMonitor cancelMonitor = new NullProgressMonitor() { + /** + *

      + * don't report progress since this is too costly for deep hierarchies + * just handle isCanceled() + *

      + * + * @see org.eclipse.core.runtime.NullProgressMonitor#setCanceled(boolean) + */ + public void setCanceled(boolean value) { + monitor.setCanceled(value); + } -/** - * Find the set of candidate subtypes of a given type. - * - * The requestor is notified of super type references (with actual path of - * its occurrence) for all types which are potentially involved inside a particular - * hierarchy. - * The match locator is not used here to narrow down the results, the type hierarchy - * resolver is rather used to compute the whole hierarchy at once. - * @param type - * @param scope - * @param binariesFromIndexMatches - * @param pathRequestor - * @param waitingPolicy - * @param progressMonitor - */ -public static void searchAllPossibleSubTypes( - IType type, - IJavaScriptSearchScope scope, - final Map binariesFromIndexMatches, - final IPathRequestor pathRequestor, - int waitingPolicy, // WaitUntilReadyToSearch | ForceImmediateSearch | CancelIfNotReadyToSearch - final IProgressMonitor progressMonitor) { - - /* embed constructs inside arrays so as to pass them to (inner) collector */ - final Queue queue = new Queue(); - final HashtableOfObject foundSuperNames = new HashtableOfObject(5); - - IndexManager indexManager = JavaModelManager.getJavaModelManager().getIndexManager(); - - /* use a special collector to collect paths and queue new subtype names */ - IndexQueryRequestor searchRequestor = new IndexQueryRequestor() { - public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant, AccessRuleSet access) { - SuperTypeReferencePattern record = (SuperTypeReferencePattern)indexRecord; - boolean isLocalOrAnonymous = record.enclosingTypeName == IIndexConstants.ONE_ZERO; - pathRequestor.acceptPath(documentPath, isLocalOrAnonymous); - char[] typeName = record.simpleName; - int suffix = documentPath.toLowerCase().lastIndexOf(SUFFIX_STRING_java); - if (suffix != -1){ - HierarchyBinaryType binaryType = (HierarchyBinaryType)binariesFromIndexMatches.get(documentPath); - if (binaryType == null){ - char[] enclosingTypeName = record.enclosingTypeName; - if (isLocalOrAnonymous) { - int lastSlash = documentPath.lastIndexOf('/'); - int lastDollar = documentPath.lastIndexOf('$'); - if (lastDollar == -1) { - // malformed local or anonymous type: it doesn't contain a $ in its name - // treat it as a top level type - enclosingTypeName = null; - typeName = documentPath.substring(lastSlash+1, suffix).toCharArray(); - } else { - enclosingTypeName = documentPath.substring(lastSlash+1, lastDollar).toCharArray(); - typeName = documentPath.substring(lastDollar+1, suffix).toCharArray(); + public boolean isCanceled() { + return monitor.isCanceled(); + } + }; + + try { + //while there are still parent type names to check and the progress monitor has not been canceled keep processing + int ticks = 0; + while (parentTypeNames.start <= parentTypeNames.end && !monitor.isCanceled()) { + // all subclasses of OBJECT are actually all types + char[] currentTypeName = parentTypeNames.retrieve(); + if (CharOperation.equals(currentTypeName, IIndexConstants.OBJECT)) { + currentTypeName = null; + } + + /* if current name then get all its synonyms then search for all of those synonyms children + * else in case, we search all sub-types, no need to search further */ + if(currentTypeName != null) { + //get all the synonyms, including self, to the current type name + char[][] synonyms = SearchEngine.getAllSynonyms(currentTypeName, scope, waitingPolicy, progressMonitor); + + //for each synonym search the index for sub types of that synonym + for(int i = 0; i < synonyms.length; ++i) { + char[] synonym = synonyms[i]; + + //search for synonym type in index so that it can be added to the hierarchy + indexManager.performConcurrentJob(new PatternSearchJob( + new TypeDeclarationPattern(synonym, SearchPattern.R_EXACT_MATCH), + participant, scope, + new IndexQueryRequestor() { + /** + * @see org.eclipse.wst.jsdt.internal.core.search.IndexQueryRequestor#acceptIndexMatch(java.lang.String, org.eclipse.wst.jsdt.core.search.SearchPattern, org.eclipse.wst.jsdt.core.search.SearchParticipant, org.eclipse.wst.jsdt.internal.compiler.env.AccessRuleSet) + */ + public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant, AccessRuleSet access) { + pathRequestor.acceptPath(documentPath, false); + + return true; + } + }), waitingPolicy, cancelMonitor); + + //perform super type pattern index search + superTypeRefPattern.superTypeName = synonym; + indexManager.performConcurrentJob(subTypeSearchJob, waitingPolicy, cancelMonitor); + + //track progress + if (++ticks <= MAXTICKS) { + monitor.worked(1); } } - binaryType = new HierarchyBinaryType(record.modifiers, record.pkgName, typeName, enclosingTypeName); - binariesFromIndexMatches.put(documentPath, binaryType); + } else { + break; } - binaryType.recordSuperType(record.superSimpleName, record.superQualification); - } - if (!isLocalOrAnonymous // local or anonymous types cannot have subtypes outside the cu that define them - && !foundSuperNames.containsKey(typeName)){ - foundSuperNames.put(typeName, typeName); - queue.add(typeName); } - return true; } - }; - - SuperTypeReferencePattern pattern = - new SuperTypeReferencePattern(null, null, SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE); - MatchLocator.setFocus(pattern, type); - SubTypeSearchJob job = new SubTypeSearchJob( - pattern, - new JavaSearchParticipant(), // java search only - scope, - searchRequestor); - - int ticks = 0; - queue.add(type.getElementName().toCharArray()); - try { - while (queue.start <= queue.end) { - if (progressMonitor != null && progressMonitor.isCanceled()) return; - - // all subclasses of OBJECT are actually all types - char[] currentTypeName = queue.retrieve(); - if (CharOperation.equals(currentTypeName, IIndexConstants.OBJECT)) - currentTypeName = null; - - // search all index references to a given supertype - pattern.superSimpleName = currentTypeName; - indexManager.performConcurrentJob(job, waitingPolicy, progressMonitor == null ? null : new NullProgressMonitor() { - // don't report progress since this is too costly for deep hierarchies - // just handle isCanceled() (seehttps://bugs.eclipse.org/bugs/show_bug.cgi?id=179511) - public void setCanceled(boolean value) { - progressMonitor.setCanceled(value); + finally { + //always end the job + subTypeSearchJob.finished(); + } + } + + public static ArrayList findAllSuperTypes(char[] typeName, IJavaScriptSearchScope scope) { + final ArrayList superTypes = new ArrayList(); + final ArrayList queue = new ArrayList(); + final ArrayList alreadySearched = new ArrayList(); + + try { + queue.add(CharOperation.toLowerCase(typeName)); + + IProgressMonitor progressMonitor = new IProgressMonitor() { + boolean isCanceled = false; + + public void beginTask(String name, int totalWork) { + // implements interface method + } + + public void done() { + // implements interface method + } + + public void internalWorked(double work) { + // implements interface method } + public boolean isCanceled() { - return progressMonitor.isCanceled(); + return isCanceled; + } + + public void setCanceled(boolean value) { + isCanceled = value; + } + + public void setTaskName(String name) { + // implements interface method + } + + public void subTask(String name) { + // implements interface method } - }); - if (progressMonitor != null && ++ticks <= MAXTICKS) - progressMonitor.worked(1); - // in case, we search all subtypes, no need to search further - if (currentTypeName == null) break; + public void worked(int work) { + // implements interface method + } + }; + IRestrictedAccessTypeRequestor typeRequestor = new IRestrictedAccessTypeRequestor() { + public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] superTypeNames, char[][] enclosingTypeNames, String path, AccessRestriction access) { + boolean doAdd = true; + for (int i = 0; i < superTypes.size(); i++) { + if (CharOperation.equals(superTypeNames[0], (char[]) superTypes.get(i))) { + doAdd = false; + break; + } + } + if (doAdd) { + superTypes.add(superTypeNames[0]); + } + queue.add(superTypeNames[0]); + } + }; + try { + while (!queue.isEmpty()) { + char[] nextSearch = (char[]) queue.get(0); + boolean doSearch = true; + if (CharOperation.equals(nextSearch, IIndexConstants.OBJECT)) { + doSearch = false; + } + + for (int i = 0; doSearch && i < alreadySearched.size(); i++) { + if (CharOperation.equals(nextSearch, (char[]) alreadySearched.get(i))) { + doSearch = false; + } + } + if (doSearch) { + alreadySearched.add(nextSearch); + // not case sensitive + new BasicSearchEngine().searchAllTypeNames(CharOperation.NO_CHAR, nextSearch, + SearchPattern.R_EXACT_MATCH, + scope, typeRequestor, IJavaScriptSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, + progressMonitor); + + } + queue.remove(0); + doSearch = true; + } + } + catch (OperationCanceledException e) { + } } - } finally { - job.finished(); + catch (JavaScriptModelException e) { + } + return superTypes; } } -} diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/RegionBasedTypeHierarchy.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/RegionBasedTypeHierarchy.java index 8400ba9a..a1f175cd 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/RegionBasedTypeHierarchy.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/RegionBasedTypeHierarchy.java @@ -133,7 +133,7 @@ private boolean pruneDeadBranches(IType type) { TypeVector subtypes = (TypeVector)this.typeToSubtypes.get(type); if (subtypes == null) return true; pruneDeadBranches(subtypes.copy().elements()); - subtypes = (TypeVector)this.typeToSubtypes.get(type); + subtypes = (TypeVector)this.typeToSubtypes.get(type.getDisplayName()); return (subtypes == null || subtypes.size == 0); } private void pruneDeadBranches(IType[] types) { @@ -150,7 +150,7 @@ private void pruneDeadBranches(IType[] types) { */ protected void removeType(IType type) { IType[] subtypes = this.getSubclasses(type); - this.typeToSubtypes.remove(type); + this.typeToSubtypes.remove(type.getDisplayName()); if (subtypes != null) { for (int i= 0; i < subtypes.length; i++) { this.removeType(subtypes[i]); @@ -158,7 +158,7 @@ protected void removeType(IType type) { } IType superclass = (IType)this.classToSuperclass.remove(type); if (superclass != null) { - TypeVector types = (TypeVector)this.typeToSubtypes.get(superclass); + TypeVector types = (TypeVector)this.typeToSubtypes.get(superclass.getDisplayName()); if (types != null) types.remove(type); } } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/TypeHierarchy.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/TypeHierarchy.java index e95bc9e2..4eb34dfc 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/TypeHierarchy.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/hierarchy/TypeHierarchy.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -15,9 +15,12 @@ import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; +import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; +import java.util.LinkedList; import java.util.Map; +import java.util.Set; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; @@ -82,14 +85,13 @@ public class TypeHierarchy implements ITypeHierarchy, IElementChangedListener { static final int SIZE = 10; /** - * The Java Project in which the hierarchy is being built - this - * provides the context for determining a classpath and namelookup rules. - * Possibly null. + * The Java Project in which the hierarchy is being built - this provides + * the context for determining a classpath and namelookup rules. Possibly + * null. */ protected IJavaScriptProject project; /** - * The type the hierarchy was specifically computed for, - * possibly null. + * The type the hierarchy was specifically computed for, possibly null. */ protected IType focusType; @@ -99,6 +101,10 @@ public class TypeHierarchy implements ITypeHierarchy, IElementChangedListener { protected IJavaScriptUnit[] workingCopies; protected Map classToSuperclass; + + /** + * <{@link String},{@link TypeVector}> + */ protected Map typeToSubtypes; protected Map typeFlags; protected TypeVector rootClasses = new TypeVector(); @@ -116,20 +122,20 @@ public class TypeHierarchy implements ITypeHierarchy, IElementChangedListener { */ protected ArrayList changeListeners = null; - /* + /** * A map from Openables to ArrayLists of ITypes */ public Map files = null; /** - * A region describing the packages considered by this - * hierarchy. Null if not activated. + * A region describing the packages considered by this hierarchy. Null if + * not activated. */ protected Region packageRegion = null; /** - * A region describing the projects considered by this - * hierarchy. Null if not activated. + * A region describing the projects considered by this hierarchy. Null if + * not activated. */ protected Region projectRegion = null; @@ -143,1078 +149,1132 @@ public class TypeHierarchy implements ITypeHierarchy, IElementChangedListener { */ IJavaScriptSearchScope scope; - /* + /** * Whether this hierarchy needs refresh */ public boolean needsRefresh = true; - /* + /** * Collects changes to types */ protected ChangeCollector changeCollector; -/** - * Creates an empty TypeHierarchy - */ -public TypeHierarchy() { - // Creates an empty TypeHierarchy -} -/** - * Creates a TypeHierarchy on the given type. - */ -public TypeHierarchy(IType type, IJavaScriptUnit[] workingCopies, IJavaScriptProject project, boolean computeSubtypes) { - this(type, workingCopies, SearchEngine.createJavaSearchScope(new IJavaScriptElement[] {project}), computeSubtypes); - this.project = project; -} -/** - * Creates a TypeHierarchy on the given type. - */ -public TypeHierarchy(IType type, IJavaScriptUnit[] workingCopies, IJavaScriptSearchScope scope, boolean computeSubtypes) { - this.focusType = type == null ? null : (IType) ((JavaElement) type).unresolved(); // unsure the focus type is unresolved (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=92357) - this.workingCopies = workingCopies; - this.computeSubtypes = computeSubtypes; - this.scope = scope; -} -/** - * Initializes the file, package and project regions - */ -protected void initializeRegions() { - - IType[] allTypes = getAllClasses(); - for (int i = 0; i < allTypes.length; i++) { - IType type = allTypes[i]; - Openable o = (Openable) ((JavaElement) type).getOpenableParent(); - if (o != null) { - ArrayList types = (ArrayList)this.files.get(o); - if (types == null) { - types = new ArrayList(); - this.files.put(o, types); + /** + * Creates an empty TypeHierarchy + */ + public TypeHierarchy() { + // Creates an empty TypeHierarchy + } + + /** + * Creates a TypeHierarchy on the given type. + */ + public TypeHierarchy(IType type, IJavaScriptUnit[] workingCopies, IJavaScriptProject project, boolean computeSubtypes) { + this(type, workingCopies, SearchEngine.createJavaSearchScope(new IJavaScriptElement[]{project}), computeSubtypes); + this.project = project; + } + + /** + * Creates a TypeHierarchy on the given type. + */ + public TypeHierarchy(IType type, IJavaScriptUnit[] workingCopies, IJavaScriptSearchScope scope, boolean computeSubtypes) { + this.focusType = type == null ? null : (IType) ((JavaElement) type).unresolved(); // unsure + this.workingCopies = workingCopies; + this.computeSubtypes = computeSubtypes; + this.scope = scope; + } + + /** + * Initializes the file, package and project regions + */ + protected void initializeRegions() { + + IType[] allTypes = getAllClasses(); + for (int i = 0; i < allTypes.length; i++) { + IType type = allTypes[i]; + Openable o = (Openable) ((JavaElement) type).getOpenableParent(); + if (o != null) { + ArrayList types = (ArrayList) this.files.get(o); + if (types == null) { + types = new ArrayList(); + this.files.put(o, types); + } + types.add(type); } - types.add(type); - } - IPackageFragment pkg = type.getPackageFragment(); - this.packageRegion.add(pkg); - IJavaScriptProject declaringProject = type.getJavaScriptProject(); - if (declaringProject != null) { - this.projectRegion.add(declaringProject); + IPackageFragment pkg = type.getPackageFragment(); + this.packageRegion.add(pkg); + IJavaScriptProject declaringProject = type.getJavaScriptProject(); + if (declaringProject != null) { + this.projectRegion.add(declaringProject); + } + checkCanceled(); } - checkCanceled(); } -} -/** - * Adds the type to the collection of root classes - * if the classes is not already present in the collection. - */ -protected void addRootClass(IType type) { - if (this.rootClasses.contains(type)) return; - this.rootClasses.add(type); -} -/** - * Adds the given subtype to the type. - */ -protected void addSubtype(IType type, IType subtype) { - TypeVector subtypes = (TypeVector)this.typeToSubtypes.get(type); - if (subtypes == null) { - subtypes = new TypeVector(); - this.typeToSubtypes.put(type, subtypes); + + /** + * Adds the type to the collection of root classes if the classes is not + * already present in the collection. + */ + protected void addRootClass(IType type) { + if (this.rootClasses.contains(type)) + return; + this.rootClasses.add(type); } - if (!subtypes.contains(subtype)) { - subtypes.add(subtype); + + /** + * Adds the given subtype to the type. + */ + protected void addSubtype(IType type, IType subtype) { + TypeVector subtypes = (TypeVector)this.typeToSubtypes.get(type.getDisplayName()); + if (subtypes == null) { + subtypes = new TypeVector(); + this.typeToSubtypes.put(type.getDisplayName(), subtypes); + } + if (!subtypes.contains(subtype)) { + subtypes.add(subtype); + } } -} -/** - * @see ITypeHierarchy - */ -public synchronized void addTypeHierarchyChangedListener(ITypeHierarchyChangedListener listener) { - ArrayList listeners = this.changeListeners; - if (listeners == null) { - this.changeListeners = listeners = new ArrayList(); + + /** + * @see ITypeHierarchy + */ + public synchronized void addTypeHierarchyChangedListener(ITypeHierarchyChangedListener listener) { + ArrayList listeners = this.changeListeners; + if (listeners == null) { + this.changeListeners = listeners = new ArrayList(); + } + + // register with JavaScriptCore to get Java element delta on first listener added + if (listeners.size() == 0) { + JavaScriptCore.addElementChangedListener(this); + } + + // add listener only if it is not already present + if (listeners.indexOf(listener) == -1) { + listeners.add(listener); + } } - // register with JavaScriptCore to get Java element delta on first listener added - if (listeners.size() == 0) { - JavaScriptCore.addElementChangedListener(this); + private static Integer bytesToFlags(byte[] bytes) { + if (bytes != null && bytes.length > 0) { + return new Integer(new String(bytes)); + } + else { + return null; + } } - // add listener only if it is not already present - if (listeners.indexOf(listener) == -1) { - listeners.add(listener); + /** + * cacheFlags. + */ + public void cacheFlags(IType type, int flags) { + this.typeFlags.put(type, new Integer(flags)); } -} -private static Integer bytesToFlags(byte[] bytes){ - if(bytes != null && bytes.length > 0) { - return new Integer(new String(bytes)); - } else { - return null; + + /** + * Caches the handle of the superclass for the specified type. As a side + * effect cache this type as a subtype of the superclass. + */ + protected void cacheSuperclass(IType type, IType superclass) { + if (superclass != null) { + this.classToSuperclass.put(type, superclass); + addSubtype(superclass, type); + } } -} -/** - * cacheFlags. - */ -public void cacheFlags(IType type, int flags) { - this.typeFlags.put(type, new Integer(flags)); -} -/** - * Caches the handle of the superclass for the specified type. - * As a side effect cache this type as a subtype of the superclass. - */ -protected void cacheSuperclass(IType type, IType superclass) { - if (superclass != null) { -//System.out.println(type.hashCode() +typehash(type)); - this.classToSuperclass.put(type, superclass); - addSubtype(superclass, type); + + /** + * Checks with the progress monitor to see whether the creation of the + * type hierarchy should be canceled. Should be regularly called so that + * the user can cancel. + * + * @exception OperationCanceledException + * if cancelling the operation has been requested + * @see IProgressMonitor#isCanceled + */ + protected void checkCanceled() { + if (this.progressMonitor != null && this.progressMonitor.isCanceled()) { + throw new OperationCanceledException(); + } } -} -/** - * Checks with the progress monitor to see whether the creation of the type hierarchy - * should be canceled. Should be regularly called - * so that the user can cancel. - * - * @exception OperationCanceledException if cancelling the operation has been requested - * @see IProgressMonitor#isCanceled - */ -protected void checkCanceled() { - if (this.progressMonitor != null && this.progressMonitor.isCanceled()) { - throw new OperationCanceledException(); + + /** + * Compute this type hierarchy. + */ + protected void compute() throws JavaScriptModelException, CoreException { + if (this.focusType != null) { + HierarchyBuilder builder = new IndexBasedHierarchyBuilder(this, this.scope); + builder.build(this.computeSubtypes); + } // else a RegionBasedTypeHierarchy should be used } -} -/** - * Compute this type hierarchy. - */ -protected void compute() throws JavaScriptModelException, CoreException { - if (this.focusType != null) { - HierarchyBuilder builder = - new IndexBasedHierarchyBuilder( - this, - this.scope); - builder.build(this.computeSubtypes); - } // else a RegionBasedTypeHierarchy should be used -} - -//private String typehash(IJavaScriptElement type) -//{ -// StringBuffer sb=new StringBuffer(); -// while (type !=null && type.getElementType()!=IJavaScriptElement.JAVASCRIPT_MODEL) -// { -// sb.append(type.getElementName()); -// sb.append(" - "); -// type=type.getParent(); -// } -// return sb.toString(); -//} -/** - * @see ITypeHierarchy - */ -public boolean contains(IType type) { - // classes -// System.out.println("CONTAINS "+typehash(type)); - if (this.classToSuperclass.get(type) != null) { - return true; + /** + * @see ITypeHierarchy + */ + public boolean contains(IType type) { + // classes + if (this.classToSuperclass.get(type) != null) { + return true; + } + + // root classes + if (this.rootClasses.contains(type)) + return true; + + return false; } - // root classes - if (this.rootClasses.contains(type)) return true; + /** + * Determines if the change effects this hierarchy, and fires change + * notification if required. + */ + public void elementChanged(ElementChangedEvent event) { + // type hierarchy change has already been fired + if (this.needsRefresh) + return; + + if (isAffected(event.getDelta())) { + this.needsRefresh = true; + fireChange(); + } + } - return false; -} -/** - * Determines if the change effects this hierarchy, and fires - * change notification if required. - */ -public void elementChanged(ElementChangedEvent event) { - // type hierarchy change has already been fired - if (this.needsRefresh) return; + /** + * @see ITypeHierarchy + */ + public boolean exists() { + if (!this.needsRefresh) + return true; - if (isAffected(event.getDelta())) { - this.needsRefresh = true; - fireChange(); + return (this.focusType == null || this.focusType.exists()) && this.javaProject().exists(); } -} -/** - * @see ITypeHierarchy - */ -public boolean exists() { - if (!this.needsRefresh) return true; - return (this.focusType == null || this.focusType.exists()) && this.javaProject().exists(); -} -/** - * Notifies listeners that this hierarchy has changed and needs - * refreshing. Note that listeners can be removed as we iterate - * through the list. - */ -public void fireChange() { - ArrayList listeners = this.changeListeners; - if (listeners == null) { - return; + /** + * Notifies listeners that this hierarchy has changed and needs + * refreshing. Note that listeners can be removed as we iterate through + * the list. + */ + public void fireChange() { + ArrayList listeners = this.changeListeners; + if (listeners == null) { + return; + } + if (DEBUG) { + System.out.println("FIRING hierarchy change [" + Thread.currentThread() + "]"); //$NON-NLS-1$ //$NON-NLS-2$ + if (this.focusType != null) { + System.out.println(" for hierarchy focused on " + ((JavaElement) this.focusType).toStringWithAncestors()); //$NON-NLS-1$ + } + } + // clone so that a listener cannot have a side-effect on this list when being notified + listeners = (ArrayList) listeners.clone(); + for (int i = 0; i < listeners.size(); i++) { + final ITypeHierarchyChangedListener listener = (ITypeHierarchyChangedListener) listeners.get(i); + SafeRunner.run(new ISafeRunnable() { + public void handleException(Throwable exception) { + Util.log(exception, "Exception occurred in listener of Type hierarchy change notification"); //$NON-NLS-1$ + } + + public void run() throws Exception { + listener.typeHierarchyChanged(TypeHierarchy.this); + } + }); + } } - if (DEBUG) { - System.out.println("FIRING hierarchy change ["+Thread.currentThread()+"]"); //$NON-NLS-1$ //$NON-NLS-2$ - if (this.focusType != null) { - System.out.println(" for hierarchy focused on " + ((JavaElement)this.focusType).toStringWithAncestors()); //$NON-NLS-1$ + + private static byte[] flagsToBytes(Integer flags) { + if (flags != null) { + return flags.toString().getBytes(); + } + else { + return NO_FLAGS; } } - // clone so that a listener cannot have a side-effect on this list when being notified - listeners = (ArrayList)listeners.clone(); - for (int i= 0; i < listeners.size(); i++) { - final ITypeHierarchyChangedListener listener= (ITypeHierarchyChangedListener)listeners.get(i); - SafeRunner.run(new ISafeRunnable() { - public void handleException(Throwable exception) { - Util.log(exception, "Exception occurred in listener of Type hierarchy change notification"); //$NON-NLS-1$ - } - public void run() throws Exception { - listener.typeHierarchyChanged(TypeHierarchy.this); + + /** + * @see ITypeHierarchy + */ + public IType[] getAllClasses() { + + TypeVector classes = this.rootClasses.copy(); + for (Iterator iter = this.classToSuperclass.keySet().iterator(); iter.hasNext();) { + classes.add((IType) iter.next()); + } + return classes.elements(); + } + + /** + * @see org.eclipse.wst.jsdt.core.ITypeHierarchy#getAllSubtypes(org.eclipse.wst.jsdt.core.IType) + */ + public IType[] getAllSubtypes(IType type) { + Set subTypes = new HashSet(); + LinkedList typesToGetSubtypesOf = new LinkedList(); + typesToGetSubtypesOf.add(type); + + //for each type to get the sub types of + while(!typesToGetSubtypesOf.isEmpty()) { + IType typeToGetSubtypeOf = (IType)typesToGetSubtypesOf.removeFirst(); + IType[] currSubTypes = this.getSubtypesForType(typeToGetSubtypeOf); + + /* for each sub type check if it is already a known sub type + * if it is not add it to the list of known subtypes and then + * add it to the list of types to get the subtypes of */ + for(int i = 0; i < currSubTypes.length; ++i) { + if(!subTypes.contains(currSubTypes[i])) { + subTypes.add(currSubTypes[i]); + typesToGetSubtypesOf.add(currSubTypes[i]); + } } - }); + } + + IType[] subClasses = new IType[subTypes.size()]; + subTypes.toArray(subClasses); + + return subClasses; } -} -private static byte[] flagsToBytes(Integer flags){ - if(flags != null) { - return flags.toString().getBytes(); - } else { - return NO_FLAGS; + + /** + * Returns an array of subtypes for the given type - will never return + * null. + */ + private IType[] getSubtypesForType(IType type) { + TypeVector vector = (TypeVector)this.typeToSubtypes.get(type.getDisplayName()); + if (vector == null) + return NO_TYPE; + else + return vector.elements(); } -} -/** - * @see ITypeHierarchy - */ -public IType[] getAllClasses() { - TypeVector classes = this.rootClasses.copy(); - for (Iterator iter = this.classToSuperclass.keySet().iterator(); iter.hasNext();){ - classes.add((IType)iter.next()); + /** + * @see ITypeHierarchy + */ + public IType[] getAllSuperclasses(IType type) { + IType superclass = getSuperclass(type); + TypeVector supers = new TypeVector(); + while (superclass != null) { + supers.add(superclass); + superclass = getSuperclass(superclass); + } + return supers.elements(); } - return classes.elements(); -} -/** - * @see ITypeHierarchy - */ -public IType[] getAllSubtypes(IType type) { - return getAllSubtypesForType(type); -} -/** - * @see #getAllSubtypes(IType) - */ -private IType[] getAllSubtypesForType(IType type) { - ArrayList subTypes = new ArrayList(); - getAllSubtypesForType0(type, subTypes); - IType[] subClasses = new IType[subTypes.size()]; - subTypes.toArray(subClasses); - return subClasses; -} -/** - */ -private void getAllSubtypesForType0(IType type, ArrayList subs) { - IType[] subTypes = getSubtypesForType(type); - if (subTypes.length != 0) { - for (int i = 0; i < subTypes.length; i++) { - IType subType = subTypes[i]; - subs.add(subType); - getAllSubtypesForType0(subType, subs); + + /** + * @see ITypeHierarchy#getCachedFlags(IType) + */ + public int getCachedFlags(IType type) { + Integer flagObject = (Integer) this.typeFlags.get(type); + if (flagObject != null) { + return flagObject.intValue(); } + return -1; } -} -/** - * Returns an array of subtypes for the given type - will never return null. - */ -private IType[] getSubtypesForType(IType type) { - TypeVector vector = (TypeVector)this.typeToSubtypes.get(type); - if (vector == null) - return NO_TYPE; - else - return vector.elements(); -} -/** - * @see ITypeHierarchy - */ -public IType[] getAllSuperclasses(IType type) { - IType superclass = getSuperclass(type); - TypeVector supers = new TypeVector(); - while (superclass != null) { - supers.add(superclass); - superclass = getSuperclass(superclass); + + /** + * @see ITypeHierarchy + */ + public IType[] getRootClasses() { + return this.rootClasses.elements(); } - return supers.elements(); -} -/** - * @see ITypeHierarchy#getCachedFlags(IType) - */ -public int getCachedFlags(IType type) { - Integer flagObject = (Integer) this.typeFlags.get(type); - if (flagObject != null){ - return flagObject.intValue(); + /** + * @see ITypeHierarchy + */ + public IType[] getSubclasses(IType type) { + TypeVector vector = (TypeVector)this.typeToSubtypes.get(type.getDisplayName()); + if (vector == null) + return NO_TYPE; + else + return vector.elements(); } - return -1; -} -/** - * @see ITypeHierarchy - */ -public IType[] getRootClasses() { - return this.rootClasses.elements(); -} -/** - * @see ITypeHierarchy - */ -public IType[] getSubclasses(IType type) { - TypeVector vector = (TypeVector)this.typeToSubtypes.get(type); - if (vector == null) - return NO_TYPE; - else - return vector.elements(); -} -/** - * @see ITypeHierarchy - */ -public IType getSuperclass(IType type) { - return (IType) this.classToSuperclass.get(type); -} -/** - * @see ITypeHierarchy - */ -public IType getType() { - return this.focusType; -} -/** - * Adds the new elements to a new array that contains all of the elements of the old array. - * Returns the new array. - */ -protected IType[] growAndAddToArray(IType[] array, IType[] additions) { - if (array == null || array.length == 0) { - return additions; + + /** + * @see ITypeHierarchy + */ + public IType getSuperclass(IType type) { + return (IType) this.classToSuperclass.get(type); } - IType[] old = array; - array = new IType[old.length + additions.length]; - System.arraycopy(old, 0, array, 0, old.length); - System.arraycopy(additions, 0, array, old.length, additions.length); - return array; -} -/** - * Adds the new element to a new array that contains all of the elements of the old array. - * Returns the new array. - */ -protected IType[] growAndAddToArray(IType[] array, IType addition) { - if (array == null || array.length == 0) { - return new IType[] {addition}; + + /** + * @see ITypeHierarchy + */ + public IType getType() { + return this.focusType; } - IType[] old = array; - array = new IType[old.length + 1]; - System.arraycopy(old, 0, array, 0, old.length); - array[old.length] = addition; - return array; -} -/* - * Whether fine-grained deltas where collected and affects this hierarchy. - */ -public boolean hasFineGrainChanges() { - ChangeCollector collector = this.changeCollector; - return collector != null && collector.needsRefresh(); -} -/** - * Returns whether one of the subtypes in this hierarchy has the given simple name - * or this type has the given simple name. - */ -private boolean hasSubtypeNamed(String simpleName) { - if (this.focusType != null && this.focusType.getElementName().equals(simpleName)) { - return true; + + /** + * Adds the new elements to a new array that contains all of the elements + * of the old array. Returns the new array. + */ + protected IType[] growAndAddToArray(IType[] array, IType[] additions) { + if (array == null || array.length == 0) { + return additions; + } + IType[] old = array; + array = new IType[old.length + additions.length]; + System.arraycopy(old, 0, array, 0, old.length); + System.arraycopy(additions, 0, array, old.length, additions.length); + return array; } - IType[] types = this.focusType == null ? getAllClasses() : getAllSubtypes(this.focusType); - for (int i = 0, length = types.length; i < length; i++) { - if (types[i].getElementName().equals(simpleName)) { - return true; + + /** + * Adds the new element to a new array that contains all of the elements + * of the old array. Returns the new array. + */ + protected IType[] growAndAddToArray(IType[] array, IType addition) { + if (array == null || array.length == 0) { + return new IType[]{addition}; } + IType[] old = array; + array = new IType[old.length + 1]; + System.arraycopy(old, 0, array, 0, old.length); + array[old.length] = addition; + return array; } - return false; -} -/** - * Returns whether one of the types in this hierarchy has the given simple name. - */ -private boolean hasTypeNamed(String simpleName) { - IType[] types = this.getAllClasses(); - for (int i = 0, length = types.length; i < length; i++) { - if (types[i].getElementName().equals(simpleName)) { + /** + * Whether fine-grained deltas where collected and affects this hierarchy. + */ + public boolean hasFineGrainChanges() { + ChangeCollector collector = this.changeCollector; + return collector != null && collector.needsRefresh(); + } + + /** + * Returns whether one of the subtypes in this hierarchy has the given + * simple name or this type has the given simple name. + */ + private boolean hasSubtypeNamed(String simpleName) { + if (this.focusType != null && this.focusType.getElementName().equals(simpleName)) { return true; } + IType[] types = this.focusType == null ? getAllClasses() : getAllSubtypes(this.focusType); + for (int i = 0, length = types.length; i < length; i++) { + if (types[i].getElementName().equals(simpleName)) { + return true; + } + } + return false; } - return false; -} -/** - * Returns whether the simple name of the given type or one of its supertypes is - * the simple name of one of the types in this hierarchy. - */ -boolean includesTypeOrSupertype(IType type) { - try { - // check type - if (hasTypeNamed(type.getElementName())) return true; - - // check superclass - String superclassName = type.getSuperclassName(); - if (superclassName != null) { - int lastSeparator = superclassName.lastIndexOf('.'); - String simpleName = superclassName.substring(lastSeparator+1); - if (hasTypeNamed(simpleName)) return true; + /** + * Returns whether one of the types in this hierarchy has the given simple + * name. + */ + private boolean hasTypeNamed(String simpleName) { + IType[] types = this.getAllClasses(); + for (int i = 0, length = types.length; i < length; i++) { + if (types[i].getElementName().equals(simpleName)) { + return true; + } } - } catch (JavaScriptModelException e) { - // ignore - } - return false; -} -/** - * Initializes this hierarchy's internal tables with the given size. - */ -protected void initialize(int size) { - if (size < 10) { - size = 10; - } - int smallSize = (size / 2); - this.classToSuperclass = new HashMap(size); - this.missingTypes = new ArrayList(smallSize); - this.rootClasses = new TypeVector(); - this.typeToSubtypes = new HashMap(smallSize); - this.typeFlags = new HashMap(smallSize); - - this.projectRegion = new Region(); - this.packageRegion = new Region(); - this.files = new HashMap(5); -} -/** - * Returns true if the given delta could change this type hierarchy - */ -public synchronized boolean isAffected(IJavaScriptElementDelta delta) { - IJavaScriptElement element= delta.getElement(); - switch (element.getElementType()) { - case IJavaScriptElement.JAVASCRIPT_MODEL: - return isAffectedByJavaModel(delta, element); - case IJavaScriptElement.JAVASCRIPT_PROJECT: - return isAffectedByJavaProject(delta, element); - case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT: - return isAffectedByPackageFragmentRoot(delta, element); - case IJavaScriptElement.PACKAGE_FRAGMENT: - return isAffectedByPackageFragment(delta, (PackageFragment) element); - case IJavaScriptElement.CLASS_FILE: - case IJavaScriptElement.JAVASCRIPT_UNIT: - return isAffectedByOpenable(delta, element); + return false; } - return false; -} -/** - * Returns true if any of the children of a project, package - * fragment root, or package fragment have changed in a way that - * effects this type hierarchy. - */ -private boolean isAffectedByChildren(IJavaScriptElementDelta delta) { - if ((delta.getFlags() & IJavaScriptElementDelta.F_CHILDREN) > 0) { - IJavaScriptElementDelta[] children= delta.getAffectedChildren(); - for (int i= 0; i < children.length; i++) { - if (isAffected(children[i])) { + + /** + * Returns whether the simple name of the given type or one of its + * supertypes is the simple name of one of the types in this hierarchy. + */ + boolean includesTypeOrSupertype(IType type) { + try { + // check type + if (hasTypeNamed(type.getElementName())) return true; + + // check superclass + String superclassName = type.getSuperclassName(); + if (superclassName != null) { + int lastSeparator = superclassName.lastIndexOf('.'); + String simpleName = superclassName.substring(lastSeparator + 1); + if (hasTypeNamed(simpleName)) + return true; } } + catch (JavaScriptModelException e) { + // ignore + } + return false; } - return false; -} -/** - * Returns true if the given java model delta could affect this type hierarchy - */ -private boolean isAffectedByJavaModel(IJavaScriptElementDelta delta, IJavaScriptElement element) { - switch (delta.getKind()) { - case IJavaScriptElementDelta.ADDED : - case IJavaScriptElementDelta.REMOVED : - return element.equals(this.javaProject().getJavaScriptModel()); - case IJavaScriptElementDelta.CHANGED : - return isAffectedByChildren(delta); + + /** + * Initializes this hierarchy's internal tables with the given size. + */ + protected void initialize(int size) { + if (size < 10) { + size = 10; + } + int smallSize = (size / 2); + this.classToSuperclass = new HashMap(size); + this.missingTypes = new ArrayList(smallSize); + this.rootClasses = new TypeVector(); + this.typeToSubtypes = new HashMap(smallSize); + this.typeFlags = new HashMap(smallSize); + + this.projectRegion = new Region(); + this.packageRegion = new Region(); + this.files = new HashMap(5); } - return false; -} -/** - * Returns true if the given java project delta could affect this type hierarchy - */ -private boolean isAffectedByJavaProject(IJavaScriptElementDelta delta, IJavaScriptElement element) { - int kind = delta.getKind(); - int flags = delta.getFlags(); - if ((flags & IJavaScriptElementDelta.F_OPENED) != 0) { - kind = IJavaScriptElementDelta.ADDED; // affected in the same way - } - if ((flags & IJavaScriptElementDelta.F_CLOSED) != 0) { - kind = IJavaScriptElementDelta.REMOVED; // affected in the same way - } - switch (kind) { - case IJavaScriptElementDelta.ADDED : - try { - // if the added project is on the classpath, then the hierarchy has changed - IIncludePathEntry[] classpath = ((JavaProject)this.javaProject()).getExpandedClasspath(); - for (int i = 0; i < classpath.length; i++) { - if (classpath[i].getEntryKind() == IIncludePathEntry.CPE_PROJECT - && classpath[i].getPath().equals(element.getPath())) { - return true; - } - } - if (this.focusType != null) { - // if the hierarchy's project is on the added project classpath, then the hierarchy has changed - classpath = ((JavaProject)element).getExpandedClasspath(); - IPath hierarchyProject = javaProject().getPath(); - for (int i = 0; i < classpath.length; i++) { - if (classpath[i].getEntryKind() == IIncludePathEntry.CPE_PROJECT - && classpath[i].getPath().equals(hierarchyProject)) { - return true; - } - } - } - return false; - } catch (JavaScriptModelException e) { - return false; - } - case IJavaScriptElementDelta.REMOVED : - // removed project - if it contains packages we are interested in - // then the type hierarchy has changed - IJavaScriptElement[] pkgs = this.packageRegion.getElements(); - for (int i = 0; i < pkgs.length; i++) { - IJavaScriptProject javaProject = pkgs[i].getJavaScriptProject(); - if (javaProject != null && javaProject.equals(element)) { + + /** + * Returns true if the given delta could change this type hierarchy + */ + public synchronized boolean isAffected(IJavaScriptElementDelta delta) { + IJavaScriptElement element = delta.getElement(); + switch (element.getElementType()) { + case IJavaScriptElement.JAVASCRIPT_MODEL : + return isAffectedByJavaModel(delta, element); + case IJavaScriptElement.JAVASCRIPT_PROJECT : + return isAffectedByJavaProject(delta, element); + case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT : + return isAffectedByPackageFragmentRoot(delta, element); + case IJavaScriptElement.PACKAGE_FRAGMENT : + return isAffectedByPackageFragment(delta, (PackageFragment) element); + case IJavaScriptElement.CLASS_FILE : + case IJavaScriptElement.JAVASCRIPT_UNIT : + return isAffectedByOpenable(delta, element); + } + return false; + } + + /** + * Returns true if any of the children of a project, package fragment + * root, or package fragment have changed in a way that effects this type + * hierarchy. + */ + private boolean isAffectedByChildren(IJavaScriptElementDelta delta) { + if ((delta.getFlags() & IJavaScriptElementDelta.F_CHILDREN) > 0) { + IJavaScriptElementDelta[] children = delta.getAffectedChildren(); + for (int i = 0; i < children.length; i++) { + if (isAffected(children[i])) { return true; } } - return false; - case IJavaScriptElementDelta.CHANGED : - return isAffectedByChildren(delta); + } + return false; } - return false; -} -/** - * Returns true if the given package fragment delta could affect this type hierarchy - */ -private boolean isAffectedByPackageFragment(IJavaScriptElementDelta delta, PackageFragment element) { - switch (delta.getKind()) { - case IJavaScriptElementDelta.ADDED : - // if the package fragment is in the projects being considered, this could - // introduce new types, changing the hierarchy - return this.projectRegion.contains(element); - case IJavaScriptElementDelta.REMOVED : - // is a change if the package fragment contains types in this hierarchy - return packageRegionContainsSamePackageFragment(element); - case IJavaScriptElementDelta.CHANGED : - // look at the files in the package fragment - return isAffectedByChildren(delta); + + /** + * Returns true if the given java model delta could affect this type + * hierarchy + */ + private boolean isAffectedByJavaModel(IJavaScriptElementDelta delta, IJavaScriptElement element) { + switch (delta.getKind()) { + case IJavaScriptElementDelta.ADDED : + case IJavaScriptElementDelta.REMOVED : + return element.equals(this.javaProject().getJavaScriptModel()); + case IJavaScriptElementDelta.CHANGED : + return isAffectedByChildren(delta); + } + return false; } - return false; -} -/** - * Returns true if the given package fragment root delta could affect this type hierarchy - */ -private boolean isAffectedByPackageFragmentRoot(IJavaScriptElementDelta delta, IJavaScriptElement element) { - switch (delta.getKind()) { - case IJavaScriptElementDelta.ADDED : - return this.projectRegion.contains(element); - case IJavaScriptElementDelta.REMOVED : - case IJavaScriptElementDelta.CHANGED : - int flags = delta.getFlags(); - if ((flags & IJavaScriptElementDelta.F_ADDED_TO_CLASSPATH) > 0) { - // check if the root is in the classpath of one of the projects of this hierarchy - if (this.projectRegion != null) { - IPackageFragmentRoot root = (IPackageFragmentRoot)element; - IPath rootPath = root.getPath(); - IJavaScriptElement[] elements = this.projectRegion.getElements(); - for (int i = 0; i < elements.length; i++) { - JavaProject javaProject = (JavaProject)elements[i]; - try { - IIncludePathEntry entry = javaProject.getClasspathEntryFor(rootPath); - if (entry != null) { + + /** + * Returns true if the given java project delta could affect this type + * hierarchy + */ + private boolean isAffectedByJavaProject(IJavaScriptElementDelta delta, IJavaScriptElement element) { + int kind = delta.getKind(); + int flags = delta.getFlags(); + if ((flags & IJavaScriptElementDelta.F_OPENED) != 0) { + kind = IJavaScriptElementDelta.ADDED; // affected in the same way + } + if ((flags & IJavaScriptElementDelta.F_CLOSED) != 0) { + kind = IJavaScriptElementDelta.REMOVED; // affected in the same way + } + switch (kind) { + case IJavaScriptElementDelta.ADDED : + try { + // if the added project is on the classpath, then the hierarchy has changed + IIncludePathEntry[] classpath = ((JavaProject) this.javaProject()).getExpandedClasspath(); + for (int i = 0; i < classpath.length; i++) { + if (classpath[i].getEntryKind() == IIncludePathEntry.CPE_PROJECT && classpath[i].getPath().equals(element.getPath())) { + return true; + } + } + if (this.focusType != null) { + /* if the hierarchy's project is on the added project + * classpath, then the hierarchy has changed */ + classpath = ((JavaProject) element).getExpandedClasspath(); + IPath hierarchyProject = javaProject().getPath(); + for (int i = 0; i < classpath.length; i++) { + if (classpath[i].getEntryKind() == IIncludePathEntry.CPE_PROJECT && classpath[i].getPath().equals(hierarchyProject)) { return true; } - } catch (JavaScriptModelException e) { - // igmore this project } } + return false; } - } - if ((flags & IJavaScriptElementDelta.F_REMOVED_FROM_CLASSPATH) > 0 || (flags & IJavaScriptElementDelta.F_CONTENT) > 0) { - // 1. removed from classpath - if it contains packages we are interested in - // the the type hierarchy has changed - // 2. content of a jar changed - if it contains packages we are interested in - // the the type hierarchy has changed + catch (JavaScriptModelException e) { + return false; + } + case IJavaScriptElementDelta.REMOVED : + /* removed project - if it contains packages we are interested in + * then the type hierarchy has changed */ IJavaScriptElement[] pkgs = this.packageRegion.getElements(); for (int i = 0; i < pkgs.length; i++) { - if (pkgs[i].getParent().equals(element)) { + IJavaScriptProject javaProject = pkgs[i].getJavaScriptProject(); + if (javaProject != null && javaProject.equals(element)) { return true; } } return false; - } - } - return isAffectedByChildren(delta); -} -/** - * Returns true if the given type delta (a compilation unit delta or a class file delta) - * could affect this type hierarchy. - */ -protected boolean isAffectedByOpenable(IJavaScriptElementDelta delta, IJavaScriptElement element) { - if (element instanceof CompilationUnit) { - CompilationUnit cu = (CompilationUnit)element; - ChangeCollector collector = this.changeCollector; - if (collector == null) { - collector = new ChangeCollector(this); + case IJavaScriptElementDelta.CHANGED : + return isAffectedByChildren(delta); } - try { - collector.addChange(cu, delta); - } catch (JavaScriptModelException e) { - if (DEBUG) - e.printStackTrace(); - } - if (cu.isWorkingCopy()) { - // changes to working copies are batched - this.changeCollector = collector; - return false; - } else { - return collector.needsRefresh(); - } - } else if (element instanceof ClassFile) { + return false; + } + + /** + * Returns true if the given package fragment delta could affect this type + * hierarchy + */ + private boolean isAffectedByPackageFragment(IJavaScriptElementDelta delta, PackageFragment element) { switch (delta.getKind()) { - case IJavaScriptElementDelta.REMOVED: - return this.files.get(element) != null; - case IJavaScriptElementDelta.ADDED: - IType type = ((ClassFile)element).getType(); - String typeName = type.getElementName(); - if (hasSupertype(typeName) - || subtypesIncludeSupertypeOf(type) - || this.missingTypes.contains(typeName)) { + case IJavaScriptElementDelta.ADDED : + // if the package fragment is in the projects being considered, this could + // introduce new types, changing the hierarchy + return this.projectRegion.contains(element); + case IJavaScriptElementDelta.REMOVED : + // is a change if the package fragment contains types in this hierarchy + return packageRegionContainsSamePackageFragment(element); + case IJavaScriptElementDelta.CHANGED : + // look at the files in the package fragment + return isAffectedByChildren(delta); + } + return false; + } - return true; + /** + * Returns true if the given package fragment root delta could affect this + * type hierarchy + */ + private boolean isAffectedByPackageFragmentRoot(IJavaScriptElementDelta delta, IJavaScriptElement element) { + switch (delta.getKind()) { + case IJavaScriptElementDelta.ADDED : + return this.projectRegion.contains(element); + case IJavaScriptElementDelta.REMOVED : + case IJavaScriptElementDelta.CHANGED : + int flags = delta.getFlags(); + if ((flags & IJavaScriptElementDelta.F_ADDED_TO_CLASSPATH) > 0) { + // check if the root is in the classpath of one of the projects of this hierarchy + if (this.projectRegion != null) { + IPackageFragmentRoot root = (IPackageFragmentRoot) element; + IPath rootPath = root.getPath(); + IJavaScriptElement[] elements = this.projectRegion.getElements(); + for (int i = 0; i < elements.length; i++) { + JavaProject javaProject = (JavaProject) elements[i]; + try { + IIncludePathEntry entry = javaProject.getClasspathEntryFor(rootPath); + if (entry != null) { + return true; + } + } + catch (JavaScriptModelException e) { + // igmore this project + } + } + } } - break; - case IJavaScriptElementDelta.CHANGED: - IJavaScriptElementDelta[] children = delta.getAffectedChildren(); - for (int i = 0, length = children.length; i < length; i++) { - IJavaScriptElementDelta child = children[i]; - IJavaScriptElement childElement = child.getElement(); - if (childElement instanceof IType) { - type = (IType)childElement; - boolean hasVisibilityChange = (delta.getFlags() & IJavaScriptElementDelta.F_MODIFIERS) > 0; - boolean hasSupertypeChange = (delta.getFlags() & IJavaScriptElementDelta.F_SUPER_TYPES) > 0; - if ((hasVisibilityChange && hasSupertype(type.getElementName())) - || (hasSupertypeChange && includesTypeOrSupertype(type))) { + if ((flags & IJavaScriptElementDelta.F_REMOVED_FROM_CLASSPATH) > 0 || (flags & IJavaScriptElementDelta.F_CONTENT) > 0) { + /* 1. removed from classpath - if it contains packages we + * are interested in the the type hierarchy has changed + * + * 2. content of a jar changed - if it contains packages we are interested in + * the the type hierarchy has changed */ + IJavaScriptElement[] pkgs = this.packageRegion.getElements(); + for (int i = 0; i < pkgs.length; i++) { + if (pkgs[i].getParent().equals(element)) { return true; } } + return false; } - break; } + return isAffectedByChildren(delta); } - return false; -} -/** - * Returns the java project this hierarchy was created in. - */ -public IJavaScriptProject javaProject() { - return this.focusType.getJavaScriptProject(); -} -protected static byte[] readUntil(InputStream input, byte separator) throws JavaScriptModelException, IOException{ - return readUntil(input, separator, 0); -} -protected static byte[] readUntil(InputStream input, byte separator, int offset) throws IOException, JavaScriptModelException{ - int length = 0; - byte[] bytes = new byte[SIZE]; - byte b; - while((b = (byte)input.read()) != separator && b != -1) { - if(bytes.length == length) { - System.arraycopy(bytes, 0, bytes = new byte[length*2], 0, length); + + /** + * Returns true if the given type delta (a compilation unit delta or a + * class file delta) could affect this type hierarchy. + */ + protected boolean isAffectedByOpenable(IJavaScriptElementDelta delta, IJavaScriptElement element) { + if (element instanceof CompilationUnit) { + CompilationUnit cu = (CompilationUnit) element; + ChangeCollector collector = this.changeCollector; + if (collector == null) { + collector = new ChangeCollector(this); + } + try { + collector.addChange(cu, delta); + } + catch (JavaScriptModelException e) { + if (DEBUG) + e.printStackTrace(); + } + if (cu.isWorkingCopy()) { + // changes to working copies are batched + this.changeCollector = collector; + return false; + } + else { + return collector.needsRefresh(); + } } - bytes[length++] = b; - } - if(b == -1) { - throw new JavaScriptModelException(new JavaModelStatus(IStatus.ERROR)); + else if (element instanceof ClassFile) { + switch (delta.getKind()) { + case IJavaScriptElementDelta.REMOVED : + return this.files.get(element) != null; + case IJavaScriptElementDelta.ADDED : + IType type = ((ClassFile) element).getType(); + String typeName = type.getElementName(); + if (hasSupertype(typeName) || subtypesIncludeSupertypeOf(type) || this.missingTypes.contains(typeName)) { + + return true; + } + break; + case IJavaScriptElementDelta.CHANGED : + IJavaScriptElementDelta[] children = delta.getAffectedChildren(); + for (int i = 0, length = children.length; i < length; i++) { + IJavaScriptElementDelta child = children[i]; + IJavaScriptElement childElement = child.getElement(); + if (childElement instanceof IType) { + type = (IType) childElement; + boolean hasVisibilityChange = (delta.getFlags() & IJavaScriptElementDelta.F_MODIFIERS) > 0; + boolean hasSupertypeChange = (delta.getFlags() & IJavaScriptElementDelta.F_SUPER_TYPES) > 0; + if ((hasVisibilityChange && hasSupertype(type.getElementName())) || (hasSupertypeChange && includesTypeOrSupertype(type))) { + return true; + } + } + } + break; + } + } + return false; } - System.arraycopy(bytes, 0, bytes = new byte[length + offset], offset, length); - return bytes; -} -public static ITypeHierarchy load(IType type, InputStream input, WorkingCopyOwner owner) throws JavaScriptModelException { - try { - TypeHierarchy typeHierarchy = new TypeHierarchy(); - typeHierarchy.initialize(1); - IType[] types = new IType[SIZE]; - int typeCount = 0; + /** + * Returns the java project this hierarchy was created in. + */ + public IJavaScriptProject javaProject() { + return this.focusType.getJavaScriptProject(); + } - byte version = (byte)input.read(); + protected static byte[] readUntil(InputStream input, byte separator) throws JavaScriptModelException, IOException { + return readUntil(input, separator, 0); + } - if(version != VERSION) { - throw new JavaScriptModelException(new JavaModelStatus(IStatus.ERROR)); + protected static byte[] readUntil(InputStream input, byte separator, int offset) throws IOException, JavaScriptModelException { + int length = 0; + byte[] bytes = new byte[SIZE]; + byte b; + while ((b = (byte) input.read()) != separator && b != -1) { + if (bytes.length == length) { + System.arraycopy(bytes, 0, bytes = new byte[length * 2], 0, length); + } + bytes[length++] = b; } - byte generalInfo = (byte)input.read(); - if((generalInfo & COMPUTE_SUBTYPES) != 0) { - typeHierarchy.computeSubtypes = true; + if (b == -1) { + throw new JavaScriptModelException(new JavaModelStatus(IStatus.ERROR)); } + System.arraycopy(bytes, 0, bytes = new byte[length + offset], offset, length); + return bytes; + } - byte b; - byte[] bytes; - - // read project - bytes = readUntil(input, SEPARATOR1); - if(bytes.length > 0) { - typeHierarchy.project = (IJavaScriptProject)JavaScriptCore.create(new String(bytes)); - typeHierarchy.scope = SearchEngine.createJavaSearchScope(new IJavaScriptElement[] {typeHierarchy.project}); - } else { - typeHierarchy.project = null; - typeHierarchy.scope = SearchEngine.createWorkspaceScope(); - } + public static ITypeHierarchy load(IType type, InputStream input, WorkingCopyOwner owner) throws JavaScriptModelException { + try { + TypeHierarchy typeHierarchy = new TypeHierarchy(); + typeHierarchy.initialize(1); - // read missing type - { - bytes = readUntil(input, SEPARATOR1); - byte[] missing; - int j = 0; - int length = bytes.length; - for (int i = 0; i < length; i++) { - b = bytes[i]; - if(b == SEPARATOR2) { - missing = new byte[i - j]; - System.arraycopy(bytes, j, missing, 0, i - j); - typeHierarchy.missingTypes.add(new String(missing)); - j = i + 1; - } + IType[] types = new IType[SIZE]; + int typeCount = 0; + + byte version = (byte) input.read(); + + if (version != VERSION) { + throw new JavaScriptModelException(new JavaModelStatus(IStatus.ERROR)); + } + byte generalInfo = (byte) input.read(); + if ((generalInfo & COMPUTE_SUBTYPES) != 0) { + typeHierarchy.computeSubtypes = true; } - System.arraycopy(bytes, j, missing = new byte[length - j], 0, length - j); - typeHierarchy.missingTypes.add(new String(missing)); - } - // read types - while((b = (byte)input.read()) != SEPARATOR1 && b != -1) { - bytes = readUntil(input, SEPARATOR4, 1); - bytes[0] = b; - IType element = (IType)JavaScriptCore.create(new String(bytes), owner); + byte b; + byte[] bytes; - if(types.length == typeCount) { - System.arraycopy(types, 0, types = new IType[typeCount * 2], 0, typeCount); + // read project + bytes = readUntil(input, SEPARATOR1); + if (bytes.length > 0) { + typeHierarchy.project = (IJavaScriptProject) JavaScriptCore.create(new String(bytes)); + typeHierarchy.scope = SearchEngine.createJavaSearchScope(new IJavaScriptElement[]{typeHierarchy.project}); + } + else { + typeHierarchy.project = null; + typeHierarchy.scope = SearchEngine.createWorkspaceScope(); } - types[typeCount++] = element; - // read flags - bytes = readUntil(input, SEPARATOR4); - Integer flags = bytesToFlags(bytes); - if(flags != null) { - typeHierarchy.cacheFlags(element, flags.intValue()); + // read missing type + { + bytes = readUntil(input, SEPARATOR1); + byte[] missing; + int j = 0; + int length = bytes.length; + for (int i = 0; i < length; i++) { + b = bytes[i]; + if (b == SEPARATOR2) { + missing = new byte[i - j]; + System.arraycopy(bytes, j, missing, 0, i - j); + typeHierarchy.missingTypes.add(new String(missing)); + j = i + 1; + } + } + System.arraycopy(bytes, j, missing = new byte[length - j], 0, length - j); + typeHierarchy.missingTypes.add(new String(missing)); } - // read info - byte info = (byte)input.read(); + // read types + while ((b = (byte) input.read()) != SEPARATOR1 && b != -1) { + bytes = readUntil(input, SEPARATOR4, 1); + bytes[0] = b; + IType element = (IType) JavaScriptCore.create(new String(bytes), owner); - if((info & COMPUTED_FOR) != 0) { - if(!element.equals(type)) { - throw new JavaScriptModelException(new JavaModelStatus(IStatus.ERROR)); + if (types.length == typeCount) { + System.arraycopy(types, 0, types = new IType[typeCount * 2], 0, typeCount); + } + types[typeCount++] = element; + + // read flags + bytes = readUntil(input, SEPARATOR4); + Integer flags = bytesToFlags(bytes); + if (flags != null) { + typeHierarchy.cacheFlags(element, flags.intValue()); + } + + // read info + byte info = (byte) input.read(); + + if ((info & COMPUTED_FOR) != 0) { + if (!element.equals(type)) { + throw new JavaScriptModelException(new JavaModelStatus(IStatus.ERROR)); + } + typeHierarchy.focusType = element; + } + if ((info & ROOT) != 0) { + typeHierarchy.addRootClass(element); } - typeHierarchy.focusType = element; - } - if((info & ROOT) != 0) { - typeHierarchy.addRootClass(element); } - } - // read super class - while((b = (byte)input.read()) != SEPARATOR1 && b != -1) { - bytes = readUntil(input, SEPARATOR3, 1); - bytes[0] = b; - int subClass = new Integer(new String(bytes)).intValue(); + // read super class + while ((b = (byte) input.read()) != SEPARATOR1 && b != -1) { + bytes = readUntil(input, SEPARATOR3, 1); + bytes[0] = b; + int subClass = new Integer(new String(bytes)).intValue(); - // read super type - bytes = readUntil(input, SEPARATOR1); - int superClass = new Integer(new String(bytes)).intValue(); + // read super type + bytes = readUntil(input, SEPARATOR1); + int superClass = new Integer(new String(bytes)).intValue(); - typeHierarchy.cacheSuperclass( - types[subClass], - types[superClass]); - } + typeHierarchy.cacheSuperclass(types[subClass], types[superClass]); + } - if(b == -1) { - throw new JavaScriptModelException(new JavaModelStatus(IStatus.ERROR)); + if (b == -1) { + throw new JavaScriptModelException(new JavaModelStatus(IStatus.ERROR)); + } + return typeHierarchy; + } + catch (IOException e) { + throw new JavaScriptModelException(e, IJavaScriptModelStatusConstants.IO_EXCEPTION); } - return typeHierarchy; - } catch(IOException e){ - throw new JavaScriptModelException(e, IJavaScriptModelStatusConstants.IO_EXCEPTION); - } -} -/** - * Returns true if an equivalent package fragment is included in the package - * region. Package fragments are equivalent if they both have the same name. - */ -protected boolean packageRegionContainsSamePackageFragment(PackageFragment element) { - IJavaScriptElement[] pkgs = this.packageRegion.getElements(); - for (int i = 0; i < pkgs.length; i++) { - PackageFragment pkg = (PackageFragment) pkgs[i]; - if (Util.equalArraysOrNull(pkg.names, element.names)) - return true; } - return false; -} -/** - * @see ITypeHierarchy - * TODO (jerome) should use a PerThreadObject to build the hierarchy instead of synchronizing - * (see also isAffected(IJavaScriptElementDelta)) - */ -public synchronized void refresh(IProgressMonitor monitor) throws JavaScriptModelException { - try { - this.progressMonitor = monitor; - if (monitor != null) { - monitor.beginTask( - this.focusType != null ? - Messages.bind(Messages.hierarchy_creatingOnType, this.focusType.getFullyQualifiedName()) : - Messages.hierarchy_creating, - 100); + /** + * Returns true if an equivalent package fragment is included + * in the package region. Package fragments are equivalent if they both + * have the same name. + */ + protected boolean packageRegionContainsSamePackageFragment(PackageFragment element) { + IJavaScriptElement[] pkgs = this.packageRegion.getElements(); + for (int i = 0; i < pkgs.length; i++) { + PackageFragment pkg = (PackageFragment) pkgs[i]; + if (Util.equalArraysOrNull(pkg.names, element.names)) + return true; } - long start = -1; - if (DEBUG) { - start = System.currentTimeMillis(); - if (this.computeSubtypes) { - System.out.println("CREATING TYPE HIERARCHY [" + Thread.currentThread() + "]"); //$NON-NLS-1$ //$NON-NLS-2$ - } else { - System.out.println("CREATING SUPER TYPE HIERARCHY [" + Thread.currentThread() + "]"); //$NON-NLS-1$ //$NON-NLS-2$ + return false; + } + + /** + * @see ITypeHierarchy TODO (jerome) should use a PerThreadObject to build + * the hierarchy instead of synchronizing (see also + * isAffected(IJavaScriptElementDelta)) + */ + public synchronized void refresh(IProgressMonitor monitor) throws JavaScriptModelException { + try { + this.progressMonitor = monitor; + if (monitor != null) { + monitor.beginTask(this.focusType != null ? Messages.bind(Messages.hierarchy_creatingOnType, this.focusType.getFullyQualifiedName()) : Messages.hierarchy_creating, 100); } - if (this.focusType != null) { - System.out.println(" on type " + ((JavaElement)this.focusType).toStringWithAncestors()); //$NON-NLS-1$ + long start = -1; + if (DEBUG) { + start = System.currentTimeMillis(); + if (this.computeSubtypes) { + System.out.println("CREATING TYPE HIERARCHY [" + Thread.currentThread() + "]"); //$NON-NLS-1$ //$NON-NLS-2$ + } + else { + System.out.println("CREATING SUPER TYPE HIERARCHY [" + Thread.currentThread() + "]"); //$NON-NLS-1$ //$NON-NLS-2$ + } + if (this.focusType != null) { + System.out.println(" on type " + ((JavaElement) this.focusType).toStringWithAncestors()); //$NON-NLS-1$ + } } - } - compute(); - initializeRegions(); - this.needsRefresh = false; - this.changeCollector = null; + compute(); + initializeRegions(); + this.needsRefresh = false; + this.changeCollector = null; - if (DEBUG) { - if (this.computeSubtypes) { - System.out.println("CREATED TYPE HIERARCHY in " + (System.currentTimeMillis() - start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ - } else { - System.out.println("CREATED SUPER TYPE HIERARCHY in " + (System.currentTimeMillis() - start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ + if (DEBUG) { + if (this.computeSubtypes) { + System.out.println("CREATED TYPE HIERARCHY in " + (System.currentTimeMillis() - start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ + } + else { + System.out.println("CREATED SUPER TYPE HIERARCHY in " + (System.currentTimeMillis() - start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ + } + System.out.println(this.toString()); } - System.out.println(this.toString()); } - } catch (JavaScriptModelException e) { - throw e; - } catch (CoreException e) { - throw new JavaScriptModelException(e); - } finally { - if (monitor != null) { - monitor.done(); + catch (JavaScriptModelException e) { + throw e; + } + catch (CoreException e) { + throw new JavaScriptModelException(e); + } + finally { + if (monitor != null) { + monitor.done(); + } + this.progressMonitor = null; } - this.progressMonitor = null; } -} -/** - * @see ITypeHierarchy - */ -public synchronized void removeTypeHierarchyChangedListener(ITypeHierarchyChangedListener listener) { - ArrayList listeners = this.changeListeners; - if (listeners == null) { - return; - } - listeners.remove(listener); + /** + * @see ITypeHierarchy + */ + public synchronized void removeTypeHierarchyChangedListener(ITypeHierarchyChangedListener listener) { + ArrayList listeners = this.changeListeners; + if (listeners == null) { + return; + } + listeners.remove(listener); - // deregister from JavaScriptCore on last listener removed - if (listeners.isEmpty()) { - JavaScriptCore.removeElementChangedListener(this); - } -} -/** - * @see ITypeHierarchy - */ -public void store(OutputStream output, IProgressMonitor monitor) throws JavaScriptModelException { - try { - // compute types in hierarchy - Hashtable hashtable = new Hashtable(); - Hashtable hashtable2 = new Hashtable(); - int count = 0; - - if(this.focusType != null) { - Integer index = new Integer(count++); - hashtable.put(this.focusType, index); - hashtable2.put(index, this.focusType); + // deregister from JavaScriptCore on last listener removed + if (listeners.isEmpty()) { + JavaScriptCore.removeElementChangedListener(this); } - Object[] types = this.classToSuperclass.entrySet().toArray(); - for (int i = 0; i < types.length; i++) { - Map.Entry entry = (Map.Entry) types[i]; - Object t = entry.getKey(); - if(hashtable.get(t) == null) { + } + + /** + * @see ITypeHierarchy + */ + public void store(OutputStream output, IProgressMonitor monitor) throws JavaScriptModelException { + try { + // compute types in hierarchy + Hashtable hashtable = new Hashtable(); + Hashtable hashtable2 = new Hashtable(); + int count = 0; + + if (this.focusType != null) { Integer index = new Integer(count++); - hashtable.put(t, index); - hashtable2.put(index, t); + hashtable.put(this.focusType, index); + hashtable2.put(index, this.focusType); } - Object superClass = entry.getValue(); - if(superClass != null && hashtable.get(superClass) == null) { - Integer index = new Integer(count++); - hashtable.put(superClass, index); - hashtable2.put(index, superClass); + Object[] types = this.classToSuperclass.entrySet().toArray(); + for (int i = 0; i < types.length; i++) { + Map.Entry entry = (Map.Entry) types[i]; + Object t = entry.getKey(); + if (hashtable.get(t) == null) { + Integer index = new Integer(count++); + hashtable.put(t, index); + hashtable2.put(index, t); + } + Object superClass = entry.getValue(); + if (superClass != null && hashtable.get(superClass) == null) { + Integer index = new Integer(count++); + hashtable.put(superClass, index); + hashtable2.put(index, superClass); + } } - } - // save version of the hierarchy format - output.write(VERSION); + // save version of the hierarchy format + output.write(VERSION); - // save general info - byte generalInfo = 0; - if(this.computeSubtypes) { - generalInfo |= COMPUTE_SUBTYPES; - } - output.write(generalInfo); + // save general info + byte generalInfo = 0; + if (this.computeSubtypes) { + generalInfo |= COMPUTE_SUBTYPES; + } + output.write(generalInfo); - // save project - if(this.project != null) { - output.write(this.project.getHandleIdentifier().getBytes()); - } - output.write(SEPARATOR1); + // save project + if (this.project != null) { + output.write(this.project.getHandleIdentifier().getBytes()); + } + output.write(SEPARATOR1); + + // save missing types + for (int i = 0; i < this.missingTypes.size(); i++) { + if (i != 0) { + output.write(SEPARATOR2); + } + output.write(((String) this.missingTypes.get(i)).getBytes()); - // save missing types - for (int i = 0; i < this.missingTypes.size(); i++) { - if(i != 0) { - output.write(SEPARATOR2); } - output.write(((String)this.missingTypes.get(i)).getBytes()); + output.write(SEPARATOR1); - } - output.write(SEPARATOR1); - - // save types - for (int i = 0; i < count ; i++) { - IType t = (IType)hashtable2.get(new Integer(i)); - - // n bytes - output.write(t.getHandleIdentifier().getBytes()); - output.write(SEPARATOR4); - output.write(flagsToBytes((Integer)this.typeFlags.get(t))); - output.write(SEPARATOR4); - byte info = CLASS; - if(this.focusType != null && this.focusType.equals(t)) { - info |= COMPUTED_FOR; + // save types + for (int i = 0; i < count; i++) { + IType t = (IType) hashtable2.get(new Integer(i)); + + // n bytes + output.write(t.getHandleIdentifier().getBytes()); + output.write(SEPARATOR4); + output.write(flagsToBytes((Integer) this.typeFlags.get(t))); + output.write(SEPARATOR4); + byte info = CLASS; + if (this.focusType != null && this.focusType.equals(t)) { + info |= COMPUTED_FOR; + } + if (this.rootClasses.contains(t)) { + info |= ROOT; + } + output.write(info); } - if(this.rootClasses.contains(t)) { - info |= ROOT; + output.write(SEPARATOR1); + + // save superclasses + types = this.classToSuperclass.entrySet().toArray(); + for (int i = 0; i < types.length; i++) { + Map.Entry entry = (Map.Entry) types[i]; + IJavaScriptElement key = (IJavaScriptElement) entry.getKey(); + IJavaScriptElement value = (IJavaScriptElement) entry.getValue(); + + output.write(((Integer) hashtable.get(key)).toString().getBytes()); + output.write('>'); + output.write(((Integer) hashtable.get(value)).toString().getBytes()); + output.write(SEPARATOR1); } - output.write(info); - } - output.write(SEPARATOR1); - - // save superclasses - types = this.classToSuperclass.entrySet().toArray(); - for (int i = 0; i < types.length; i++) { - Map.Entry entry = (Map.Entry) types[i]; - IJavaScriptElement key = (IJavaScriptElement) entry.getKey(); - IJavaScriptElement value = (IJavaScriptElement) entry.getValue(); - - output.write(((Integer)hashtable.get(key)).toString().getBytes()); - output.write('>'); - output.write(((Integer)hashtable.get(value)).toString().getBytes()); output.write(SEPARATOR1); - } - output.write(SEPARATOR1); - output.write(SEPARATOR1); - } catch(IOException e) { - throw new JavaScriptModelException(e, IJavaScriptModelStatusConstants.IO_EXCEPTION); + output.write(SEPARATOR1); + } + catch (IOException e) { + throw new JavaScriptModelException(e, IJavaScriptModelStatusConstants.IO_EXCEPTION); + } } -} -/** - * Returns whether the simple name of a supertype of the given type is - * the simple name of one of the subtypes in this hierarchy or the - * simple name of this type. - */ -boolean subtypesIncludeSupertypeOf(IType type) { - // look for superclass - String superclassName = null; - try { - superclassName = type.getSuperclassName(); - } catch (JavaScriptModelException e) { - if (DEBUG) { - e.printStackTrace(); + + /** + * Returns whether the simple name of a supertype of the given type is the + * simple name of one of the subtypes in this hierarchy or the simple name + * of this type. + */ + boolean subtypesIncludeSupertypeOf(IType type) { + // look for superclass + String superclassName = null; + try { + superclassName = type.getSuperclassName(); + } + catch (JavaScriptModelException e) { + if (DEBUG) { + e.printStackTrace(); + } + return false; + } + if (superclassName == null) { + superclassName = "Object"; //$NON-NLS-1$ + } + int dot = -1; + String simpleSuper = (dot = superclassName.lastIndexOf('.')) > -1 ? superclassName.substring(dot + 1) : superclassName; + if (hasSubtypeNamed(simpleSuper)) { + return true; } + return false; } - if (superclassName == null) { - superclassName = "Object"; //$NON-NLS-1$ - } - int dot = -1; - String simpleSuper = (dot = superclassName.lastIndexOf('.')) > -1 ? - superclassName.substring(dot + 1) : - superclassName; - if (hasSubtypeNamed(simpleSuper)) { - return true; - } - return false; -} -/** - * @see ITypeHierarchy - */ -public String toString() { - StringBuffer buffer = new StringBuffer(); - buffer.append("Focus: "); //$NON-NLS-1$ - buffer.append(this.focusType == null ? "" : ((JavaElement)this.focusType).toStringWithAncestors(false/*don't show key*/)); //$NON-NLS-1$ - buffer.append("\n"); //$NON-NLS-1$ - if (exists()) { - if (this.focusType != null) { - buffer.append("Super types:\n"); //$NON-NLS-1$ - toString(buffer, this.focusType, 1, true); - buffer.append("Sub types:\n"); //$NON-NLS-1$ - toString(buffer, this.focusType, 1, false); - } else { - buffer.append("Sub types of root classes:\n"); //$NON-NLS-1$ - IJavaScriptElement[] roots = Util.sortCopy(getRootClasses()); - for (int i= 0; i < roots.length; i++) { - toString(buffer, (IType) roots[i], 1, false); + /** + * @see ITypeHierarchy + */ + public String toString() { + StringBuffer buffer = new StringBuffer(); + buffer.append("Focus: "); //$NON-NLS-1$ + buffer.append(this.focusType == null ? "" : ((JavaElement) this.focusType).toStringWithAncestors(false/*don't show key*/)); //$NON-NLS-1$ + buffer.append("\n"); //$NON-NLS-1$ + if (exists()) { + if (this.focusType != null) { + buffer.append("Super types:\n"); //$NON-NLS-1$ + toString(buffer, this.focusType, 1, true); + buffer.append("Sub types:\n"); //$NON-NLS-1$ + toString(buffer, this.focusType, 1, false); } - } - if (this.rootClasses.size > 1) { - buffer.append("Root classes:\n"); //$NON-NLS-1$ - IJavaScriptElement[] roots = Util.sortCopy(getRootClasses()); - for (int i = 0, length = roots.length; i < length; i++) { - toString(buffer, (IType) roots[i], 1, false); + else { + buffer.append("Sub types of root classes:\n"); //$NON-NLS-1$ + IJavaScriptElement[] roots = Util.sortCopy(getRootClasses()); + for (int i = 0; i < roots.length; i++) { + toString(buffer, (IType) roots[i], 1, false); + } + } + if (this.rootClasses.size > 1) { + buffer.append("Root classes:\n"); //$NON-NLS-1$ + IJavaScriptElement[] roots = Util.sortCopy(getRootClasses()); + for (int i = 0, length = roots.length; i < length; i++) { + toString(buffer, (IType) roots[i], 1, false); + } + } + else if (this.rootClasses.size == 0) { + // see http://bugs.eclipse.org/bugs/show_bug.cgi?id=24691 + buffer.append("No root classes"); //$NON-NLS-1$ } - } else if (this.rootClasses.size == 0) { - // see http://bugs.eclipse.org/bugs/show_bug.cgi?id=24691 - buffer.append("No root classes"); //$NON-NLS-1$ } - } else { - buffer.append("(Hierarchy became stale)"); //$NON-NLS-1$ + else { + buffer.append("(Hierarchy became stale)"); //$NON-NLS-1$ + } + return buffer.toString(); } - return buffer.toString(); -} -/** - * Append a String to the given buffer representing the hierarchy for the type, - * beginning with the specified indentation level. - * If ascendant, shows the super types, otherwise show the sub types. - */ -private void toString(StringBuffer buffer, IType type, int indent, boolean ascendant) { - IType[] types= ascendant ? new IType[]{getSuperclass(type)} : getSubclasses(type); - IJavaScriptElement[] sortedTypes = Util.sortCopy(types); - for (int i= 0; i < sortedTypes.length; i++) { - for (int j= 0; j < indent; j++) { - buffer.append(" "); //$NON-NLS-1$ + + /** + * Append a String to the given buffer representing the hierarchy for the + * type, beginning with the specified indentation level. If ascendant, + * shows the super types, otherwise show the sub types. + */ + private void toString(StringBuffer buffer, IType type, int indent, boolean ascendant) { + IType[] types = ascendant ? new IType[]{getSuperclass(type)} : getSubclasses(type); + IJavaScriptElement[] sortedTypes = Util.sortCopy(types); + for (int i = 0; i < sortedTypes.length; i++) { + for (int j = 0; j < indent; j++) { + buffer.append(" "); //$NON-NLS-1$ + } + JavaElement element = (JavaElement) sortedTypes[i]; + buffer.append(element.toStringWithAncestors(false/* don't show key */)); + buffer.append('\n'); + toString(buffer, types[i], indent + 1, ascendant); } - JavaElement element = (JavaElement)sortedTypes[i]; - buffer.append(element.toStringWithAncestors(false/*don't show key*/)); - buffer.append('\n'); - toString(buffer, types[i], indent + 1, ascendant); } -} -/** - * Returns whether one of the types in this hierarchy has a supertype whose simple - * name is the given simple name. - */ -boolean hasSupertype(String simpleName) { - for(Iterator iter = this.classToSuperclass.values().iterator(); iter.hasNext();){ - IType superType = (IType)iter.next(); - if (superType.getElementName().equals(simpleName)) { - return true; + + /** + * Returns whether one of the types in this hierarchy has a supertype + * whose simple name is the given simple name. + */ + boolean hasSupertype(String simpleName) { + for (Iterator iter = this.classToSuperclass.values().iterator(); iter.hasNext();) { + IType superType = (IType) iter.next(); + if (superType.getElementName().equals(simpleName)) { + return true; + } } + return false; } - return false; -} -/** - * @see IProgressMonitor - */ -protected void worked(int work) { - if (this.progressMonitor != null) { - this.progressMonitor.worked(work); - checkCanceled(); + + /** + * @see IProgressMonitor + */ + protected void worked(int work) { + if (this.progressMonitor != null) { + this.progressMonitor.worked(work); + checkCanceled(); + } } -} -} +} \ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/index/DiskIndex.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/index/DiskIndex.java index 46c5a832..52ecd1f3 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/index/DiskIndex.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/index/DiskIndex.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -17,6 +17,7 @@ import java.io.IOException; import java.io.RandomAccessFile; import java.io.UTFDataFormatException; +import org.eclipse.core.runtime.ISafeRunnable; import org.eclipse.wst.jsdt.core.compiler.CharOperation; import org.eclipse.wst.jsdt.core.search.SearchPattern; import org.eclipse.wst.jsdt.internal.compiler.util.HashtableOfIntValues; @@ -24,6 +25,7 @@ import org.eclipse.wst.jsdt.internal.compiler.util.HashtableOfObject; import org.eclipse.wst.jsdt.internal.compiler.util.SimpleLookupTable; import org.eclipse.wst.jsdt.internal.compiler.util.SimpleSet; import org.eclipse.wst.jsdt.internal.compiler.util.SimpleSetOfCharArray; +import org.eclipse.wst.jsdt.internal.core.Logger; import org.eclipse.wst.jsdt.internal.core.util.Messages; import org.eclipse.wst.jsdt.internal.core.util.SimpleWordSet; import org.eclipse.wst.jsdt.internal.core.util.Util; @@ -40,11 +42,13 @@ private int documentReferenceSize; // 1, 2 or more bytes... depends on # of docu private int startOfCategoryTables; private HashtableOfIntValues categoryOffsets, categoryEnds; -private int cacheUserCount; +private volatile int cacheUserCount; private String[][] cachedChunks; // decompressed chunks of document names private HashtableOfObject categoryTables; // category name -> HashtableOfObject(words -> int[] of document #'s) or offset if not read yet private char[] cachedCategoryName; +private Object fStopQueryAction; + private static final int DEFAULT_BUFFER_SIZE = 2048; private static int BUFFER_READ_SIZE = DEFAULT_BUFFER_SIZE; private static final int BUFFER_WRITE_SIZE = DEFAULT_BUFFER_SIZE; @@ -52,7 +56,7 @@ private byte[] streamBuffer; private int bufferIndex, bufferEnd; // used when reading from the file into the streamBuffer private int streamEnd; // used when writing data from the streamBuffer to the file -public static final String SIGNATURE= "INDEX VERSION 1.122"; //$NON-NLS-1$ +public static final String SIGNATURE= "INDEX VERSION 1.3"; //$NON-NLS-1$ private static final char[] SIGNATURE_CHARS = SIGNATURE.toCharArray(); public static boolean DEBUG = false; @@ -221,7 +225,7 @@ HashtableOfObject addQueryResults(char[][] categories, char[] key, int matchRule if (results == null) return null; return results; } -private void cacheDocumentNames() throws IOException { +private synchronized void cacheDocumentNames() throws IOException { // will need all document names so get them now this.cachedChunks = new String[this.numberOfChunks][]; FileInputStream stream = new FileInputStream(this.indexFile); @@ -790,23 +794,51 @@ private void readHeaderInfo(RandomAccessFile file) throws IOException { } this.categoryTables = new HashtableOfObject(3); } -synchronized void startQuery() { +void startQuery() { this.cacheUserCount++; + synchronized (DiskIndex.this) { + //if there is currently a scheduled stop action, cancel it so caches don't get cleared + if (this.fStopQueryAction != null) { + PostponedRunnablesManager.cancelPostponedRunnable(this.fStopQueryAction); + this.fStopQueryAction = null; + } + } } -synchronized void stopQuery() { +void stopQuery() { if (--this.cacheUserCount < 0) { - // clear cached items - this.cacheUserCount = -1; - this.cachedChunks = null; - if (this.categoryTables != null) { - if (this.cachedCategoryName == null) { - this.categoryTables = null; - } else if (this.categoryTables.elementSize > 1) { - HashtableOfObject newTables = new HashtableOfObject(3); - newTables.put(this.cachedCategoryName, this.categoryTables.get(this.cachedCategoryName)); - this.categoryTables = newTables; + //schedule cache clearing for later so if another query comes in cache will not be cleared + this.fStopQueryAction = PostponedRunnablesManager.addPostponedRunnable(new ISafeRunnable() { + /** + *

      Clears category table caches

      + * + * @see org.eclipse.core.runtime.ISafeRunnable#run() + */ + public void run() throws Exception { + synchronized (DiskIndex.this) { + if (DiskIndex.this.cacheUserCount >= 0) + return; + // clear cached items + DiskIndex.this.cachedChunks = null; + if (DiskIndex.this.categoryTables != null) { + if (DiskIndex.this.cachedCategoryName == null) { + DiskIndex.this.categoryTables = null; + } + else if (DiskIndex.this.categoryTables.elementSize > 1) { + HashtableOfObject newTables = new HashtableOfObject(3); + newTables.put(DiskIndex.this.cachedCategoryName, DiskIndex.this.categoryTables.get(DiskIndex.this.cachedCategoryName)); + DiskIndex.this.categoryTables = newTables; + } + } + } } - } + + /** + * @see org.eclipse.core.runtime.ISafeRunnable#handleException(java.lang.Throwable) + */ + public void handleException(Throwable e) { + Logger.logException("Error while trying to clear disk index cache", e); + } + }, 2000); } } private void readStreamBuffer(FileInputStream stream) throws IOException { diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/index/Index.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/index/Index.java index 868f4831..8807f57a 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/index/Index.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/index/Index.java @@ -210,4 +210,15 @@ public void stopQuery() { public String toString() { return "Index for " + this.containerPath; //$NON-NLS-1$ } +/** + * Reset memory and disk indexes. + * + * @throws IOException + */ +public void reset() throws IOException { + this.memoryIndex = new MemoryIndex(); + this.diskIndex = new DiskIndex(this.diskIndex.indexFile.getAbsolutePath()); + this.diskIndex.initialize(false/*do not reuse the index file*/); +} + } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/index/PostponedRunnablesManager.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/index/PostponedRunnablesManager.java new file mode 100644 index 00000000..0a23172d --- /dev/null +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/index/PostponedRunnablesManager.java @@ -0,0 +1,365 @@ +/******************************************************************************* + * Copyright (c) 2011 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.wst.jsdt.internal.core.index; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.ISafeRunnable; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.SafeRunner; +import org.eclipse.core.runtime.Status; +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.wst.jsdt.internal.core.util.Messages; + +/** + *

      Uses a single {@link Job} to run any number of {@link ISafeRunnable} + * scheduled to run at a later time. This is to prevent a different {@link Job} from + * having to be created for every single {@link ISafeRunnable} to be run after a delayed time.

      + * + *

      NOTE: All times are in milliseconds.

      + */ +class PostponedRunnablesManager { + + /** + *

      Lock to use whenever {@link #fRunnablesProcessingJob} is being accessed.

      + */ + private static final Object fRunnablesProcessingJobLock = new Object(); + + /** + *

      The single {@link Job} that handles running the runnables.

      + */ + private static RunnablesProcessingJob fRunnablesProcessingJob; + + /** + *

      Use to add an {@link ISafeRunnable} to be run at a future time. + * The given delay is a minimum time to wait before running the runnable, + * it could be longer before the runnable is run, this is dependent on {@link Job} + * scheduling, the number of runnables to be run, and the running time of each + * runnable since all runnables are run on the same {@link Job}

      + * + * @param runnable {@link ISafeRunnable} to be run after the given delay + * @param delay time in milliseconds to wait before running the given runnable. + * + * @return the created postponed runnable. Pass this to {@link #cancelPostponedRunnable(Object)} + * in order to cancel the postponed runnable before it runs. + * + * @see #cancelPostponedRunnable(ISafeRunnable) + */ + protected static Object addPostponedRunnable(ISafeRunnable runnable, int delay) { + Object result; + synchronized (fRunnablesProcessingJobLock) { + if(fRunnablesProcessingJob == null) { + fRunnablesProcessingJob = new RunnablesProcessingJob(); + } + + result = fRunnablesProcessingJob.addPostponedRunnable(runnable, delay); + } + + return result; + } + + /** + *

      Use to cancel a postponed runnable added with {@link #addPostponedRunnable(ISafeRunnable, int)}.

      + * + * @param runnable the resulting runnable from a call to {@link #addPostponedRunnable(ISafeRunnable, int)} to cancel + * + * @throws InvalidParameterException if the given runnable was not the result of a + * call to {@link #addPostponedRunnable(ISafeRunnable, int)} + * + * @see #addPostponedRunnable(ISafeRunnable, int) + */ + protected static void cancelPostponedRunnable(Object runnable) throws IllegalArgumentException { + synchronized (fRunnablesProcessingJobLock) { + if(fRunnablesProcessingJob != null) { + fRunnablesProcessingJob.removePostponedRunnable(runnable); + } + } + } + + /** + *

      Internal {@link Job} for running all of the postponed runnables.

      + * + *

      IMPORTANT: Should never externally call schedule on this job, it deals with scheduling itself.

      + * + */ + private static class RunnablesProcessingJob extends Job { + + /** + *

      The current amount of time this job is waiting for before the job scheduler will run it.

      + */ + private long fCurrentWaitTime; + + /** + *

      The last time a call to {@link #reSchedule(long)} was made or -1 if the job has run + * since the last scheduling.

      + */ + private long fTimeScheduled; + + /** + *

      The postponed runnables to be run.

      + */ + private final List fRunnables; + + /** + *

      Use this lock whenever accessing {@link #fRunnables} or whenever changing the value of + * {@link #fTimeScheduled} or {@link #fCurrentWaitTime}.

      + */ + private final Object LOCK = new Object(); + + /** + *

      Sets up this job as a long running system job

      + */ + protected RunnablesProcessingJob() { + super(Messages.PostponedRunnablesManager_job_title); + + //set this up as a long running system job + this.setUser(false); + this.setSystem(true); + this.setPriority(Job.INTERACTIVE); + + this.fRunnables = new LinkedList(); + + this.fCurrentWaitTime = -1; + this.fTimeScheduled = -1; + } + + /** + *

      Adds an runnable to run using this job.

      + * + * @param runnable to run after the given delay + * @param delay to run the given runnable after + * + * @return {@link PostponedRunnable} created from the given information, used if the runnable + * is to be canceled before it is run + * + * {@link #removePostponedRunnable(Object)} + */ + protected PostponedRunnable addPostponedRunnable(ISafeRunnable runnable, int delay) { + PostponedRunnable postponedAction = new PostponedRunnable(runnable, delay); + this.addAction(postponedAction); + + return postponedAction; + } + + /** + *

      Removes an runnable to be run using this job.

      + * + * @param runnable {@link PostponedRunnable} that was created with {@link #addPostponedRunnable(ISafeRunnable, int)} or + * {@link #addAction(PostponedRunnable)} to remove before it is run + * + * @throws InvalidParameterException if the given runnable was not the result of a + * call to {@link #addPostponedRunnable(ISafeRunnable, int)} or {@link #addAction(PostponedRunnable)} + */ + protected void removePostponedRunnable(Object runnable) throws IllegalArgumentException { + if(runnable instanceof PostponedRunnable) { + synchronized (LOCK) { + //cancel it in case its already in the list to be processed by #run + ((PostponedRunnable)runnable).cancel(); + + //remove from list of waiting runnables + this.fRunnables.remove(runnable); + } + } else { + throw new IllegalArgumentException("The given runnable to remove was not created " + + "from a call to PostponedRunnablesManager#addPostponedAction"); + } + } + + /** + * @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor) + */ + protected IStatus run(IProgressMonitor monitor) { + //if have runnables to run, try to run them + if(this.hasRunnablesToRun()) { + + //get the current batch of runnables and try to run them + List runnables = this.getRunnables(); + long shortestTimeToWait = 0; + for(int i = 0; i < runnables.size(); ++i) { + final PostponedRunnable runnable = (PostponedRunnable)runnables.get(i); + + //only try to run if not canceled, if it is canceled it will now just go away + if(!runnable.isCanceled()) { + /* if should run, then run + * else add back to runnables to run later + */ + if(runnable.doneWaiting()) { + runnable.run(); + } else { + long timeToWait = runnable.timeToWait(); + shortestTimeToWait = shortestTimeToWait < timeToWait? shortestTimeToWait : timeToWait; + this.addAction(runnable); + } + } + } + + //if still more runnables to run, reschedule for the runnable with the shortest wait time, plus a bit + if(this.hasRunnablesToRun()) { + this.reSchedule(shortestTimeToWait + 100); + } + } + + return Status.OK_STATUS; + } + + /** + *

      Deals with re-scheduling this job to run again after a given amount of time. + * If the job has already been scheduled with a shorter wait time nothing happens. + * If the job has already been scheduled with a longer wait time the job is canceled and + * re-scheduled with the shorter wait time. + * If the job is already running it is scheduled to run again with the given wait time.

      + * + * @param newWaitTime minimum time before this job should run again + */ + private void reSchedule(long newWaitTime) { + synchronized (LOCK) { + //if not currently waiting or new wait time is less then approximate time left to wait then schedule + long aproxTimeLeftToWait = System.currentTimeMillis() - this.fTimeScheduled - this.fCurrentWaitTime; + if(this.fCurrentWaitTime == -1 || newWaitTime < aproxTimeLeftToWait) { + /* cancel if already waiting or sleeping so we can reschedule at smaller wait time + * if job is running this cancel will do nothing because this jobs implementation of #run + * is designed to ignore cancel + */ + this.cancel(); + + this.fCurrentWaitTime = newWaitTime; + this.fTimeScheduled = System.currentTimeMillis(); + + this.schedule(this.fCurrentWaitTime); + } + } + } + + /** + *

      Adds an runnable back to the list of runnables to be run. Helpful if an runnable + * still needs to wait longer before running.

      + * + * @return the given {@link PostponedRunnable} + */ + private void addAction(PostponedRunnable runnable) { + synchronized (LOCK) { + this.fRunnables.add(runnable); + } + + this.reSchedule(runnable.fDelay); + } + + /** + * @return true if there are runnables to be run, + * false if there are not. + */ + private boolean hasRunnablesToRun() { + return !this.fRunnables.isEmpty(); + } + + /** + *

      Creates a new list out of the existing runnables to run and then clears out + * {@link #fRunnables}.

      + * + *

      This avoids a lot of the problems that would be caused by + * allowing runnables to be added to the same list being processed by {@link #run(IProgressMonitor)}.

      + * + *

      IMPORTANT: Because calling this removes the returned list of runnables from the master + * list of runnables any runnables that are not run now need to be added back to the master list.

      + * + *

      NOTE: Because the list returned is a new list the caller does not need to worry about + * synchronization when using the returned result.

      + * + * @return a snap shot of the runnables to be run + */ + private List getRunnables() { + + List runnables = null; + synchronized (LOCK) { + //reset current wait time + this.fCurrentWaitTime = -1; + this.fTimeScheduled = -1; + + runnables = new ArrayList(this.fRunnables); + this.fRunnables.clear(); + } + + return runnables; + } + + /** + *

      Represents a single postponed runnable to be run after some amount of delay.

      + */ + private static class PostponedRunnable { + /**

      The runnable to run after {@link #fDelay}.

      */ + private final ISafeRunnable fRunnable; + + /**

      Delay to wait before running this runnable.

      */ + private final long fDelay; + + /**

      Time this runnable was created.

      */ + private final long fCreated; + + /** true if runnable canceled, false otherwise.

      */ + private boolean fCanceled; + + /** + *

      Creates an runnable to be run after a given delay.

      + * + * @param runnable to run after the given delay + * @param delay to wait before running the given runnable + */ + public PostponedRunnable(ISafeRunnable runnable, long delay) { + this.fRunnable = runnable; + this.fDelay = delay; + this.fCreated = System.currentTimeMillis(); + this.fCanceled = false; + } + + /** + * @return true
      if this runnable no longer needs to wait + * and can be run now, false if it still has more waiting to do + */ + protected boolean doneWaiting() { + return this.timeToWait() <= 0; + } + + /** + * @return amount of time to wait before this postponed runnable's delay is completed + */ + protected long timeToWait() { + return this.fDelay - (System.currentTimeMillis() - this.fCreated); + } + + /** + *

      Prevents this postponed runnable from running assuming its not already running. + * If it is already running this is a no op.

      + */ + protected void cancel() { + this.fCanceled = true; + } + + /** + * @return true if this postponed runnable has been canceled and thus + * should not run, false otherwise + */ + protected boolean isCanceled() { + return this.fCanceled; + } + + /** + *

      Runs this postponed runnable using a {@link SafeRunner} so that any errors it may have + * will not make this entire system explode.

      + */ + protected void run() { + SafeRunner.run(this.fRunnable); + } + } + } +} diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/InterpreterEngine.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/InterpreterEngine.java index b41fe98a..426a9182 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/InterpreterEngine.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/interpret/InterpreterEngine.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2009 IBM Corporation and others. + * Copyright (c) 2005, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -512,7 +512,7 @@ public class InterpreterEngine extends ASTVisitor implements Contants{ } public boolean visit(MethodDeclaration methodDeclaration, Scope scope) { FunctionValue func=new FunctionValue(methodDeclaration); - this.context.setValue(methodDeclaration.selector, func); + this.context.setValue(methodDeclaration.getName(), func); return false; } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/BasicSearchEngine.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/BasicSearchEngine.java index baa3bc4b..b6baa27f 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/BasicSearchEngine.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/BasicSearchEngine.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -10,8 +10,11 @@ *******************************************************************************/ package org.eclipse.wst.jsdt.internal.core.search; +import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; +import java.util.List; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; @@ -29,6 +32,7 @@ import org.eclipse.wst.jsdt.core.IPackageFragmentRoot; import org.eclipse.wst.jsdt.core.IType; import org.eclipse.wst.jsdt.core.JavaScriptCore; import org.eclipse.wst.jsdt.core.JavaScriptModelException; +import org.eclipse.wst.jsdt.core.Signature; import org.eclipse.wst.jsdt.core.WorkingCopyOwner; import org.eclipse.wst.jsdt.core.compiler.CharOperation; import org.eclipse.wst.jsdt.core.infer.InferredAttribute; @@ -44,7 +48,6 @@ import org.eclipse.wst.jsdt.core.search.TypeNameMatch; import org.eclipse.wst.jsdt.internal.compiler.ASTVisitor; import org.eclipse.wst.jsdt.internal.compiler.CompilationResult; import org.eclipse.wst.jsdt.internal.compiler.DefaultErrorHandlingPolicies; -import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode; import org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration; import org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration; @@ -55,7 +58,6 @@ import org.eclipse.wst.jsdt.internal.compiler.env.AccessRuleSet; import org.eclipse.wst.jsdt.internal.compiler.impl.CompilerOptions; import org.eclipse.wst.jsdt.internal.compiler.lookup.Binding; import org.eclipse.wst.jsdt.internal.compiler.lookup.BlockScope; -import org.eclipse.wst.jsdt.internal.compiler.lookup.ClassScope; import org.eclipse.wst.jsdt.internal.compiler.lookup.CompilationUnitScope; import org.eclipse.wst.jsdt.internal.compiler.lookup.Scope; import org.eclipse.wst.jsdt.internal.compiler.parser.Parser; @@ -65,22 +67,25 @@ import org.eclipse.wst.jsdt.internal.core.CompilationUnit; import org.eclipse.wst.jsdt.internal.core.DefaultWorkingCopyOwner; import org.eclipse.wst.jsdt.internal.core.JavaModelManager; import org.eclipse.wst.jsdt.internal.core.JavaProject; +import org.eclipse.wst.jsdt.internal.core.Logger; import org.eclipse.wst.jsdt.internal.core.search.indexing.IIndexConstants; import org.eclipse.wst.jsdt.internal.core.search.indexing.IndexManager; -import org.eclipse.wst.jsdt.internal.core.search.matching.ConstructorDeclarationPattern; +import org.eclipse.wst.jsdt.internal.core.search.matching.ConstructorPattern; import org.eclipse.wst.jsdt.internal.core.search.matching.DeclarationOfAccessedFieldsPattern; import org.eclipse.wst.jsdt.internal.core.search.matching.DeclarationOfReferencedMethodsPattern; import org.eclipse.wst.jsdt.internal.core.search.matching.DeclarationOfReferencedTypesPattern; +import org.eclipse.wst.jsdt.internal.core.search.matching.FieldPattern; import org.eclipse.wst.jsdt.internal.core.search.matching.JavaSearchPattern; import org.eclipse.wst.jsdt.internal.core.search.matching.LocalVariablePattern; import org.eclipse.wst.jsdt.internal.core.search.matching.MatchLocator; import org.eclipse.wst.jsdt.internal.core.search.matching.MethodPattern; import org.eclipse.wst.jsdt.internal.core.search.matching.MultiTypeDeclarationPattern; import org.eclipse.wst.jsdt.internal.core.search.matching.OrPattern; -import org.eclipse.wst.jsdt.internal.core.search.matching.QualifiedTypeDeclarationPattern; import org.eclipse.wst.jsdt.internal.core.search.matching.SecondaryTypeDeclarationPattern; import org.eclipse.wst.jsdt.internal.core.search.matching.TypeDeclarationPattern; +import org.eclipse.wst.jsdt.internal.core.search.processing.IJob; import org.eclipse.wst.jsdt.internal.core.util.Messages; +import org.eclipse.wst.jsdt.internal.core.util.QualificationHelpers; import org.eclipse.wst.jsdt.internal.core.util.Util; /** @@ -89,6 +94,7 @@ import org.eclipse.wst.jsdt.internal.core.util.Util; * Note that search basic engine does not implement depreciated functionalities... */ public class BasicSearchEngine { + private static final String GLOBAL_TYPE_SYMBOL = new String(IIndexConstants.GLOBAL_SYMBOL); /* * A default parser to parse non-reconciled working copies @@ -101,6 +107,11 @@ public class BasicSearchEngine { * compilation units. */ private IJavaScriptUnit[] workingCopies; + + /** + *

      Set of all of the working copies paths

      + */ + private HashSet fWorkingCopiesPaths; /* * A working copy owner whose working copies will take precedent over @@ -366,9 +377,9 @@ public class BasicSearchEngine { return this.parser; } - /* - * Returns the list of working copies used by this search engine. - * Returns null if none. + /** + * @return list of working copies used by this search engine, + * or null if none. */ private IJavaScriptUnit[] getWorkingCopies() { IJavaScriptUnit[] copies; @@ -425,6 +436,22 @@ public class BasicSearchEngine { } return result; } + + /** + * @return {@link HashSet} of all of the working copy paths + */ + private HashSet getWorkingCopiesPaths() { + if(this.fWorkingCopiesPaths == null) { + this.fWorkingCopiesPaths = new HashSet(); + + IJavaScriptUnit[] workingCopies = this.getWorkingCopies(); + for(int i = 0; workingCopies != null && i < workingCopies.length; ++i) { + this.fWorkingCopiesPaths.add(workingCopies[i].getPath().toString()); + } + } + + return this.fWorkingCopiesPaths; + } /* * Returns the list of working copies used to do the search on the given Java element. @@ -512,8 +539,7 @@ public class BasicSearchEngine { } findMatches(pattern, participants, scope, requestor, monitor); } - - + public void searchAllBindingNames( final char[] packageName, final char[] bindingName, @@ -546,9 +572,7 @@ public class BasicSearchEngine { suffix = IIndexConstants.CLASS_SUFFIX; searchPattern = new TypeDeclarationPattern( packageName, - null, // do find member types bindingName, - suffix, matchRule); break; @@ -557,7 +581,8 @@ public class BasicSearchEngine { case Binding.LOCAL : case Binding.FIELD : { - searchPattern = new LocalVariablePattern(true, false, false,bindingName, matchRule); + //searchPattern = new LocalVariablePattern(true, false, false,bindingName, matchRule); + searchPattern = new FieldPattern(true, false, false, true, bindingName, null, IIndexConstants.GLOBAL_SYMBOL, null, null, matchRule, null); } break; case Binding.METHOD: @@ -566,7 +591,7 @@ public class BasicSearchEngine { true,false,true, bindingName, null,null,null,null, - null,null,null, + null,IIndexConstants.GLOBAL_SYMBOL, matchRule); } @@ -578,27 +603,24 @@ public class BasicSearchEngine { searchPattern = new MethodPattern( true,false,true, bindingName, - null,null,null,null, - null,null,null, matchRule); } if ((bindingType & (Binding.VARIABLE |Binding.LOCAL |Binding.FIELD )) >0) { - LocalVariablePattern localVariablePattern = new LocalVariablePattern(true, false, false,bindingName, matchRule); + //LocalVariablePattern localVariablePattern = new LocalVariablePattern(true, false, false,bindingName, matchRule); + FieldPattern fieldPattern = new FieldPattern(true, false, false, true, bindingName, null, IIndexConstants.GLOBAL_SYMBOL, null, null, matchRule, null); if (searchPattern==null) - searchPattern=localVariablePattern; + searchPattern=fieldPattern; else - searchPattern=new OrPattern(searchPattern,localVariablePattern); + searchPattern=new OrPattern(searchPattern,fieldPattern); } if ((bindingType & Binding.TYPE) >0) { suffix = IIndexConstants.CLASS_SUFFIX; TypeDeclarationPattern typeDeclarationPattern = new TypeDeclarationPattern( packageName, - null, // do find member types bindingName, - suffix, matchRule); if (searchPattern==null) searchPattern=typeDeclarationPattern; @@ -610,24 +632,7 @@ public class BasicSearchEngine { final SearchPattern pattern =searchPattern; final char typeSuffix=suffix; - // Get working copy path(s). Store in a single string in case of only one to optimize comparison in requestor - final HashSet workingCopyPaths = new HashSet(); - String workingCopyPath = null; - IJavaScriptUnit[] copies = getWorkingCopies(); - final int copiesLength = copies == null ? 0 : copies.length; - if (copies != null) { - if (copiesLength == 1) { - workingCopyPath = copies[0].getPath().toString(); - } else { - for (int i = 0; i < copiesLength; i++) { - IJavaScriptUnit workingCopy = copies[i]; - workingCopyPaths.add(workingCopy.getPath().toString()); - } - } - } - final String singleWkcpPath = workingCopyPath; - - // Index requestor + // Index requester IndexQueryRequestor searchRequestor = new IndexQueryRequestor(){ public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant, AccessRuleSet access) { // Filter unexpected types @@ -691,6 +696,8 @@ public class BasicSearchEngine { progressMonitor == null ? null : new SubProgressMonitor(progressMonitor, 100)); // add type names from working copies + IJavaScriptUnit[] copies = getWorkingCopies(); + final int copiesLength = copies == null ? 0 : copies.length; if (copies != null && doParse) { for (int i = 0; i < copiesLength; i++) { IJavaScriptUnit workingCopy = copies[i]; @@ -705,14 +712,6 @@ public class BasicSearchEngine { IType[] allTypes = workingCopy.getAllTypes(); for (int j = 0, allTypesLength = allTypes.length; j < allTypesLength; j++) { IType type = allTypes[j]; - IJavaScriptElement parent = type.getParent(); - char[][] enclosingTypeNames; - if (parent instanceof IType) { - char[] parentQualifiedName = ((IType)parent).getTypeQualifiedName('.').toCharArray(); - enclosingTypeNames = CharOperation.splitOn('.', parentQualifiedName); - } else { - enclosingTypeNames = CharOperation.NO_CHAR_CHAR; - } char[] simpleName = type.getElementName().toCharArray(); int kind = TypeDeclaration.CLASS_DECL; @@ -726,16 +725,7 @@ public class BasicSearchEngine { IFunction[] allMethods = workingCopy.getFunctions(); for (int j = 0, allMethodsLength = allMethods.length; j < allMethodsLength; j++) { IFunction method = allMethods[j]; - IJavaScriptElement parent = method.getParent(); -// char[][] enclosingTypeNames; - if (parent instanceof IType) { -// char[] parentQualifiedName = ((IType)parent).getTypeQualifiedName('.').toCharArray(); -// enclosingTypeNames = CharOperation.splitOn('.', parentQualifiedName); - } else { -// enclosingTypeNames = CharOperation.NO_CHAR_CHAR; - } char[] simpleName = method.getElementName().toCharArray(); -// int kind; if (match(typeSuffix, packageName, bindingName, matchRule, 0, packageDeclaration, simpleName)) { nameRequestor.acceptBinding(bindingType,method.getFlags(), packageDeclaration, simpleName, path, null); } @@ -749,16 +739,7 @@ public class BasicSearchEngine { IField[] allFields = workingCopy.getFields (); for (int j = 0, allFieldsLength = allFields.length; j < allFieldsLength; j++) { IField field = allFields[j]; - IJavaScriptElement parent = field.getParent(); - char[][] enclosingTypeNames; - if (parent instanceof IType) { - char[] parentQualifiedName = ((IType)parent).getTypeQualifiedName('.').toCharArray(); - enclosingTypeNames = CharOperation.splitOn('.', parentQualifiedName); - } else { - enclosingTypeNames = CharOperation.NO_CHAR_CHAR; - } char[] simpleName = field.getElementName().toCharArray(); - int kind; if (match(typeSuffix, packageName, bindingName, matchRule, 0, packageDeclaration, simpleName)) { nameRequestor.acceptBinding(bindingType,field.getFlags(), packageDeclaration, simpleName, path, null); } @@ -793,30 +774,13 @@ public class BasicSearchEngine { return true; } public boolean visit(MethodDeclaration methodDeclaration, Scope scope) { - if (bindingType==Binding.METHOD && methodDeclaration.selector!=null && - match(typeSuffix, packageName, bindingName, matchRule,0, packageDeclaration, methodDeclaration.selector)) { - nameRequestor.acceptBinding(bindingType,methodDeclaration.modifiers, packageDeclaration, methodDeclaration.selector, path, null); + char[] methName = methodDeclaration.getName(); + if (bindingType==Binding.METHOD && methName!=null && + match(typeSuffix, packageName, bindingName, matchRule,0, packageDeclaration, methName)) { + nameRequestor.acceptBinding(bindingType,methodDeclaration.modifiers, packageDeclaration, methName, path, null); } return true; } -// public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope classScope) { -// if (match(typeSuffix, packageName, bindingName, matchRule, TypeDeclaration.kind(memberTypeDeclaration.modifiers), packageDeclaration, memberTypeDeclaration.name)) { -// // compute encloising type names -// TypeDeclaration enclosing = memberTypeDeclaration.enclosingType; -// char[][] enclosingTypeNames = CharOperation.NO_CHAR_CHAR; -// while (enclosing != null) { -// enclosingTypeNames = CharOperation.arrayConcat(new char[][] {enclosing.name}, enclosingTypeNames); -// if ((enclosing.bits & ASTNode.IsMemberType) != 0) { -// enclosing = enclosing.enclosingType; -// } else { -// enclosing = null; -// } -// } -// // report -// nameRequestor.acceptType(memberTypeDeclaration.modifiers, packageDeclaration, memberTypeDeclaration.name, enclosingTypeNames, path, null); -// } -// return true; -// } public boolean visit(InferredType inferredType, BlockScope scope) { if (bindingType==Binding.TYPE && match(typeSuffix, packageName, bindingName, matchRule, TypeDeclaration.kind(0), packageDeclaration, inferredType.getName())) { @@ -885,59 +849,33 @@ public class BasicSearchEngine { IndexManager indexManager = JavaModelManager.getJavaModelManager().getIndexManager(); final TypeDeclarationPattern pattern = new SecondaryTypeDeclarationPattern(); - // Get working copy path(s). Store in a single string in case of only one to optimize comparison in requestor - final HashSet workingCopyPaths = new HashSet(); - String workingCopyPath = null; - IJavaScriptUnit[] copies = getWorkingCopies(); - final int copiesLength = copies == null ? 0 : copies.length; - if (copies != null) { - if (copiesLength == 1) { - workingCopyPath = copies[0].getPath().toString(); - } else { - for (int i = 0; i < copiesLength; i++) { - IJavaScriptUnit workingCopy = copies[i]; - workingCopyPaths.add(workingCopy.getPath().toString()); - } - } - } - final String singleWkcpPath = workingCopyPath; + // Get working copy path(s). Store in a single string in case of only one to optimize comparison in requester + final HashSet workingCopyPaths = this.getWorkingCopiesPaths(); - // Index requestor + // Index requester IndexQueryRequestor searchRequestor = new IndexQueryRequestor(){ public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant, AccessRuleSet access) { // Filter unexpected types TypeDeclarationPattern record = (TypeDeclarationPattern)indexRecord; - if (!record.secondary) { - return true; // filter maint types - } + if (record.enclosingTypeNames == IIndexConstants.ONE_ZERO_CHAR) { return true; // filter out local and anonymous classes } - switch (copiesLength) { - case 0: - break; - case 1: - if (singleWkcpPath.equals(documentPath)) { - return true; // fliter out *the* working copy - } - break; - default: - if (workingCopyPaths.contains(documentPath)) { - return true; // filter out working copies - } - break; + + if (workingCopyPaths.contains(documentPath)) { + return true; // filter out working copies } // Accept document path AccessRestriction accessRestriction = null; if (access != null) { // Compute document relative path - int pkgLength = (record.pkg==null || record.pkg.length==0) ? 0 : record.pkg.length+1; + int pkgLength = (record.qualification==null || record.qualification.length==0) ? 0 : record.qualification.length+1; int nameLength = record.simpleName==null ? 0 : record.simpleName.length; char[] path = new char[pkgLength+nameLength]; int pos = 0; if (pkgLength > 0) { - System.arraycopy(record.pkg, 0, path, pos, pkgLength-1); + System.arraycopy(record.qualification, 0, path, pos, pkgLength-1); CharOperation.replace(path, '.', '/'); path[pkgLength-1] = '/'; pos += pkgLength; @@ -951,7 +889,7 @@ public class BasicSearchEngine { accessRestriction = access.getViolatedRestriction(path); } } - nameRequestor.acceptType(record.modifiers, record.pkg, record.simpleName, record.enclosingTypeNames, documentPath, accessRestriction); + nameRequestor.acceptType(record.modifiers, record.qualification, record.simpleName, record.superTypes, record.enclosingTypeNames, documentPath, accessRestriction); return true; } }; @@ -979,21 +917,51 @@ public class BasicSearchEngine { } } } + + /** + *

      Search for types using the given prefix. The prefix could be part of the + * qualification or simple name for a type, or it could be a camel case + * statement for a simple name of a type.

      + * + * @param prefix + * @param matchRule + * @param scope + * @param nameRequestor + * @param waitingPolicy + * @param progressMonitor + * @throws JavaScriptModelException + */ + public void searchAllTypeNames( + final char[] prefix, + final int matchRule, + IJavaScriptSearchScope scope, + final IRestrictedAccessTypeRequestor nameRequestor, + int waitingPolicy, + IProgressMonitor progressMonitor) throws JavaScriptModelException { + + // Create pattern + TypeDeclarationPattern pattern = new TypeDeclarationPattern(prefix, matchRule); + + this.searchAllTypeNames(pattern, scope, nameRequestor, waitingPolicy, progressMonitor); + } /** - * Searches for all top-level types and member types in the given scope. - * The search can be selecting specific types (given a package or a type name - * prefix and match modes). - * - * @see org.eclipse.wst.jsdt.core.search.SearchEngine#searchAllTypeNames(char[], int, char[], int, int, IJavaScriptSearchScope, org.eclipse.wst.jsdt.core.search.TypeNameRequestor, int, IProgressMonitor) - * for detailed comment + *

      Search for a type with a specific qualification and simple name

      + * + * @param qualification + * @param qualificationMatchRule + * @param simpleTypeName + * @param matchRule + * @param scope + * @param nameRequestor + * @param waitingPolicy + * @param progressMonitor + * @throws JavaScriptModelException */ public void searchAllTypeNames( - final char[] packageName, - final int packageMatchRule, - final char[] typeName, - final int typeMatchRule, - int searchFor, + final char[] qualification, + final char[] simpleTypeName, + final int matchRule, IJavaScriptSearchScope scope, final IRestrictedAccessTypeRequestor nameRequestor, int waitingPolicy, @@ -1001,92 +969,101 @@ public class BasicSearchEngine { if (VERBOSE) { Util.verbose("BasicSearchEngine.searchAllTypeNames(char[], char[], int, int, IJavaScriptSearchScope, IRestrictedAccessTypeRequestor, int, IProgressMonitor)"); //$NON-NLS-1$ - Util.verbose(" - package name: "+(packageName==null?"null":new String(packageName))); //$NON-NLS-1$ //$NON-NLS-2$ - Util.verbose(" - match rule: "+getMatchRuleString(packageMatchRule)); //$NON-NLS-1$ - Util.verbose(" - type name: "+(typeName==null?"null":new String(typeName))); //$NON-NLS-1$ //$NON-NLS-2$ - Util.verbose(" - match rule: "+getMatchRuleString(typeMatchRule)); //$NON-NLS-1$ - Util.verbose(" - search for: "+searchFor); //$NON-NLS-1$ + Util.verbose(" - package name: "+(qualification==null?"null":new String(qualification))); //$NON-NLS-1$ //$NON-NLS-2$ + Util.verbose(" - type name: "+(simpleTypeName==null?"null":new String(simpleTypeName))); //$NON-NLS-1$ //$NON-NLS-2$ + Util.verbose(" - match rule: "+getMatchRuleString(matchRule)); //$NON-NLS-1$ Util.verbose(" - scope: "+scope); //$NON-NLS-1$ } // Create pattern - IndexManager indexManager = JavaModelManager.getJavaModelManager().getIndexManager(); - final char typeSuffix; - switch(searchFor){ - case IJavaScriptSearchConstants.CLASS : - typeSuffix = IIndexConstants.CLASS_SUFFIX; - break; - default : - typeSuffix = IIndexConstants.TYPE_SUFFIX; - break; + TypeDeclarationPattern pattern = new TypeDeclarationPattern( + qualification, + simpleTypeName, + matchRule); + + this.searchAllTypeNames(pattern, scope, nameRequestor, waitingPolicy, progressMonitor); + } + + /** + *

      Search for multiple types with specific qualifications and simple type names.

      + * + * @param qualifications + * @param simpleTypeNames + * @param matchRule + * @param scope + * @param nameRequestor + * @param waitingPolicy + * @param progressMonitor + * @throws JavaScriptModelException + */ + public void searchAllTypeNames( + final char[][] qualifications, + final char[][] simpleTypeNames, + final int matchRule, + IJavaScriptSearchScope scope, + final IRestrictedAccessTypeRequestor nameRequestor, + int waitingPolicy, + IProgressMonitor progressMonitor) throws JavaScriptModelException { + + if (VERBOSE) { + Util.verbose("BasicSearchEngine.searchAllTypeNames(char[][], char[][], int, int, IJavaScriptSearchScope, IRestrictedAccessTypeRequestor, int, IProgressMonitor)"); //$NON-NLS-1$ + Util.verbose(" - package name: "+(qualifications==null?"null":new String(CharOperation.concatWith(qualifications, ',')))); //$NON-NLS-1$ //$NON-NLS-2$ + Util.verbose(" - type name: "+(simpleTypeNames==null?"null":new String(CharOperation.concatWith(simpleTypeNames, ',')))); //$NON-NLS-1$ //$NON-NLS-2$ + Util.verbose(" - match rule: "+matchRule); //$NON-NLS-1$ + Util.verbose(" - scope: "+scope); //$NON-NLS-1$ } - final TypeDeclarationPattern pattern = packageMatchRule == SearchPattern.R_EXACT_MATCH - ? new TypeDeclarationPattern( - packageName, - null, - typeName, - typeSuffix, - typeMatchRule) - : new QualifiedTypeDeclarationPattern( - packageName, - packageMatchRule, - typeName, - typeSuffix, - typeMatchRule); + + MultiTypeDeclarationPattern pattern = new MultiTypeDeclarationPattern( + qualifications, simpleTypeNames, matchRule); + this.searchAllTypeNames(pattern, scope, nameRequestor, waitingPolicy, progressMonitor); + } + + /** + *

      Used to search for types using a given pattern.

      + * + * @param pattern + * @param scope + * @param nameRequestor + * @param waitingPolicy + * @param progressMonitor + * @throws JavaScriptModelException + */ + private void searchAllTypeNames( + final TypeDeclarationPattern pattern, + IJavaScriptSearchScope scope, + final IRestrictedAccessTypeRequestor nameRequestor, + int waitingPolicy, + IProgressMonitor progressMonitor) throws JavaScriptModelException { // Get working copy path(s). Store in a single string in case of only one to optimize comparison in requestor - final HashSet workingCopyPaths = new HashSet(); - String workingCopyPath = null; - IJavaScriptUnit[] copies = getWorkingCopies(); - final int copiesLength = copies == null ? 0 : copies.length; - if (copies != null) { - if (copiesLength == 1) { - workingCopyPath = copies[0].getPath().toString(); - } else { - for (int i = 0; i < copiesLength; i++) { - IJavaScriptUnit workingCopy = copies[i]; - workingCopyPaths.add(workingCopy.getPath().toString()); - } - } - } - final String singleWkcpPath = workingCopyPath; + final HashSet workingCopyPaths = this.getWorkingCopiesPaths(); // Index requestor IndexQueryRequestor searchRequestor = new IndexQueryRequestor(){ public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant, AccessRuleSet access) { // Filter unexpected types - TypeDeclarationPattern record = (TypeDeclarationPattern)indexRecord; + TypeDeclarationPattern record = (TypeDeclarationPattern) indexRecord; if (record.enclosingTypeNames == IIndexConstants.ONE_ZERO_CHAR) { return true; // filter out local and anonymous classes } - switch (copiesLength) { - case 0: - break; - case 1: - if (singleWkcpPath.equals(documentPath)) { - return true; // fliter out *the* working copy - } - break; - default: - if (workingCopyPaths.contains(documentPath)) { - return true; // filter out working copies - } - break; + + if (workingCopyPaths.contains(documentPath)) { + return true; // filter out working copies } // Accept document path AccessRestriction accessRestriction = null; if (access != null) { // Compute document relative path - int pkgLength = (record.pkg==null || record.pkg.length==0) ? 0 : record.pkg.length+1; - int nameLength = record.simpleName==null ? 0 : record.simpleName.length; - char[] path = new char[pkgLength+nameLength]; + int qualificationLength = (record.qualification == null || record.qualification.length == 0) ? 0 : record.qualification.length + 1; + int nameLength = record.simpleName == null ? 0 : record.simpleName.length; + char[] path = new char[qualificationLength + nameLength]; int pos = 0; - if (pkgLength > 0) { - System.arraycopy(record.pkg, 0, path, pos, pkgLength-1); + if (qualificationLength > 0) { + System.arraycopy(record.qualification, 0, path, pos, qualificationLength - 1); CharOperation.replace(path, '.', '/'); - path[pkgLength-1] = '/'; - pos += pkgLength; + path[qualificationLength-1] = '/'; + pos += qualificationLength; } if (nameLength > 0) { System.arraycopy(record.simpleName, 0, path, pos, nameLength); @@ -1097,9 +1074,7 @@ public class BasicSearchEngine { accessRestriction = access.getViolatedRestriction(path); } } - if (match(record.typeSuffix, record.modifiers)) { - nameRequestor.acceptType(record.modifiers, record.pkg, record.simpleName, record.enclosingTypeNames, documentPath, accessRestriction); - } + nameRequestor.acceptType(record.modifiers, record.qualification, record.simpleName, record.superTypes, record.enclosingTypeNames, documentPath, accessRestriction); return true; } }; @@ -1109,6 +1084,7 @@ public class BasicSearchEngine { progressMonitor.beginTask(Messages.engine_searching, 100); } // add type names from indexes + IndexManager indexManager = JavaModelManager.getJavaModelManager().getIndexManager(); indexManager.performConcurrentJob( new PatternSearchJob( pattern, @@ -1119,97 +1095,47 @@ public class BasicSearchEngine { progressMonitor == null ? null : new SubProgressMonitor(progressMonitor, 100)); // add type names from working copies + IJavaScriptUnit[] copies = this.getWorkingCopies(); if (copies != null) { - for (int i = 0; i < copiesLength; i++) { + final int matchRule = pattern.getMatchRule(); + for (int i = 0; i < copies.length; i++) { final IJavaScriptUnit workingCopy = copies[i]; if (!scope.encloses(workingCopy)) continue; final String path = workingCopy.getPath().toString(); - if (workingCopy.isConsistent()) { - char[] packageDeclaration = CharOperation.NO_CHAR; - IType[] allTypes = workingCopy.getAllTypes(); - for (int j = 0, allTypesLength = allTypes.length; j < allTypesLength; j++) { - IType type = allTypes[j]; - IJavaScriptElement parent = type.getParent(); - char[][] enclosingTypeNames; - if (parent instanceof IType) { - char[] parentQualifiedName = ((IType)parent).getTypeQualifiedName('.').toCharArray(); - enclosingTypeNames = CharOperation.splitOn('.', parentQualifiedName); - } else { - enclosingTypeNames = CharOperation.NO_CHAR_CHAR; - } - char[] simpleName = type.getElementName().toCharArray(); - int kind = TypeDeclaration.CLASS_DECL; - - if (match(typeSuffix, packageName, typeName, typeMatchRule, kind, packageDeclaration, simpleName)) { - if (nameRequestor instanceof TypeNameMatchRequestorWrapper) { - ((TypeNameMatchRequestorWrapper)nameRequestor).requestor.acceptTypeNameMatch(new JavaSearchTypeNameMatch(type, type.getFlags())); - } else { - nameRequestor.acceptType(type.getFlags(), packageDeclaration, simpleName, enclosingTypeNames, path, null); - } - } + + //make the working copy consistent if it is not + if(!workingCopy.isConsistent()) { + workingCopy.makeConsistent(progressMonitor); + } + + //search all types in the working copy + IType[] allTypes = workingCopy.getAllTypes(); + for (int j = 0, allTypesLength = allTypes.length; j < allTypesLength; j++) { + IType type = allTypes[j]; + + //get type name + char[] wcTypeQualification = null; + char[] wcTypeSimpleName = null; + char[] wcTypeFullName = type.getTypeQualifiedName().toCharArray(); + if(type.getTypeQualifiedName() != null) { + char[][] wcSeperatedDeclaringType = QualificationHelpers.seperateFullyQualifedName(wcTypeFullName); + wcTypeQualification = wcSeperatedDeclaringType[QualificationHelpers.QULIFIERS_INDEX]; + wcTypeSimpleName = wcSeperatedDeclaringType[QualificationHelpers.SIMPLE_NAMES_INDEX]; } - } else { - Parser basicParser = getParser(); - org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit unit = (org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit) workingCopy; - CompilationResult compilationUnitResult = new CompilationResult(unit, 0, 0, this.compilerOptions.maxProblemsPerUnit); - CompilationUnitDeclaration parsedUnit = basicParser.dietParse(unit, compilationUnitResult); - if (parsedUnit != null) { - basicParser.inferTypes(parsedUnit, null); - final char[] packageDeclaration = parsedUnit.currentPackage == null ? CharOperation.NO_CHAR : CharOperation.concatWith(parsedUnit.currentPackage.getImportName(), '.'); - class AllTypeDeclarationsVisitor extends ASTVisitor { - public boolean visit(TypeDeclaration typeDeclaration, BlockScope blockScope) { - return false; // no local/anonymous type + + if(wcTypeSimpleName != null) { + TypeDeclarationPattern wcPattern = new TypeDeclarationPattern(wcTypeQualification, wcTypeSimpleName, matchRule); + if (pattern.matchesDecodedKey(wcPattern)) { + char[][] superTypes = CharOperation.NO_CHAR_CHAR; + try { + String superType = type.getSuperclassName(); + superTypes = new char[][]{superType.toCharArray()}; } - public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope compilationUnitScope) { - if (match(typeSuffix, packageName, typeName, typeMatchRule, TypeDeclaration.kind(typeDeclaration.modifiers), packageDeclaration, typeDeclaration.name)) { - if (nameRequestor instanceof TypeNameMatchRequestorWrapper) { - IType type = workingCopy.getType(new String(typeName)); - ((TypeNameMatchRequestorWrapper)nameRequestor).requestor.acceptTypeNameMatch(new JavaSearchTypeNameMatch(type, typeDeclaration.modifiers)); - } else { - nameRequestor.acceptType(typeDeclaration.modifiers, packageDeclaration, typeDeclaration.name, CharOperation.NO_CHAR_CHAR, path, null); - } - } - return true; - } - public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope classScope) { - if (match(typeSuffix, packageName, typeName, typeMatchRule, TypeDeclaration.kind(memberTypeDeclaration.modifiers), packageDeclaration, memberTypeDeclaration.name)) { - // compute encloising type names - TypeDeclaration enclosing = memberTypeDeclaration.enclosingType; - char[][] enclosingTypeNames = CharOperation.NO_CHAR_CHAR; - while (enclosing != null) { - enclosingTypeNames = CharOperation.arrayConcat(new char[][] {enclosing.name}, enclosingTypeNames); - if ((enclosing.bits & ASTNode.IsMemberType) != 0) { - enclosing = enclosing.enclosingType; - } else { - enclosing = null; - } - } - // report - if (nameRequestor instanceof TypeNameMatchRequestorWrapper) { - IType type = workingCopy.getType(new String(enclosingTypeNames[0])); - for (int j=1, l=enclosingTypeNames.length; j 0) { - System.arraycopy(record.qualification, 0, path, pos, qualificationLength - 1); - CharOperation.replace(path, '.', '/'); - path[qualificationLength-1] = '/'; - pos += qualificationLength; + if(!workingCopiesPaths.contains(documentPath)) { + if (indexRecord instanceof MethodPattern) { + MethodPattern record = (MethodPattern) indexRecord; + requestor.acceptFunction(record.selector, + record.getDeclaringQualification(), + record.getDeclaringSimpleName(), + documentPath); } - if (nameLength > 0) { - System.arraycopy(record.simpleName, 0, path, pos, nameLength); - pos += nameLength; + else if (indexRecord instanceof FieldPattern) { + FieldPattern record = (FieldPattern) indexRecord; + requestor.acceptField(record.name, + record.getDeclaringQualification(), + record.getDeclaringSimpleName(), + documentPath); } - // Update access restriction if path is not empty - if (pos > 0) { - accessRestriction = access.getViolatedRestriction(path); + else if (indexRecord instanceof TypeDeclarationPattern) { + TypeDeclarationPattern record = (TypeDeclarationPattern) indexRecord; + requestor.acceptType(record.qualification, + record.simpleName, + documentPath); } } - nameRequestor.acceptType(record.modifiers, record.pkg, record.simpleName, record.enclosingTypeNames, documentPath, accessRestriction); return true; } }; + // Find matches from index + IndexManager indexManager = JavaModelManager.getJavaModelManager().getIndexManager(); try { - if (progressMonitor != null) { - progressMonitor.beginTask(Messages.engine_searching, 100); + if (monitor != null) { + monitor.beginTask(Messages.engine_searching, 1000); } - // add type names from indexes - indexManager.performConcurrentJob( - new PatternSearchJob( - pattern, - getDefaultSearchParticipant(), // Java search only - scope, - searchRequestor), - waitingPolicy, - progressMonitor == null ? null : new SubProgressMonitor(progressMonitor, 100)); - // add type names from working copies - if (copies != null) { - for (int i = 0, length = copies.length; i < length; i++) { - IJavaScriptUnit workingCopy = copies[i]; - final String path = workingCopy.getPath().toString(); - if (workingCopy.isConsistent()) { - char[] packageDeclaration = CharOperation.NO_CHAR; - IType[] allTypes = workingCopy.getAllTypes(); - for (int j = 0, allTypesLength = allTypes.length; j < allTypesLength; j++) { - IType type = allTypes[j]; - IJavaScriptElement parent = type.getParent(); - char[][] enclosingTypeNames; - char[] qualification = packageDeclaration; - if (parent instanceof IType) { - char[] parentQualifiedName = ((IType)parent).getTypeQualifiedName('.').toCharArray(); - enclosingTypeNames = CharOperation.splitOn('.', parentQualifiedName); - qualification = CharOperation.concat(qualification, parentQualifiedName); - } else { - enclosingTypeNames = CharOperation.NO_CHAR_CHAR; - } - char[] simpleName = type.getElementName().toCharArray(); - char suffix = IIndexConstants.TYPE_SUFFIX; - if (type.isClass()) { - suffix = IIndexConstants.CLASS_SUFFIX; + indexManager.performConcurrentJob(new PatternSearchJob( + pattern, + getDefaultSearchParticipant(), // JavaScript search only + scope, + queryRequestor), + IJavaScriptSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, + monitor == null ? null : new SubProgressMonitor(monitor, 1000)); + + SearchPattern typePattern = null; + SearchPattern fieldPattern = null; + SearchPattern methodPattern = null; + + if (pattern instanceof OrPattern) { + typePattern = ((OrPattern) pattern).findPatternKind(IIndexConstants.TYPE_DECL_PATTERN); + methodPattern = ((OrPattern) pattern).findPatternKind(IIndexConstants.METHOD_PATTERN); + fieldPattern = ((OrPattern) pattern).findPatternKind(IIndexConstants.FIELD_PATTERN); + } else if (pattern instanceof TypeDeclarationPattern) { + typePattern = pattern; + } else if (pattern instanceof FieldPattern) { + fieldPattern = pattern; + } else if (pattern instanceof MethodPattern) { + methodPattern = pattern; + } + + // find matches from working copies + IJavaScriptUnit[] workingCopies = this.getWorkingCopies(); + for (int w = 0; workingCopies != null && w < workingCopies.length; w++) { + final IJavaScriptUnit workingCopy = workingCopies[w]; + + //skip this working copy if not in the scope + if (!scope.encloses(workingCopy)) { + continue; + } + + try { + //make the working copy consistent if it is not + if (!workingCopy.isConsistent()) { + workingCopy.makeConsistent(monitor); + } + + //check each each type in the working copy for a match + IType[] types = workingCopy.getAllTypes(); + for (int t = 0; t < types.length; t++) { + IType type = types[t]; + if (typePattern != null && !type.isAnonymous()) { + //get type name + char[] wcTypeSimpleName = null; + char[] wcTypeQualification = null; + if (type.getTypeQualifiedName() != null) { + char[][] wcSeperatedDeclaringType = QualificationHelpers.seperateFullyQualifedName(type.getTypeQualifiedName().toCharArray()); + wcTypeQualification = wcSeperatedDeclaringType[QualificationHelpers.QULIFIERS_INDEX]; + wcTypeSimpleName = wcSeperatedDeclaringType[QualificationHelpers.SIMPLE_NAMES_INDEX]; } - if (pattern.matchesDecodedKey(new QualifiedTypeDeclarationPattern(qualification, simpleName, suffix, matchRule))) { - nameRequestor.acceptType(type.getFlags(), packageDeclaration, simpleName, enclosingTypeNames, path, null); + + if (wcTypeSimpleName != null) { + TypeDeclarationPattern wcPattern = new TypeDeclarationPattern(wcTypeQualification, wcTypeSimpleName, pattern.getMatchRule()); + if (typePattern.matchesDecodedKey(wcPattern)) { + requestor.acceptType(type); + } } } - } else { - Parser basicParser = getParser(); - org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit unit = (org.eclipse.wst.jsdt.internal.compiler.env.ICompilationUnit) workingCopy; - CompilationResult compilationUnitResult = new CompilationResult(unit, 0, 0, this.compilerOptions.maxProblemsPerUnit); - CompilationUnitDeclaration parsedUnit = basicParser.dietParse(unit, compilationUnitResult); - if (parsedUnit != null) { - basicParser.inferTypes(parsedUnit, null); - final char[] packageDeclaration = parsedUnit.currentPackage == null - ? CharOperation.NO_CHAR - : CharOperation.concatWith(parsedUnit.currentPackage.getImportName(), '.'); - class AllTypeDeclarationsVisitor extends ASTVisitor { - public boolean visit(TypeDeclaration typeDeclaration, BlockScope blockScope) { - return false; // no local/anonymous type + if (methodPattern != null) { + IFunction[] allFunctions = type.getFunctions(); + for (int f = 0; f < allFunctions.length; f++) { + IFunction function = allFunctions[f]; + //selector must not be null for it to be a match + char[] wcSelector = null; + if (function.getElementName() != null) { + wcSelector = function.getElementName().toCharArray(); } - public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope compilationUnitScope) { - SearchPattern decodedPattern = - new QualifiedTypeDeclarationPattern(packageDeclaration, typeDeclaration.name, convertTypeKind(TypeDeclaration.kind(typeDeclaration.modifiers)), matchRule); - if (pattern.matchesDecodedKey(decodedPattern)) { - nameRequestor.acceptType(typeDeclaration.modifiers, packageDeclaration, typeDeclaration.name, CharOperation.NO_CHAR_CHAR, path, null); - } - return true; + char[] wcDeclaringTypeSimpleName = null; + char[] wcDeclaringTypeQualification = null; + if (function.getDeclaringType() != null && function.getDeclaringType().getTypeQualifiedName() != null) { + char[] wcDeclaringType = function.getDeclaringType().getTypeQualifiedName().toCharArray(); + char[][] wcSeperatedDeclaringType = QualificationHelpers.seperateFullyQualifedName(wcDeclaringType); + wcDeclaringTypeQualification = wcSeperatedDeclaringType[QualificationHelpers.QULIFIERS_INDEX]; + wcDeclaringTypeSimpleName = wcSeperatedDeclaringType[QualificationHelpers.SIMPLE_NAMES_INDEX]; } - public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope classScope) { - // compute encloising type names - char[] qualification = packageDeclaration; - TypeDeclaration enclosing = memberTypeDeclaration.enclosingType; - char[][] enclosingTypeNames = CharOperation.NO_CHAR_CHAR; - while (enclosing != null) { - qualification = CharOperation.concat(qualification, enclosing.name, '.'); - enclosingTypeNames = CharOperation.arrayConcat(new char[][] {enclosing.name}, enclosingTypeNames); - if ((enclosing.bits & ASTNode.IsMemberType) != 0) { - enclosing = enclosing.enclosingType; - } else { - enclosing = null; - } + if (wcSelector != null) { + MethodPattern wcPattern = new MethodPattern(true, false, false, wcSelector, null, null, null, null, + wcDeclaringTypeQualification, wcDeclaringTypeSimpleName, pattern.getMatchRule()); + //if working copy function matches the search pattern then accept the function + if (methodPattern.matchesDecodedKey(wcPattern)) { + requestor.acceptFunction(function); } - SearchPattern decodedPattern = - new QualifiedTypeDeclarationPattern(qualification, memberTypeDeclaration.name, convertTypeKind(TypeDeclaration.kind(memberTypeDeclaration.modifiers)), matchRule); - if (pattern.matchesDecodedKey(decodedPattern)) { - nameRequestor.acceptType(memberTypeDeclaration.modifiers, packageDeclaration, memberTypeDeclaration.name, enclosingTypeNames, path, null); - } - return true; } - public boolean visit(InferredType inferredType, BlockScope scope) { - SearchPattern decodedPattern = - new QualifiedTypeDeclarationPattern(packageDeclaration, inferredType.getName(), convertTypeKind(TypeDeclaration.kind(0)), matchRule); - if (pattern.matchesDecodedKey(decodedPattern)) { - nameRequestor.acceptType(0, packageDeclaration, inferredType.getName(), CharOperation.NO_CHAR_CHAR, path, null); + } + } + if (fieldPattern != null) { + IField[] allFields = type.getFields(); + for (int i = 0; i < allFields.length; i++) { + IField field = allFields[i]; + //selector must not be null for it to be a match + char[] wcName = null; + if (field.getElementName() != null) { + wcName = field.getElementName().toCharArray(); + } + char[] wcDeclaringTypeSimpleName = null; + char[] wcDeclaringTypeQualification = null; + if (field.getDeclaringType() != null && field.getDeclaringType().getTypeQualifiedName() != null) { + char[] wcDeclaringType = field.getDeclaringType().getTypeQualifiedName().toCharArray(); + char[][] wcSeperatedDeclaringType = QualificationHelpers.seperateFullyQualifedName(wcDeclaringType); + wcDeclaringTypeQualification = wcSeperatedDeclaringType[QualificationHelpers.QULIFIERS_INDEX]; + wcDeclaringTypeSimpleName = wcSeperatedDeclaringType[QualificationHelpers.SIMPLE_NAMES_INDEX]; + } + if (wcName != null) { + //create a pattern from the working copy field + FieldPattern wcPattern = new FieldPattern(true, false, false, + wcName, wcDeclaringTypeQualification, wcDeclaringTypeSimpleName, pattern.getMatchRule()); + if (fieldPattern.matchesDecodedKey(wcPattern)) { + requestor.acceptField(field); } - return true; } - } - parsedUnit.traverse(new AllTypeDeclarationsVisitor(), parsedUnit.scope); + } } } + } catch(JavaScriptModelException e) { + Logger.logException("Error while processing working copy", e); } } } finally { - if (progressMonitor != null) { - progressMonitor.done(); + if (monitor != null) { + monitor.done(); } } } + public void searchDeclarations(IJavaScriptElement enclosingElement, SearchRequestor requestor, SearchPattern pattern, IProgressMonitor monitor) throws JavaScriptModelException { if (VERBOSE) { Util.verbose(" - java element: "+enclosingElement); //$NON-NLS-1$ @@ -1540,10 +1420,10 @@ public class BasicSearchEngine { *

      Used to search all constructor declarations for ones that match the given type name using the given role, * in the given scope, reporting to the given requester.

      * - * @param typeNamePattern type name pattern to search for + * @param prefix constructor prefix to search for * @param typeMatchRule Search pattern matching rule to use with the given typeNamePattern * @param scope scope of the search - * @param nameRequester requester to report findings to + * @param requestor requester to report findings to * @param waitingPolicy Policy to use when waiting for the index * @param progressMonitor monitor to report index search progress to * @@ -1561,63 +1441,68 @@ public class BasicSearchEngine { * @see IJavaScriptSearchConstants#WAIT_UNTIL_READY_TO_SEARCH */ public void searchAllConstructorDeclarations( - final char[] typeNamePattern, + final char[] prefix, final int typeMatchRule, IJavaScriptSearchScope scope, - final IConstructorRequestor nameRequester, + final IConstructorRequestor requestor, int waitingPolicy, IProgressMonitor progressMonitor) { // Debug if (VERBOSE) { Util.verbose("BasicSearchEngine.searchAllConstructorDeclarations(char[], char[], int, IJavaSearchScope, IRestrictedAccessConstructorRequestor, int, IProgressMonitor)"); //$NON-NLS-1$ - Util.verbose(" - type name: "+(typeNamePattern==null?"null":new String(typeNamePattern))); //$NON-NLS-1$ //$NON-NLS-2$ + Util.verbose(" - type name: "+(prefix==null?"null":new String(prefix))); //$NON-NLS-1$ //$NON-NLS-2$ Util.verbose(" - type match rule: "+getMatchRuleString(typeMatchRule)); //$NON-NLS-1$ Util.verbose(" - scope: "+scope); //$NON-NLS-1$ } // Create pattern IndexManager indexManager = JavaModelManager.getJavaModelManager().getIndexManager(); - final ConstructorDeclarationPattern pattern = new ConstructorDeclarationPattern( - typeNamePattern, + final ConstructorPattern pattern = new ConstructorPattern( + prefix, typeMatchRule); // Index requester + final HashSet workingCopiesPaths = this.getWorkingCopiesPaths(); IndexQueryRequestor searchRequestor = new IndexQueryRequestor(){ public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant, AccessRuleSet access) { // Filter unexpected types - ConstructorDeclarationPattern record = (ConstructorDeclarationPattern)indexRecord; + ConstructorPattern record = (ConstructorPattern)indexRecord; - - // Accept document path - AccessRestriction accessRestriction = null; - if (access != null) { - // Compute document relative path - int nameLength = record.declaringSimpleName==null ? 0 : record.declaringSimpleName.length; - char[] path = new char[nameLength]; - int pos = 0; - - if (nameLength > 0) { - System.arraycopy(record.declaringSimpleName, 0, path, pos, nameLength); - pos += nameLength; - } - // Update access restriction if path is not empty - if (pos > 0) { - accessRestriction = access.getViolatedRestriction(path); + //do not accept matches from files that have working copies open + if(!workingCopiesPaths.contains(documentPath)) { + // Accept document path + AccessRestriction accessRestriction = null; + if (access != null) { + // Compute document relative path + int nameLength = record.declaringSimpleName==null ? 0 : record.declaringSimpleName.length; + char[] path = new char[nameLength]; + int pos = 0; + + if (nameLength > 0) { + System.arraycopy(record.declaringSimpleName, 0, path, pos, nameLength); + pos += nameLength; + } + // Update access restriction if path is not empty + if (pos > 0) { + accessRestriction = access.getViolatedRestriction(path); + } } + requestor.acceptConstructor( + record.modifiers, + QualificationHelpers.createFullyQualifiedName( + record.declaringQualification, record.declaringSimpleName), + record.parameterNames == null ? 0 : record.parameterNames.length, + record.getFullyQualifiedParameterTypeNames(), + record.parameterNames, + documentPath, + accessRestriction); } - nameRequester.acceptConstructor( - record.modifiers, - record.declaringSimpleName, - record.parameterCount, - record.parameterTypes, - record.parameterNames, - documentPath, - accessRestriction); return true; } }; + //find constructor matches from index try { if (progressMonitor != null) { progressMonitor.beginTask(Messages.engine_searching, 1000); @@ -1636,5 +1521,444 @@ public class BasicSearchEngine { progressMonitor.done(); } } + + // find constructor matches from working copies + IJavaScriptUnit[] workingCopies = this.getWorkingCopies(); + for (int w = 0; workingCopies != null && w < workingCopies.length; w++) { + final IJavaScriptUnit workingCopy = workingCopies[w]; + + //skip this working copy if not in the scope + if(!scope.encloses(workingCopy)) { + continue; + } + + try { + //make the working copy consistent if it is not + if(!workingCopy.isConsistent()) { + workingCopy.makeConsistent(progressMonitor); + } + + //check each constructor in each type in the working copy for a match + IType[] types = workingCopy.getAllTypes(); + for(int t = 0; t < types.length; ++t) { + IType type = types[t]; + + //get type name + char[] wcTypeQualification = null; + char[] wcTypeSimpleName = null; + char[] wcTypeFullName = type.getTypeQualifiedName().toCharArray(); + if(type.getTypeQualifiedName() != null) { + char[][] wcSeperatedDeclaringType = QualificationHelpers.seperateFullyQualifedName(wcTypeFullName); + wcTypeQualification = wcSeperatedDeclaringType[QualificationHelpers.QULIFIERS_INDEX]; + wcTypeSimpleName = wcSeperatedDeclaringType[QualificationHelpers.SIMPLE_NAMES_INDEX]; + } + + if(wcTypeSimpleName != null) { + //if working type matches the pattern then propose its constructor + ConstructorPattern wcPattern = new ConstructorPattern( + wcTypeQualification, wcTypeSimpleName, typeMatchRule); + if(pattern.matchesDecodedKey(wcPattern)) { + IFunction[] allFunctions = type.getFunctions(); + for (int f = 0; f < allFunctions.length; ++f) { + IFunction function = allFunctions[f]; + + //if the function is a constructor propose it + if(function.isConstructor()) { + //figure out parameter names and types + String[] wcParameterNames = function.getParameterNames(); + char[][] wcParameterTypes = QualificationHelpers.stringArrayToCharArray(function.getParameterTypes()); + for(int i = 0; i < wcParameterTypes.length; ++i) { + try { + wcParameterTypes[i] = Signature.toCharArray(wcParameterTypes[i]); + } catch(IllegalArgumentException e) { + /* ignore, this will happen if a name looking like it maybe a signature gets passed in, but isn't, such as "QName" + * the real future fix for this should be to completely stop using signatures + */ + } + } + + //accept the constructor + requestor.acceptConstructor( + function.getFlags(), + wcTypeFullName, + wcParameterNames == null ? 0 : wcParameterNames.length, + wcParameterTypes, + QualificationHelpers.stringArrayToCharArray(wcParameterNames), + workingCopy.getPath().toString(), + null); + } + } + } + } + } + } catch(JavaScriptModelException e) { + Logger.logException("Error while processing working copy", e); //$NON-NLS-1$ + } + } + } + + /** + *

      Searches for all methods in the index and working copies.

      + * + * @param functionRequester requester to report results to + * @param selectorPattern selector pattern that the results need to match + * @param declaringType type that all results must be defined on + * @param selectorPatternMatchRule the match rule used with the given selectorPattern + * @param scope of the search + * @param waitingPolicy policy to use when waiting for the index to index + * @param progressMonitor monitor to report status too + * + * @see SearchPattern + * + * @see IJob#ForceImmediate + * @see IJob#CancelIfNotReady + * @see IJob#WaitUntilReady + */ + public void searchAllFunctions(final IFunctionRequester functionRequester, + char[] selectorPattern, char[][] declaringTypes, final int selectorPatternMatchRule, + IJavaScriptSearchScope scope, + int waitingPolicy, IProgressMonitor progressMonitor) { + + //pattern for searching the index and working copies + final MethodPattern searchPattern = new MethodPattern(true, false, + selectorPattern, declaringTypes, selectorPatternMatchRule); + + //requester used to accept index matches + final HashSet workingCopiesPaths = this.getWorkingCopiesPaths(); + IndexQueryRequestor queryRequestor = new IndexQueryRequestor() { + /** + * @see org.eclipse.wst.jsdt.internal.core.search.IndexQueryRequestor#acceptIndexMatch(java.lang.String, org.eclipse.wst.jsdt.core.search.SearchPattern, org.eclipse.wst.jsdt.core.search.SearchParticipant, org.eclipse.wst.jsdt.internal.compiler.env.AccessRuleSet) + */ + public boolean acceptIndexMatch(String documentPath, + SearchPattern indexRecord, SearchParticipant participant, + AccessRuleSet access) { + + if(!workingCopiesPaths.contains(documentPath)) { + MethodPattern record = (MethodPattern)indexRecord; + + functionRequester.acceptFunction(record.selector, + QualificationHelpers.createFullyQualifiedNames(record.parameterQualifications, record.parameterSimpleNames), + record.parameterNames, + record.returnQualification, record.returnSimpleName, + record.getDeclaringQualification(), record.getDeclaringSimpleName(), + record.modifiers, + documentPath); + } + + return true; + } + }; + + // Find function matches from index + IndexManager indexManager = JavaModelManager.getJavaModelManager().getIndexManager(); + try { + if (progressMonitor != null) { + progressMonitor.beginTask(Messages.engine_searching, 1000); + } + + indexManager.performConcurrentJob( + new PatternSearchJob( + searchPattern, + getDefaultSearchParticipant(), // JavaScript search only + scope, + queryRequestor), + waitingPolicy, + progressMonitor == null ? null : new SubProgressMonitor(progressMonitor, 1000)); + } finally { + if (progressMonitor != null) { + progressMonitor.done(); + } + } + + // find function matches from working copies + IJavaScriptUnit[] workingCopies = this.getWorkingCopies(); + for (int workingCopyIndex = 0; workingCopies != null && workingCopyIndex < workingCopies.length; + workingCopyIndex++) { + + final IJavaScriptUnit workingCopy = workingCopies[workingCopyIndex]; + + //skip this working copy if not in the scope + if(!scope.encloses(workingCopy)) { + continue; + } + + try { + //make the working copy consistent if it is not + if(!workingCopy.isConsistent()) { + workingCopy.makeConsistent(progressMonitor); + } + + //get all functions defined at the compilation unit level + List allFunctions = new ArrayList(); + allFunctions.addAll(Arrays.asList(workingCopy.getFunctions())); + + //get all functions defined on global type + IType[] types = workingCopy.getTypes(); + if(types != null & types.length > 0) { + IType globalType = findGlobalType(workingCopy); + + if(globalType != null) { + allFunctions.addAll(Arrays.asList(globalType.getFunctions())); + } + } + + //check each field in the working copy for a match + for (int funcIndex = 0; funcIndex < allFunctions.size(); ++funcIndex) { + IFunction function = (IFunction)allFunctions.get(funcIndex); + + //selector must not be null for it to be a match + char[] wcSelector = null; + if(function.getElementName() != null) { + wcSelector = function.getElementName().toCharArray(); + } + if(wcSelector != null) { + + //create a pattern from the working copy method + char[] wcDeclaringType = null; + if(function.getDeclaringType() != null && function.getDeclaringType().getTypeQualifiedName() != null) { + wcDeclaringType = function.getDeclaringType().getTypeQualifiedName().toCharArray(); + } + wcDeclaringType = wcDeclaringType != null ? wcDeclaringType : IIndexConstants.GLOBAL_SYMBOL; + MethodPattern wcPattern = new MethodPattern(true, false, + wcSelector, declaringTypes, selectorPatternMatchRule); + + //if working copy function matches the search pattern then accept the function + if(searchPattern.matchesDecodedKey(wcPattern)) { + //figure out parameter types + char[][] wcParameterTypes = QualificationHelpers.stringArrayToCharArray(function.getParameterTypes()); + for(int i = 0; i < wcParameterTypes.length; ++i) { + try { + wcParameterTypes[i] = Signature.toCharArray(wcParameterTypes[i]); + } catch(IllegalArgumentException e) { + /* ignore, this will happen if a name looking like it maybe a signature gets passed in, but isn't, such as "QName" + * the real future fix for this should be to completely stop using signatures + */ + } + } + + //figure out the return type parts + char[] wcReturnQualification = null; + char[] wcReturnSimpleName = null; + String wcReturnTypeSig = function.getReturnType(); + if(wcReturnTypeSig != null) { + char[] wcReturnType = Signature.toString(wcReturnTypeSig).toCharArray(); + char[][] wcSeperatedReturnType = + QualificationHelpers.seperateFullyQualifedName(wcReturnType); + wcReturnQualification = wcSeperatedReturnType[QualificationHelpers.QULIFIERS_INDEX]; + wcReturnSimpleName = wcSeperatedReturnType[QualificationHelpers.SIMPLE_NAMES_INDEX]; + } + + //get the declaring type parts + char[][] wcSeperatedDeclaringType = QualificationHelpers.seperateFullyQualifedName(wcDeclaringType); + + //accept the method + functionRequester.acceptFunction(wcSelector, + wcParameterTypes, + QualificationHelpers.stringArrayToCharArray(function.getParameterNames()), + wcReturnQualification, wcReturnSimpleName, + wcSeperatedDeclaringType[QualificationHelpers.QULIFIERS_INDEX], + wcSeperatedDeclaringType[QualificationHelpers.SIMPLE_NAMES_INDEX], + function.getFlags(), workingCopy.getPath().toString()); + } + } + } + } catch(JavaScriptModelException e) { + Logger.logException("Error while processing working copy", e); + } + } + } + + + /** + *

      Searches for all variables in the index and working copies.

      + * + * @param variableRequester requester to report results to + * @param variablePattern selector pattern that the results need to match + * @param declaringType type that all results must be defined on + * @param variablePatternMatchRule the match rule used with the given variablePattern + * @param scope of the search + * @param waitingPolicy policy to use when waiting for the index to index + * @param progressMonitor monitor to report status too + * + * @see SearchPattern + * + * @see IJob#ForceImmediate + * @see IJob#CancelIfNotReady + * @see IJob#WaitUntilReady + */ + public void searchAllVariables(final IVariableRequester variableRequester, + char[] variablePattern, char[][] declaringTypes, final int variablePatternMatchRule, + IJavaScriptSearchScope scope, + int waitingPolicy, IProgressMonitor progressMonitor) { + + //determine the declaring type pattern characters + char[][] declaringTypePatternChars = null; + if(declaringTypes != null && declaringTypes.length > 0) { + declaringTypePatternChars = new char[declaringTypes.length][]; + for(int i = 0; i < declaringTypes.length; i++) + declaringTypePatternChars[i] = declaringTypes[i]; + } + + //pattern for searching the index and working copies + final FieldPattern searchPattern = new FieldPattern(true, false, false, true, + variablePattern, declaringTypePatternChars, null, null, variablePatternMatchRule, null); + + //requester used to accept index matches + final HashSet workingCopiesPaths = this.getWorkingCopiesPaths(); + IndexQueryRequestor queryRequestor = new IndexQueryRequestor() { + /** + * @see org.eclipse.wst.jsdt.internal.core.search.IndexQueryRequestor#acceptIndexMatch(java.lang.String, org.eclipse.wst.jsdt.core.search.SearchPattern, org.eclipse.wst.jsdt.core.search.SearchParticipant, org.eclipse.wst.jsdt.internal.compiler.env.AccessRuleSet) + */ + public boolean acceptIndexMatch(String documentPath, + SearchPattern indexRecord, SearchParticipant participant, + AccessRuleSet access) { + + if(!workingCopiesPaths.contains(documentPath)) { + FieldPattern record = (FieldPattern)indexRecord; + variableRequester.acceptVariable(record.name, + record.typeQualification, record.typeSimpleName, record.getDeclaringQualification(), + record.getDeclaringSimpleName(), + record.modifiers, + documentPath); + } + + return true; + } + }; + + // Find function matches from index + IndexManager indexManager = JavaModelManager.getJavaModelManager().getIndexManager(); + try { + if (progressMonitor != null) { + progressMonitor.beginTask(Messages.engine_searching, 1000); + } + + indexManager.performConcurrentJob( + new PatternSearchJob( + searchPattern, + getDefaultSearchParticipant(), // JavaScript search only + scope, + queryRequestor), + waitingPolicy, + progressMonitor == null ? null : new SubProgressMonitor(progressMonitor, 1000)); + } finally { + if (progressMonitor != null) { + progressMonitor.done(); + } + } + + // find function matches from working copies + IJavaScriptUnit[] workingCopies = this.getWorkingCopies(); + for (int workingCopyIndex = 0; workingCopies != null && workingCopyIndex < workingCopies.length; + workingCopyIndex++) { + + final IJavaScriptUnit workingCopy = workingCopies[workingCopyIndex]; + + //skip this working copy if not in the scope + if(!scope.encloses(workingCopy)) { + continue; + } + + try { + //make the working copy consistent if it is not + if(!workingCopy.isConsistent()) { + workingCopy.makeConsistent(progressMonitor); + } + + //get all fields defined at the compilation unit level + List allFields = new ArrayList(); + allFields.addAll(Arrays.asList(workingCopy.getFields())); + + //get all fields defined on global type defined in this file + IType[] types = workingCopy.getTypes(); + if(types != null & types.length > 0) { + IType globalType = findGlobalType(workingCopy); + + if(globalType != null) { + allFields.addAll(Arrays.asList(globalType.getFields())); + } + } + + //check each field in the working copy for a match + for (int fieldIndex = 0; fieldIndex < allFields.size(); ++fieldIndex) { + IField field = (IField)allFields.get(fieldIndex); + + //selector must not be null for it to be a match + char[] wcName = null; + if(field.getElementName() != null) { + wcName = field.getElementName().toCharArray(); + } + if(wcName != null) { + + //create a pattern from the working copy method + char[] wcDeclaringType = null; + if(field.getDeclaringType() != null && field.getDeclaringType().getTypeQualifiedName() != null) { + wcDeclaringType = field.getDeclaringType().getTypeQualifiedName().toCharArray(); + } + + wcDeclaringType = wcDeclaringType != null ? wcDeclaringType : IIndexConstants.GLOBAL_SYMBOL; + FieldPattern wcPattern = new FieldPattern(true, false, false, true, + wcName, declaringTypePatternChars, null, null, variablePatternMatchRule, null); + + //if working copy function matches the search pattern then accept the function + if(searchPattern.matchesDecodedKey(wcPattern)) { + + //figure out the return type parts + char[] wcTypeQualification = null; + char[] wcTypeSimpleName = null; + String wcTypeSig = field.getTypeSignature(); + if(wcTypeSig != null) { + char[] wcType = Signature.toString(wcTypeSig).toCharArray(); + char[][] wcSeperatedType = + QualificationHelpers.seperateFullyQualifedName(wcType); + wcTypeQualification = wcSeperatedType[QualificationHelpers.QULIFIERS_INDEX]; + wcTypeSimpleName = wcSeperatedType[QualificationHelpers.SIMPLE_NAMES_INDEX]; + } + + //get the declaring type parts + char[][] wcSeperatedDeclaringType = QualificationHelpers.seperateFullyQualifedName(wcDeclaringType); + + //accept the field + variableRequester.acceptVariable(wcName, + wcTypeQualification, wcTypeSimpleName, + wcSeperatedDeclaringType[QualificationHelpers.QULIFIERS_INDEX], + wcSeperatedDeclaringType[QualificationHelpers.SIMPLE_NAMES_INDEX], + field.getFlags(), workingCopy.getPath().toString()); + } + } + } + } catch(JavaScriptModelException e) { + Logger.logException("Error while processing working copy", e); + } + } + } + + /** + *

      + * Finds the global type on the given unit if there is one. + *

      + * + * @param unit + * {@link IJavaScriptUnit} to find the global type on + * + * @return global type in the given {@link IJavaScriptUnit}, or + * null if there is none + * + * @throws JavaScriptModelException + * getting the types on the unit can throw this + */ + private static IType findGlobalType(IJavaScriptUnit unit) throws JavaScriptModelException { + IType globalType = null; + + IType[] types = unit.getTypes(); + if(types != null & types.length > 0) { + for(int i = 0; i < types.length && globalType == null; ++i) { + if(types[i].getElementName().equals(GLOBAL_TYPE_SYMBOL)) { + globalType = types[i]; + } + } + } + + return globalType; } } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/HierarchyScope.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/HierarchyScope.java index 940c3001..3c1e6c00 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/HierarchyScope.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/HierarchyScope.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/IFunctionRequester.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/IFunctionRequester.java new file mode 100644 index 00000000..28be78a9 --- /dev/null +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/IFunctionRequester.java @@ -0,0 +1,41 @@ +/******************************************************************************* + * Copyright (c) 2011, 2012 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.wst.jsdt.internal.core.search; + +/** + *

      Requester to use when requesting function matches.

      + */ +public interface IFunctionRequester { + + /** + *

      Accept a function defined with all of the given information.

      + * + * @param signature + * @param parameterFullyQualifiedTypeNames + * @param parameterNames + * @param returnQualification + * @param returnSimpleName + * @param declaringQualification + * @param declaringSimpleName + * @param modifiers + * @param path + */ + public void acceptFunction( + char[] signature, + char[][] parameterFullyQualifiedTypeNames, + char[][] parameterNames, + char[] returnQualification, + char[] returnSimpleName, + char[] declaringQualification, + char[] declaringSimpleName, + int modifiers, + String path); +} diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/IModuleRequestor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/IModuleRequestor.java new file mode 100644 index 00000000..b0c1661a --- /dev/null +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/IModuleRequestor.java @@ -0,0 +1,46 @@ +/******************************************************************************* + * Copyright (c) 2013 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.wst.jsdt.internal.core.search; + +import org.eclipse.wst.jsdt.core.IField; +import org.eclipse.wst.jsdt.core.IFunction; +import org.eclipse.wst.jsdt.core.IType; + + +public interface IModuleRequestor { + + public void acceptFunction(char[] signature, + char[] declaringQualification, + char[] declaringSimpleName, + String path); + + + public void acceptField(char[] signature, + char[] declaringQualification, + char[] declaringSimpleName, + String path); + + + public void acceptType(char[] qualification, + char[] simpleName, + String documentPath); + + + public void acceptFunction(IFunction function); + + + public void acceptField(IField field); + + + public void acceptType(IType type); + + +} diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/IRestrictedAccessTypeRequestor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/IRestrictedAccessTypeRequestor.java index d3208dd3..be219d1e 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/IRestrictedAccessTypeRequestor.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/IRestrictedAccessTypeRequestor.java @@ -19,6 +19,6 @@ import org.eclipse.wst.jsdt.internal.compiler.env.AccessRestriction; */ public interface IRestrictedAccessTypeRequestor { - public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path, AccessRestriction access); + public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] superTypeNames, char[][] enclosingTypeNames, String path, AccessRestriction access); } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/IVariableRequester.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/IVariableRequester.java new file mode 100644 index 00000000..19fa2cf1 --- /dev/null +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/IVariableRequester.java @@ -0,0 +1,38 @@ +/******************************************************************************* + * Copyright (c) 2011 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.wst.jsdt.internal.core.search; + +/** + *

      Requester to use when requesting variable matches.

      + */ + +public interface IVariableRequester { + + /** + *

      Accept a variable defined with all of the given information.

      + * + * @param signature + * @param typeQualification + * @param typeSimpleName + * @param declaringQualification + * @param declaringSimpleName + * @param modifiers + * @param path + */ + public void acceptVariable( + char[] signature, + char[] typeQualification, + char[] typeSimpleName, + char[] declaringQualification, + char[] declaringSimpleName, + int modifiers, + String path); +} diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/IndexQueryRequestor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/IndexQueryRequestor.java index c09d28db..60e738e2 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/IndexQueryRequestor.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/IndexQueryRequestor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -15,11 +15,21 @@ import org.eclipse.wst.jsdt.core.search.SearchPattern; import org.eclipse.wst.jsdt.internal.compiler.env.AccessRuleSet; /** - * TODO add spec + *

      Requester used when searching an index for matches to a pattern.

      */ public abstract class IndexQueryRequestor { - // answer false if requesting cancel - public abstract boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant, AccessRuleSet access); + /** + *

      Accepts an index match when searching an index.

      + * + * @param documentPath + * @param indexRecord + * @param participant + * @param access + * + * @return true to continue search, false to request cancel of search + */ + public abstract boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, + SearchParticipant participant, AccessRuleSet access); } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/IndexSelector.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/IndexSelector.java index 045a1746..d7b673b5 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/IndexSelector.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/IndexSelector.java @@ -82,7 +82,7 @@ public static boolean canSeeFocus(IJavaScriptElement focus, JavaProject javaProj return true; if (focusEntriesForPolymorphicSearch != null) { - // look for referring project + // look for refering project IPath projectPath = javaProject.getProject().getFullPath(); for (int i = 0, length = focusEntriesForPolymorphicSearch.length; i < length; i++) { IIncludePathEntry entry = focusEntriesForPolymorphicSearch[i]; @@ -91,7 +91,7 @@ public static boolean canSeeFocus(IJavaScriptElement focus, JavaProject javaProj } } if (focus instanceof LibraryFragmentRoot || focus instanceof PackageFragmentRoot) { - // focus is part of a library or a non-project folder in the workspace + // focus is part of a jar IPath focusPath = focus.getPath(); IIncludePathEntry[] entries = javaProject.getExpandedClasspath(); for (int i = 0, length = entries.length; i < length; i++) { @@ -99,7 +99,7 @@ public static boolean canSeeFocus(IJavaScriptElement focus, JavaProject javaProj if ((entry.getEntryKind() == IIncludePathEntry.CPE_LIBRARY || entry.getEntryKind() == IIncludePathEntry.CPE_SOURCE) && entry.getPath().equals(focusPath)) return true; } - if (focus instanceof LibraryFragmentRoot) + if(focus instanceof LibraryFragmentRoot) return false; } // look for dependent projects diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/JavaSearchDocument.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/JavaSearchDocument.java index 9eae996b..b2cd2055 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/JavaSearchDocument.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/JavaSearchDocument.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -32,10 +32,17 @@ public class JavaSearchDocument extends SearchDocument { public JavaSearchDocument(String documentPath, SearchParticipant participant) { super(documentPath, participant); } + /** + * @deprecated - we don't have compiled output requiring handling as bytes + */ public JavaSearchDocument(java.util.zip.ZipEntry zipEntry, IPath zipFilePath, byte[] contents, SearchParticipant participant) { super(zipFilePath + IJavaScriptSearchScope.JAR_FILE_ENTRY_SEPARATOR + zipEntry.getName(), participant); this.byteContents = contents; } + public JavaSearchDocument(java.util.zip.ZipEntry zipEntry, IPath zipFilePath, char[] contents, SearchParticipant participant) { + super(zipFilePath + IJavaScriptSearchScope.JAR_FILE_ENTRY_SEPARATOR + zipEntry.getName(), participant); + this.charContents = contents; + } public JavaSearchDocument( IPath filePath, char[] contents, SearchParticipant participant, String packageName) { super(filePath.toString(), participant); diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/JavaSearchParticipant.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/JavaSearchParticipant.java index b3e20a11..d2b65964 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/JavaSearchParticipant.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/JavaSearchParticipant.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -19,6 +19,7 @@ import org.eclipse.wst.jsdt.core.search.SearchDocument; import org.eclipse.wst.jsdt.core.search.SearchParticipant; import org.eclipse.wst.jsdt.core.search.SearchPattern; import org.eclipse.wst.jsdt.core.search.SearchRequestor; +import org.eclipse.wst.jsdt.internal.compiler.util.Util; import org.eclipse.wst.jsdt.internal.core.search.indexing.SourceIndexer; import org.eclipse.wst.jsdt.internal.core.search.matching.MatchLocator; @@ -80,9 +81,9 @@ public class JavaSearchParticipant extends SearchParticipant { else if (org.eclipse.wst.jsdt.internal.core.util.Util.isMetadataFileName(documentPath)) { new SourceIndexer(document).indexMetadata(); } -// else if (org.eclipse.wst.jsdt.internal.compiler.util.Util.isClassFileName(documentPath)) { -// new BinaryIndexer(document).indexDocument(); -// } + else if (Util.isArchiveFileName(documentPath)) { + new SourceIndexer(document).indexArchive(); + } } /* (non-Javadoc) diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/JavaSearchScope.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/JavaSearchScope.java index 4d90c4c1..64a31e18 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/JavaSearchScope.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/JavaSearchScope.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -190,6 +190,16 @@ void add(JavaProject javaProject, IPath pathToAdd, int includeMask, HashSet visi * @throws JavaScriptModelException May happen if some Java Model info are not available */ public void add(IJavaScriptElement element) throws JavaScriptModelException { + add(element, true); +} + +/** + * Add an element to the java search scope. + * @param element The element we want to add to current java search scope + * @param excludeSubfolders A flag indicating whether folders should exclude subfolders + * @throws JavaScriptModelException May happen if some Java Model info are not available + */ +public void add(IJavaScriptElement element, boolean excludeSubfolders) throws JavaScriptModelException { IPath containerPath = null; String containerPathToString = null; int includeMask = SOURCES | APPLICATION_LIBRARIES | SYSTEM_LIBRARIES; @@ -233,7 +243,7 @@ public void add(IJavaScriptElement element) throws JavaScriptModelException { String relativePath = Util.concatWith(((PackageFragment) element).names, '/'); containerPath = root.getPath(); containerPathToString = containerPath.getDevice() == null ? containerPath.toString() : containerPath.toOSString(); - add(projectPath, relativePath, containerPathToString, true/*package*/, null); + add(projectPath, relativePath, containerPathToString, excludeSubfolders, null); } else { IResource resource = element.getResource(); if (resource != null) { @@ -245,7 +255,7 @@ public void add(IJavaScriptElement element) throws JavaScriptModelException { } containerPathToString = containerPath.getDevice() == null ? containerPath.toString() : containerPath.toOSString(); String relativePath = Util.relativePath(resource.getFullPath(), containerPath.segmentCount()); - add(projectPath, relativePath, containerPathToString, true/*package*/, null); + add(projectPath, relativePath, containerPathToString, excludeSubfolders, null); } } break; @@ -374,10 +384,8 @@ public boolean encloses(String resourcePathString) { * 2. /P/src/pkg */ private int indexOf(String fullPath) { - /* - * cannot guess the index of the container path, fallback to - * sequentially looking at all known paths - */ + // cannot guess the index of the container path + // fallback to sequentially looking at all known paths int answer = -1; String answerFullPath = null; for (int i = 0, length = this.relativePaths.length; i < length; i++) { @@ -391,7 +399,7 @@ private int indexOf(String fullPath) { * is not enclosed by the previous answer, it is either more * specific or different altogether (which is fine) */ - if (answerFullPath == null || !encloses(currentFullPath, answerFullPath, i)) { + if(answerFullPath == null || !encloses(currentFullPath, answerFullPath, i)) { answerFullPath = currentFullPath; answer = i; } @@ -433,11 +441,8 @@ private int indexOf(String containerPath, String relativePath) { return -1; } -/** - * @param enclosingPath - * @param path - * @param index - * @return whether the enclosing path encloses the given path (or is equal to it) +/* + * Returns whether the enclosing path encloses the given path (or is equal to it) */ private boolean encloses(String enclosingPath, String path, int index) { // normalize given path as it can come from outside @@ -596,9 +601,10 @@ public void processDelta(IJavaScriptElementDelta delta) { switch (element.getElementType()) { case IJavaScriptElement.JAVASCRIPT_PROJECT: path = ((IJavaScriptProject)element).getProject().getFullPath(); - break; case IJavaScriptElement.PACKAGE_FRAGMENT_ROOT: - path = ((IPackageFragmentRoot)element).getPath(); + if (path == null) { + path = ((IPackageFragmentRoot)element).getPath(); + } int toRemove = -1; for (int i = 0; i < this.pathsCount; i++) { if (this.relativePaths[i].equals(path)) { // TODO (jerome) this compares String and IPath ! diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/JavaSearchTypeNameMatch.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/JavaSearchTypeNameMatch.java index a630d454..18683b64 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/JavaSearchTypeNameMatch.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/JavaSearchTypeNameMatch.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -22,6 +22,16 @@ public class JavaSearchTypeNameMatch extends TypeNameMatch { private IType type; private int modifiers = -1; // store modifiers to avoid java model population +private char[][] superTypeNames; + +/** + * Creates a new Java Search type name match. + */ +public JavaSearchTypeNameMatch(IType type, char[][] superTypeNames, int modifiers) { + this.type = type; + this.modifiers = modifiers; + this.superTypeNames = superTypeNames; +} /** * Creates a new Java Search type name match. @@ -54,6 +64,13 @@ public int getModifiers() { return this.modifiers; } +/** + * @return + */ +public char[][] getSuperTypeNames() { + return this.superTypeNames; +} + /* (non-Javadoc) * Note that returned handle exists as it matches a type accepted * from up-to-date index file. diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/ModuleMatchRequestorWrapper.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/ModuleMatchRequestorWrapper.java new file mode 100644 index 00000000..7d8c002d --- /dev/null +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/ModuleMatchRequestorWrapper.java @@ -0,0 +1,237 @@ +/******************************************************************************* + * Copyright (c) 2013 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.wst.jsdt.internal.core.search; + +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.Path; +import org.eclipse.wst.jsdt.core.IClassFile; +import org.eclipse.wst.jsdt.core.IField; +import org.eclipse.wst.jsdt.core.IFunction; +import org.eclipse.wst.jsdt.core.IJavaScriptUnit; +import org.eclipse.wst.jsdt.core.IPackageFragment; +import org.eclipse.wst.jsdt.core.IPackageFragmentRoot; +import org.eclipse.wst.jsdt.core.IType; +import org.eclipse.wst.jsdt.core.JavaScriptModelException; +import org.eclipse.wst.jsdt.core.compiler.CharOperation; +import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope; +import org.eclipse.wst.jsdt.core.search.ModuleMatchRequestor; +import org.eclipse.wst.jsdt.internal.core.LibraryFragmentRoot; +import org.eclipse.wst.jsdt.internal.core.PackageFragmentRoot; +import org.eclipse.wst.jsdt.internal.core.util.HashtableOfArrayToObject; + + +public class ModuleMatchRequestorWrapper implements IModuleRequestor { + ModuleMatchRequestor requestor; + private IJavaScriptSearchScope scope; // scope is needed to retrieve project path for external resource + + /** + * Cache package fragment root information to optimize speed performance. + */ + private String lastPkgFragmentRootPath; + private IPackageFragmentRoot lastPkgFragmentRoot; + + /** + * Cache package handles to optimize memory. + */ + private HashtableOfArrayToObject packageHandles; + + public ModuleMatchRequestorWrapper(ModuleMatchRequestor requestor, IJavaScriptSearchScope scope) { + this.requestor = requestor; + this.scope = scope; + } + + public void acceptType(char[] qualification, char[] simpleName, String path) { + try { + IType type = null; + if (qualification!=null && qualification.length>0 && (CharOperation.indexOf('.',simpleName) == -1)) { + simpleName=CharOperation.concat(qualification, simpleName, '.'); + } + int separatorIndex= path.indexOf(IJavaScriptSearchScope.JAR_FILE_ENTRY_SEPARATOR); + type = separatorIndex == -1 + ? createTypeFromPath(path, new String(simpleName)) + : createTypeFromJar(path, separatorIndex); + + if (type != null && !type.isAnonymous()) { + this.requestor.acceptElementMatch(type); + } + } catch (JavaScriptModelException e) { + // skip + } + } + + /* (non-Javadoc) + * @see org.eclipse.wst.jsdt.internal.core.search.IJSElementRequestor#acceptFunction(char[], char[][], char[][], char[], char[], char[], char[], java.lang.String) + */ + public void acceptFunction(char[] signature, char[] declaringQualification, char[] declaringSimpleName, String path) { + try { + IType type = null; + if (declaringQualification!=null && declaringQualification.length>0 && (CharOperation.indexOf('.',declaringSimpleName) == -1)) { + declaringSimpleName=CharOperation.concat(declaringQualification, declaringSimpleName, '.'); + } + int separatorIndex= path.indexOf(IJavaScriptSearchScope.JAR_FILE_ENTRY_SEPARATOR); + type = separatorIndex == -1 + ? createTypeFromPath(path, new String(declaringSimpleName)) + : createTypeFromJar(path, separatorIndex); + + if (type != null) { + IFunction method = type.getFunction(CharOperation.charToString(signature), new String[0]); + if (method.exists()) { + this.requestor.acceptElementMatch(method); + return; + } + } + } + catch (JavaScriptModelException e) { + // skip + } + } + + /* (non-Javadoc) + * @see org.eclipse.wst.jsdt.internal.core.search.IJSElementRequestor#acceptField(char[], char[], char[], char[], char[], java.lang.String) + */ + public void acceptField(char[] signature, char[] declaringQualification, char[] declaringSimpleName, String path) { + try { + IType type = null; + if (declaringQualification!=null && declaringQualification.length>0 && (CharOperation.indexOf('.',declaringSimpleName) == -1)) { + declaringSimpleName=CharOperation.concat(declaringQualification, declaringSimpleName, '.'); + } + int separatorIndex= path.indexOf(IJavaScriptSearchScope.JAR_FILE_ENTRY_SEPARATOR); + type = separatorIndex == -1 + ? createTypeFromPath(path, new String(declaringSimpleName)) + : createTypeFromJar(path, separatorIndex); + + if (type != null) { + IField field = type.getField(CharOperation.charToString(signature)); + if (field.exists()) { + this.requestor.acceptElementMatch(field); + } + } + } + catch (JavaScriptModelException e) { + // skip + } + } + + /* (non-Javadoc) + * @see org.eclipse.wst.jsdt.internal.core.search.IJSElementRequestor#acceptType(org.eclipse.wst.jsdt.core.IType) + */ + public void acceptType(IType type) { + this.requestor.acceptElementMatch(type); + } + + /* (non-Javadoc) + * @see org.eclipse.wst.jsdt.internal.core.search.IJSElementRequestor#acceptFunction(org.eclipse.wst.jsdt.core.IFunction) + */ + public void acceptFunction(IFunction function) { + this.requestor.acceptElementMatch(function); + } + + /* (non-Javadoc) + * @see org.eclipse.wst.jsdt.internal.core.search.IJSElementRequestor#acceptField(org.eclipse.wst.jsdt.core.IField) + */ + public void acceptField(IField field) { + this.requestor.acceptElementMatch(field); + } + + private IType createTypeFromJar(String resourcePath, int separatorIndex) throws JavaScriptModelException { + // path to a class file inside a jar + // Optimization: cache package fragment root handle and package handles + if (this.lastPkgFragmentRootPath == null + || this.lastPkgFragmentRootPath.length() > resourcePath.length() + || !resourcePath.startsWith(this.lastPkgFragmentRootPath)) { + String jarPath= resourcePath.substring(0, separatorIndex); + IPackageFragmentRoot root= ((JavaSearchScope)this.scope).packageFragmentRoot(resourcePath); + if (root == null) return null; + this.lastPkgFragmentRootPath= jarPath; + this.lastPkgFragmentRoot= root; + this.packageHandles= new HashtableOfArrayToObject(5); + } + // create handle + String classFilePath= resourcePath.substring(separatorIndex + 1); + String[] simpleNames = new Path(classFilePath).segments(); + String[] pkgName; + int length = simpleNames.length-1; + if (length > 0) { + pkgName = new String[length]; + System.arraycopy(simpleNames, 0, pkgName, 0, length); + } else { + pkgName = CharOperation.NO_STRINGS; + } + IPackageFragment pkgFragment= (IPackageFragment) this.packageHandles.get(pkgName); + if (pkgFragment == null) { + pkgFragment= ((PackageFragmentRoot) this.lastPkgFragmentRoot).getPackageFragment(pkgName); + this.packageHandles.put(pkgName, pkgFragment); + } + return pkgFragment.getClassFile(simpleNames[length]).getType(); + } + + private IType createTypeFromPath(String resourcePath, String typeName) throws JavaScriptModelException { + // path to a file in a directory + // Optimization: cache package fragment root handle and package handles + int rootPathLength = -1; + boolean samePath=false; + if (resourcePath!=null && this.lastPkgFragmentRoot!=null) { + IPath path1 = new Path(resourcePath); + IPath path2 = new Path(this.lastPkgFragmentRootPath); + samePath = path1.equals(path2); + } + if (!samePath && (this.lastPkgFragmentRootPath == null || !(resourcePath.startsWith(this.lastPkgFragmentRootPath) + && ((rootPathLength = this.lastPkgFragmentRootPath.length()) > 0 + && (rootPathLength 0) { + pkgName = new String[length]; + System.arraycopy(simpleNames, 0, pkgName, 0, length); + } else { + pkgName = CharOperation.NO_STRINGS; + } + IPackageFragment pkgFragment= (IPackageFragment) this.packageHandles.get(pkgName); + if (pkgFragment == null) { + pkgFragment= ((PackageFragmentRoot) this.lastPkgFragmentRoot).getPackageFragment(pkgName); + this.packageHandles.put(pkgName, pkgFragment); + } + String simpleName= simpleNames[length]; + if (org.eclipse.wst.jsdt.internal.core.util.Util.isJavaLikeFileName(simpleName) && pkgFragment.getKind()!=IPackageFragmentRoot.K_BINARY) { + IJavaScriptUnit unit= pkgFragment.getJavaScriptUnit(simpleName); + IType type = unit.getType(typeName); + return type; + } else { + IClassFile classFile= pkgFragment.getClassFile(simpleName); + return classFile.getType(typeName); + } + } + } + +} diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/TypeNameMatchRequestorWrapper.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/TypeNameMatchRequestorWrapper.java index 04f604a4..d3800c54 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/TypeNameMatchRequestorWrapper.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/TypeNameMatchRequestorWrapper.java @@ -1,221 +1,222 @@ -/******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.jsdt.internal.core.search; - -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.Path; -import org.eclipse.wst.jsdt.core.IClassFile; -import org.eclipse.wst.jsdt.core.IJavaScriptElement; -import org.eclipse.wst.jsdt.core.IJavaScriptUnit; -import org.eclipse.wst.jsdt.core.IPackageFragment; -import org.eclipse.wst.jsdt.core.IPackageFragmentRoot; -import org.eclipse.wst.jsdt.core.IType; -import org.eclipse.wst.jsdt.core.JavaScriptModelException; -import org.eclipse.wst.jsdt.core.compiler.CharOperation; -import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope; -import org.eclipse.wst.jsdt.core.search.TypeNameMatchRequestor; -import org.eclipse.wst.jsdt.internal.compiler.env.AccessRestriction; -import org.eclipse.wst.jsdt.internal.core.LibraryFragmentRoot; -import org.eclipse.wst.jsdt.internal.core.Openable; -import org.eclipse.wst.jsdt.internal.core.PackageFragmentRoot; -import org.eclipse.wst.jsdt.internal.core.util.HandleFactory; -import org.eclipse.wst.jsdt.internal.core.util.HashtableOfArrayToObject; - -/** - * Wrapper used to link {@link IRestrictedAccessTypeRequestor} with {@link org.eclipse.wst.jsdt.core.search.TypeNameRequestor}. - * This wrapper specifically allows usage of internal method {@link BasicSearchEngine#searchAllTypeNames( - * char[] packageName, - * int packageMatchRule, - * char[] typeName, - * int typeMatchRule, - * int searchFor, - * org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope scope, - * IRestrictedAccessTypeRequestor nameRequestor, - * int waitingPolicy, - * org.eclipse.core.runtime.IProgressMonitor monitor) }. - * from API method {@link org.eclipse.wst.jsdt.core.search.SearchEngine#searchAllTypeNames( - * char[] packageName, - * int packageMatchRule, - * char[] typeName, - * int matchRule, - * int searchFor, - * org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope scope, - * org.eclipse.wst.jsdt.core.search.TypeNameRequestor nameRequestor, - * int waitingPolicy, - * org.eclipse.core.runtime.IProgressMonitor monitor) }. - */ -public class TypeNameMatchRequestorWrapper implements IRestrictedAccessTypeRequestor { - TypeNameMatchRequestor requestor; - private IJavaScriptSearchScope scope; // scope is needed to retrieve project path for external resource - private HandleFactory handleFactory; // in case of IJavaScriptSearchScope defined by clients, use an HandleFactory instead - - /** - * Cache package fragment root information to optimize speed performance. - */ - private String lastPkgFragmentRootPath; - private IPackageFragmentRoot lastPkgFragmentRoot; - - /** - * Cache package handles to optimize memory. - */ - private HashtableOfArrayToObject packageHandles; - -public TypeNameMatchRequestorWrapper(TypeNameMatchRequestor requestor, IJavaScriptSearchScope scope) { - this.requestor = requestor; - this.scope = scope; - if (!(scope instanceof JavaSearchScope)) { - this.handleFactory = new HandleFactory(); - } -} - -/* (non-Javadoc) - * @see org.eclipse.wst.jsdt.internal.core.search.IRestrictedAccessTypeRequestor#acceptType(int, char[], char[], char[][], java.lang.String, org.eclipse.wst.jsdt.internal.compiler.env.AccessRestriction) - */ -public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path, AccessRestriction access) { - try { - IType type = null; - if (packageName!=null && packageName.length>0) - { - simpleTypeName=CharOperation.concat(packageName, simpleTypeName, '.'); - } - if (this.handleFactory != null) { - Openable openable = this.handleFactory.createOpenable(path, this.scope); - if (openable == null) return; - switch (openable.getElementType()) { - case IJavaScriptElement.JAVASCRIPT_UNIT: - IJavaScriptUnit cu = (IJavaScriptUnit) openable; - if (enclosingTypeNames != null && enclosingTypeNames.length > 0) { - type = cu.getType(new String(enclosingTypeNames[0])); - for (int j=1, l=enclosingTypeNames.length; j resourcePath.length() - || !resourcePath.startsWith(this.lastPkgFragmentRootPath)) { - String jarPath= resourcePath.substring(0, separatorIndex); - IPackageFragmentRoot root= ((JavaSearchScope)this.scope).packageFragmentRoot(resourcePath); - if (root == null) return null; - this.lastPkgFragmentRootPath= jarPath; - this.lastPkgFragmentRoot= root; - this.packageHandles= new HashtableOfArrayToObject(5); - } - // create handle - String classFilePath= resourcePath.substring(separatorIndex + 1); - String[] simpleNames = new Path(classFilePath).segments(); - String[] pkgName; - int length = simpleNames.length-1; - if (length > 0) { - pkgName = new String[length]; - System.arraycopy(simpleNames, 0, pkgName, 0, length); - } else { - pkgName = CharOperation.NO_STRINGS; - } - IPackageFragment pkgFragment= (IPackageFragment) this.packageHandles.get(pkgName); - if (pkgFragment == null) { - pkgFragment= ((PackageFragmentRoot) this.lastPkgFragmentRoot).getPackageFragment(pkgName); - this.packageHandles.put(pkgName, pkgFragment); - } - return pkgFragment.getClassFile(simpleNames[length]).getType(); -} -private IType createTypeFromPath(String resourcePath, String simpleTypeName, char[][] enclosingTypeNames) throws JavaScriptModelException { - // path to a file in a directory - // Optimization: cache package fragment root handle and package handles - int rootPathLength = -1; - boolean samePath=false; - if(resourcePath!=null && this.lastPkgFragmentRoot!=null) { - IPath path1 = new Path(resourcePath); - IPath path2 = new Path(this.lastPkgFragmentRootPath); - samePath = path1.equals(path2); - } - if (!samePath && (this.lastPkgFragmentRootPath == null || !(resourcePath.startsWith(this.lastPkgFragmentRootPath) - && ((rootPathLength = this.lastPkgFragmentRootPath.length()) > 0 - && (rootPathLength 0) { - pkgName = new String[length]; - System.arraycopy(simpleNames, 0, pkgName, 0, length); - } else { - pkgName = CharOperation.NO_STRINGS; - } - IPackageFragment pkgFragment= (IPackageFragment) this.packageHandles.get(pkgName); - if (pkgFragment == null) { - pkgFragment= ((PackageFragmentRoot) this.lastPkgFragmentRoot).getPackageFragment(pkgName); - this.packageHandles.put(pkgName, pkgFragment); - } - String simpleName= simpleNames[length]; - if (org.eclipse.wst.jsdt.internal.core.util.Util.isJavaLikeFileName(simpleName) && pkgFragment.getKind()!=IPackageFragmentRoot.K_BINARY) { - IJavaScriptUnit unit= pkgFragment.getJavaScriptUnit(simpleName); - int etnLength = enclosingTypeNames == null ? 0 : enclosingTypeNames.length; - IType type = (etnLength == 0) ? unit.getType(simpleTypeName) : unit.getType(new String(enclosingTypeNames[0])); - if (etnLength > 0) { - for (int i=1; i0 && (CharOperation.indexOf('.',simpleTypeName) == -1)) + { + simpleTypeName=CharOperation.concat(packageName, simpleTypeName, '.'); + } + if (this.handleFactory != null) { + Openable openable = this.handleFactory.createOpenable(path, this.scope); + if (openable == null) return; + switch (openable.getElementType()) { + case IJavaScriptElement.JAVASCRIPT_UNIT: + IJavaScriptUnit cu = (IJavaScriptUnit) openable; + if (enclosingTypeNames != null && enclosingTypeNames.length > 0) { + type = cu.getType(new String(enclosingTypeNames[0])); + for (int j=1, l=enclosingTypeNames.length; j resourcePath.length() + || !resourcePath.startsWith(this.lastPkgFragmentRootPath)) { + String jarPath= resourcePath.substring(0, separatorIndex); + IPackageFragmentRoot root= ((JavaSearchScope)this.scope).packageFragmentRoot(resourcePath); + if (root == null) return null; + this.lastPkgFragmentRootPath= jarPath; + this.lastPkgFragmentRoot= root; + this.packageHandles= new HashtableOfArrayToObject(5); + } + // create handle + String classFilePath= resourcePath.substring(separatorIndex + 1); + String[] simpleNames = new Path(classFilePath).segments(); + String[] pkgName; + int length = simpleNames.length-1; + if (length > 0) { + pkgName = new String[length]; + System.arraycopy(simpleNames, 0, pkgName, 0, length); + } else { + pkgName = CharOperation.NO_STRINGS; + } + IPackageFragment pkgFragment= (IPackageFragment) this.packageHandles.get(pkgName); + if (pkgFragment == null) { + pkgFragment= ((PackageFragmentRoot) this.lastPkgFragmentRoot).getPackageFragment(pkgName); + this.packageHandles.put(pkgName, pkgFragment); + } + return pkgFragment.getClassFile(simpleNames[length]).getType(); +} +private IType createTypeFromPath(String resourcePath, String simpleTypeName, char[][] enclosingTypeNames) throws JavaScriptModelException { + // path to a file in a directory + // Optimization: cache package fragment root handle and package handles + int rootPathLength = -1; + boolean samePath=false; + if(resourcePath!=null && this.lastPkgFragmentRoot!=null) { + IPath path1 = new Path(resourcePath); + IPath path2 = new Path(this.lastPkgFragmentRootPath); + samePath = path1.equals(path2); + } + if (!samePath && (this.lastPkgFragmentRootPath == null || !(resourcePath.startsWith(this.lastPkgFragmentRootPath) + && ((rootPathLength = this.lastPkgFragmentRootPath.length()) > 0 + && (rootPathLength 0) { + pkgName = new String[length]; + System.arraycopy(simpleNames, 0, pkgName, 0, length); + } else { + pkgName = CharOperation.NO_STRINGS; + } + IPackageFragment pkgFragment= (IPackageFragment) this.packageHandles.get(pkgName); + if (pkgFragment == null) { + pkgFragment= ((PackageFragmentRoot) this.lastPkgFragmentRoot).getPackageFragment(pkgName); + this.packageHandles.put(pkgName, pkgFragment); + } + String simpleName= simpleNames[length]; + if (org.eclipse.wst.jsdt.internal.core.util.Util.isJavaLikeFileName(simpleName) && pkgFragment.getKind()!=IPackageFragmentRoot.K_BINARY) { + IJavaScriptUnit unit= pkgFragment.getJavaScriptUnit(simpleName); + int etnLength = enclosingTypeNames == null ? 0 : enclosingTypeNames.length; + IType type = (etnLength == 0) ? unit.getType(simpleTypeName) : unit.getType(new String(enclosingTypeNames[0])); + if (etnLength > 0) { + for (int i=1; i 0) { + this.addIndexEntry(TYPE_SYNONYMS, TypeSynonymsPattern.createIndexKey(fullyQualifiedName, synonyms)); + } + } public void addConstructorDeclaration(char[] typeName, char[][] parameterTypes, char[][] parameterNames, int modifiers) { - int argCount = parameterTypes == null ? 0 : parameterTypes.length; - addIndexEntry(CONSTRUCTOR_DECL, ConstructorDeclarationPattern.createDeclarationIndexKey(typeName, argCount, parameterTypes, parameterNames, modifiers)); + addIndexEntry(CONSTRUCTOR_DECL, ConstructorPattern.createIndexKey(typeName, parameterTypes, parameterNames, modifiers)); if (parameterTypes != null) { - for (int i = 0; i < argCount; i++) - addTypeReference(parameterTypes[i]); + for (int i = 0; i < parameterTypes.length; i++) { + if(parameterTypes[i] != null) { + addTypeReference(parameterTypes[i]); + } + } } } public void addConstructorReference(char[] typeName, int argCount) { - char[] simpleTypeName = CharOperation.lastSegment(typeName,'.'); - addTypeReference(simpleTypeName); - addIndexEntry(CONSTRUCTOR_REF, ConstructorPattern.createIndexKey(simpleTypeName, argCount)); - char[] innermostTypeName = CharOperation.lastSegment(simpleTypeName,'$'); - if (innermostTypeName != simpleTypeName) - addIndexEntry(CONSTRUCTOR_REF, ConstructorPattern.createIndexKey(innermostTypeName, argCount)); - } - public void addFieldDeclaration(char[] typeName, char[] fieldName, boolean isVar) { - char [] key = isVar ? VAR_DECL:FIELD_DECL; - addIndexEntry(key, FieldPattern.createIndexKey(fieldName)); - if (typeName!=null) addTypeReference(typeName); + addIndexEntry(CONSTRUCTOR_REF, ConstructorPattern.createIndexKey(typeName, null, null, ClassFileConstants.AccDefault)); + } + public void addFieldDeclaration(char[] typeName, char[] fieldName, char[] declaringType, int modifiers, + boolean isVar) { + + //only index if field has a name + if(fieldName != null && fieldName.length > 0) { + char [] key = isVar ? VAR_DECL:FIELD_DECL; + addIndexEntry(key, FieldPattern.createIndexKey(fieldName, typeName, declaringType != null ? declaringType : IIndexConstants.GLOBAL_SYMBOL, modifiers)); + if (typeName!=null) { + addTypeReference(typeName); + } + } else { + //this should never happen, so log it + String errorMsg = "JSDT AbstractIndexer attempted to index a field with no name, this should never happen."; + if(typeName != null) { + errorMsg += "\ntypeName: " + new String(typeName); + } + if(declaringType != null) { + errorMsg += "\ndeclaringType: " + new String(declaringType); + } + Logger.log(Logger.WARNING, errorMsg); + } } public void addFieldReference(char[] fieldName) { addNameReference(fieldName); @@ -74,41 +98,50 @@ public abstract class AbstractIndexer implements IIndexConstants { protected void addIndexEntry(char[] category, char[] key) { this.document.addIndexEntry(category, key); } - public void addMethodDeclaration(char[] methodName, char[][] parameterTypes, - char[] returnType,boolean isFunction) { - int argCount = parameterTypes == null ? 0 : parameterTypes.length; - addIndexEntry(isFunction ? FUNCTION_DECL : METHOD_DECL, MethodPattern.createIndexKey(methodName, argCount)); + public void addMethodDeclaration(char[] methodName, char[][] parameterTypes, char[][] paramaterNames, + char[] returnType, char[] declaringType, boolean isFunction, int modifiers) { + + //compute key + char[] key = MethodPattern.createIndexKey(methodName, parameterTypes, paramaterNames, + declaringType != null ? declaringType : IIndexConstants.GLOBAL_SYMBOL, returnType, modifiers); + if(key != null) { + addIndexEntry(isFunction ? FUNCTION_DECL : METHOD_DECL, key); + } if (parameterTypes != null) { - for (int i = 0; i < argCount; i++) + for (int i = 0; i < parameterTypes.length; i++) addTypeReference(parameterTypes[i]); } if (returnType != null) addTypeReference(returnType); } - public void addMethodReference(char[] methodName, int argCount) { - addIndexEntry(METHOD_REF, MethodPattern.createIndexKey(methodName, argCount)); + public void addMethodReference(char[] methodName) { + char[] key = MethodPattern.createIndexKey(methodName); + if(key != null) { + addIndexEntry(METHOD_REF, key); + } } public void addNameReference(char[] name) { addIndexEntry(REF, name); } - protected void addTypeDeclaration(int modifiers, char[] packageName, char[] name, char[][] enclosingTypeNames, boolean secondary) { - char[] indexKey = TypeDeclarationPattern.createIndexKey(modifiers, name, packageName, enclosingTypeNames, secondary); - if (secondary) - JavaModelManager.getJavaModelManager().secondaryTypeAdding( - this.document.getPath(), - name == null ? CharOperation.NO_CHAR : name, - packageName == null ? CharOperation.NO_CHAR : packageName); - - addIndexEntry(TYPE_DECL, indexKey); - - // add a second key that includes the package name - indexKey = TypeDeclarationPattern.createIndexKey(modifiers, CharOperation.concat(packageName, name, '.'), packageName, enclosingTypeNames, secondary); + + /** + * + *

      Adds a type declaration to the index.

      + * + * @param modifiers of the type + * @param qualification qualification of the type + * @param simpleTypeName simple name of the type + * @param superTypeName fully qualified super type + */ + protected void addTypeDeclaration(int modifiers, char[] qualification, char[] simpleTypeName, char[] superTypeName) { + char[] indexKey = TypeDeclarationPattern.createIndexKey(qualification, simpleTypeName, new char[][] {superTypeName}, modifiers); addIndexEntry(TYPE_DECL, indexKey); } public void addTypeReference(char[] typeName) { - if (typeName!=null) - addNameReference(CharOperation.lastSegment(typeName, '.')); + if (typeName!=null) { + addNameReference(typeName); + } } public abstract void indexDocument(); } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/AddJarFileToIndex.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/AddJarFileToIndex.java new file mode 100644 index 00000000..bbf638ea --- /dev/null +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/AddJarFileToIndex.java @@ -0,0 +1,254 @@ +/******************************************************************************* + * Copyright (c) 2000, 2012 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.wst.jsdt.internal.core.search.indexing; + +import java.io.File; +import java.io.IOException; +import java.net.URI; +import java.util.Enumeration; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.Path; +import org.eclipse.wst.jsdt.core.compiler.InvalidInputException; +import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope; +import org.eclipse.wst.jsdt.core.search.SearchEngine; +import org.eclipse.wst.jsdt.core.search.SearchParticipant; +import org.eclipse.wst.jsdt.internal.compiler.parser.Scanner; +import org.eclipse.wst.jsdt.internal.compiler.parser.TerminalTokens; +import org.eclipse.wst.jsdt.internal.compiler.util.SimpleLookupTable; +import org.eclipse.wst.jsdt.internal.compiler.util.Util; +import org.eclipse.wst.jsdt.internal.core.JavaModelManager; +import org.eclipse.wst.jsdt.internal.core.index.Index; +import org.eclipse.wst.jsdt.internal.core.search.JavaSearchDocument; +import org.eclipse.wst.jsdt.internal.core.search.processing.JobManager; + +class AddJarFileToIndex extends IndexRequest { + + private static final char JAR_SEPARATOR = IJavaScriptSearchScope.JAR_FILE_ENTRY_SEPARATOR.charAt(0); + IFile resource; + Scanner scanner; + + public AddJarFileToIndex(IFile resource, IndexManager manager) { + super(resource.getFullPath(), manager); + this.resource = resource; + } + public AddJarFileToIndex(IPath jarPath, IndexManager manager) { + // external JAR scenario - no resource + super(jarPath, manager); + } + public boolean equals(Object o) { + if (o instanceof AddJarFileToIndex) { + if (this.resource != null) + return this.resource.equals(((AddJarFileToIndex) o).resource); + if (this.containerPath != null) + return this.containerPath.equals(((AddJarFileToIndex) o).containerPath); + } + return false; + } + public int hashCode() { + if (this.resource != null) + return this.resource.hashCode(); + if (this.containerPath != null) + return this.containerPath.hashCode(); + return -1; + } + public boolean execute(IProgressMonitor progressMonitor) { + + if (this.isCancelled || progressMonitor != null && progressMonitor.isCanceled()) return true; + + try { + // if index is already cached, then do not perform any check + // MUST reset the IndexManager if a jar file is changed + Index index = this.manager.getIndexForUpdate(this.containerPath, false, /*do not reuse index file*/ false /*do not create if none*/); + if (index != null) { + if (JobManager.VERBOSE) + org.eclipse.wst.jsdt.internal.core.util.Util.verbose("-> no indexing required (index already exists) for " + this.containerPath); //$NON-NLS-1$ + return true; + } + + index = this.manager.getIndexForUpdate(this.containerPath, true, /*reuse index file*/ true /*create if none*/); + if (index == null) { + if (JobManager.VERBOSE) + org.eclipse.wst.jsdt.internal.core.util.Util.verbose("-> index could not be created for " + this.containerPath); //$NON-NLS-1$ + return true; + } + ReadWriteMonitor monitor = index.monitor; + if (monitor == null) { + if (JobManager.VERBOSE) + org.eclipse.wst.jsdt.internal.core.util.Util.verbose("-> index for " + this.containerPath + " just got deleted"); //$NON-NLS-1$//$NON-NLS-2$ + return true; // index got deleted since acquired + } +// index.separator = JAR_SEPARATOR; + ZipFile zip = null; + try { + // this path will be a relative path to the workspace in case the zipfile in the workspace otherwise it will be a path in the + // local file system + Path zipFilePath = null; + + monitor.enterWrite(); // ask permission to write + if (this.resource != null) { + URI location = this.resource.getLocationURI(); + if (location == null) return false; + if (JavaModelManager.ZIP_ACCESS_VERBOSE) + System.out.println("(" + Thread.currentThread() + ") [AddJarFileToIndex.execute()] Creating ZipFile on " + location.getPath()); //$NON-NLS-1$ //$NON-NLS-2$ + File file = null; + try { + file = org.eclipse.wst.jsdt.internal.core.util.Util.toLocalFile(location, progressMonitor); + } catch (CoreException e) { + if (JobManager.VERBOSE) { + org.eclipse.wst.jsdt.internal.core.util.Util.verbose("-> failed to index " + location.getPath() + " because of the following exception:"); //$NON-NLS-1$ //$NON-NLS-2$ + e.printStackTrace(); + } + } + if (file == null) { + if (JobManager.VERBOSE) + org.eclipse.wst.jsdt.internal.core.util.Util.verbose("-> failed to index " + location.getPath() + " because the file could not be fetched"); //$NON-NLS-1$ //$NON-NLS-2$ + return false; + } + zip = new ZipFile(file); + zipFilePath = (Path) this.resource.getFullPath().makeRelative(); + // absolute path relative to the workspace + } else { + if (JavaModelManager.ZIP_ACCESS_VERBOSE) + System.out.println("(" + Thread.currentThread() + ") [AddJarFileToIndex.execute()] Creating ZipFile on " + this.containerPath); //$NON-NLS-1$ //$NON-NLS-2$ + // external file -> it is ok to use toFile() + zip = new ZipFile(this.containerPath.toFile()); + zipFilePath = (Path) this.containerPath; + // path is already canonical since coming from a library classpath entry + } + + if (this.isCancelled) { + if (JobManager.VERBOSE) + org.eclipse.wst.jsdt.internal.core.util.Util.verbose("-> indexing of " + zip.getName() + " has been cancelled"); //$NON-NLS-1$ //$NON-NLS-2$ + return false; + } + + if (JobManager.VERBOSE) + org.eclipse.wst.jsdt.internal.core.util.Util.verbose("-> indexing " + zip.getName()); //$NON-NLS-1$ + long initialTime = System.currentTimeMillis(); + + String[] paths = index.queryDocumentNames(""); // all file names //$NON-NLS-1$ + if (paths != null) { + int max = paths.length; + /* check integrity of the existing index file + * if the length is equal to 0, we want to index the whole jar again + * If not, then we want to check that there is no missing entry, if + * one entry is missing then we recreate the index + */ + String EXISTS = "OK"; //$NON-NLS-1$ + String DELETED = "DELETED"; //$NON-NLS-1$ + SimpleLookupTable indexedFileNames = new SimpleLookupTable(max == 0 ? 33 : max + 11); + for (int i = 0; i < max; i++) + indexedFileNames.put(paths[i], DELETED); + for (Enumeration e = zip.entries(); e.hasMoreElements();) { + // iterate each entry to index it + ZipEntry ze = (ZipEntry) e.nextElement(); + String zipEntryName = ze.getName(); + if (Util.isClassFileName(zipEntryName)) + // the class file may not be there if the package name is not valid + indexedFileNames.put(zipEntryName, EXISTS); + } + boolean needToReindex = indexedFileNames.elementSize != max; // a new file was added + if (!needToReindex) { + Object[] valueTable = indexedFileNames.valueTable; + for (int i = 0, l = valueTable.length; i < l; i++) { + if (valueTable[i] == DELETED) { + needToReindex = true; // a file was deleted so re-index + break; + } + } + if (!needToReindex) { + if (JobManager.VERBOSE) + org.eclipse.wst.jsdt.internal.core.util.Util.verbose("-> no indexing required (index is consistent with library) for " //$NON-NLS-1$ + + zip.getName() + " (" //$NON-NLS-1$ + + (System.currentTimeMillis() - initialTime) + "ms)"); //$NON-NLS-1$ + this.manager.saveIndex(index); // to ensure its placed into the saved state + return true; + } + } + } + + // Index the jar for the first time or reindex the jar in case the previous index file has been corrupted + // index already existed: recreate it so that we forget about previous entries + SearchParticipant participant = SearchEngine.getDefaultSearchParticipant(); + if (!this.manager.resetIndex(this.containerPath)) { + // failed to recreate index, see 73330 + this.manager.removeIndex(this.containerPath); + return false; + } +// index.separator = JAR_SEPARATOR; + IPath indexPath = null; + for (Enumeration e = zip.entries(); e.hasMoreElements();) { + if (this.isCancelled) { + if (JobManager.VERBOSE) + org.eclipse.wst.jsdt.internal.core.util.Util.verbose("-> indexing of " + zip.getName() + " has been cancelled"); //$NON-NLS-1$ //$NON-NLS-2$ + return false; + } + + // iterate each entry to index it + ZipEntry ze = (ZipEntry) e.nextElement(); + String zipEntryName = ze.getName(); + if (Util.isClassFileName(zipEntryName)) { + final byte[] classFileBytes = org.eclipse.wst.jsdt.internal.compiler.util.Util.getZipEntryByteContent(ze, zip); + char[] classFileChars = new char[classFileBytes.length]; + for (int i = 0; i < classFileChars.length; i++) { + classFileChars[i] = (char) classFileBytes[i]; + } + JavaSearchDocument entryDocument = new JavaSearchDocument(ze, zipFilePath, classFileChars, participant); + this.manager.indexDocument(entryDocument, participant, index, indexPath); + } + } + this.manager.saveIndex(index); + if (JobManager.VERBOSE) + org.eclipse.wst.jsdt.internal.core.util.Util.verbose("-> done indexing of " //$NON-NLS-1$ + + zip.getName() + " (" //$NON-NLS-1$ + + (System.currentTimeMillis() - initialTime) + "ms)"); //$NON-NLS-1$ + } finally { + if (zip != null) { + if (JavaModelManager.ZIP_ACCESS_VERBOSE) + System.out.println("(" + Thread.currentThread() + ") [AddJarFileToIndex.execute()] Closing ZipFile " + zip); //$NON-NLS-1$ //$NON-NLS-2$ + zip.close(); + } + monitor.exitWrite(); // free write lock + } + } catch (IOException e) { + if (JobManager.VERBOSE) { + org.eclipse.wst.jsdt.internal.core.util.Util.verbose("-> failed to index " + this.containerPath + " because of the following exception:"); //$NON-NLS-1$ //$NON-NLS-2$ + e.printStackTrace(); + } + this.manager.removeIndex(this.containerPath); + return false; + } + return true; + } + private boolean isIdentifier() throws InvalidInputException { + switch(this.scanner.scanIdentifier()) { + // assert and enum will not be recognized as java identifiers + // in 1.7 mode, which are in 1.3. + case TerminalTokens.TokenNameIdentifier: + case TerminalTokens.TokenNameenum: + return true; + default: + return false; + } + } + protected Integer updatedIndexState() { + return IndexManager.REBUILDING_STATE; + } + public String toString() { + return "indexing " + this.containerPath.toString(); //$NON-NLS-1$ + } +} diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/AddLibraryFileToIndex.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/AddLibraryFileToIndex.java index 2b99cfb3..946f2f4b 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/AddLibraryFileToIndex.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/AddLibraryFileToIndex.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -12,6 +12,10 @@ package org.eclipse.wst.jsdt.internal.core.search.indexing; import java.io.File; import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Enumeration; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.IPath; @@ -19,6 +23,7 @@ import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.wst.jsdt.core.search.SearchEngine; import org.eclipse.wst.jsdt.core.search.SearchParticipant; +import org.eclipse.wst.jsdt.internal.compiler.util.SimpleLookupTable; import org.eclipse.wst.jsdt.internal.compiler.util.Util; import org.eclipse.wst.jsdt.internal.core.JavaModelManager; import org.eclipse.wst.jsdt.internal.core.index.Index; @@ -28,13 +33,23 @@ import org.eclipse.wst.jsdt.internal.core.search.processing.JobManager; class AddLibraryFileToIndex extends IndexRequest { IPath absolutePath; + + char[][] inclusionPatterns; + char[][] exclusionPatterns; + public AddLibraryFileToIndex(IFile resource, IndexManager manager) { super(resource.getFullPath(), manager); this.absolutePath=resource.getLocation(); } public AddLibraryFileToIndex(IPath jarPath, IndexManager manager) { // external JAR scenario - no resource - super(jarPath, manager); + this(jarPath, null, null, manager); + } + + public AddLibraryFileToIndex(IPath filePath, char[][] inclusionPatterns, char[][] exclusionPatterns, IndexManager manager) { + super(filePath, manager); + this.inclusionPatterns = inclusionPatterns; + this.exclusionPatterns = exclusionPatterns; } public boolean equals(Object o) { if (o instanceof AddLibraryFileToIndex) { @@ -49,7 +64,6 @@ class AddLibraryFileToIndex extends IndexRequest { return -1; } public boolean execute(IProgressMonitor progressMonitor) { - if (this.isCancelled || progressMonitor != null && progressMonitor.isCanceled()) return true; try { @@ -96,43 +110,46 @@ class AddLibraryFileToIndex extends IndexRequest { org.eclipse.wst.jsdt.internal.core.util.Util.verbose("-> indexing " + libraryFilePath.toString()); //$NON-NLS-1$ long initialTime = System.currentTimeMillis(); -// String[] paths = index.queryDocumentNames(""); // all file names //$NON-NLS-1$ -// if (paths != null) { -// int max = paths.length; -// /* check integrity of the existing index file -// * if the length is equal to 0, we want to index the whole jar again -// * If not, then we want to check that there is no missing entry, if -// * one entry is missing then we recreate the index -// */ -// String EXISTS = "OK"; //$NON-NLS-1$ -// String DELETED = "DELETED"; //$NON-NLS-1$ -// SimpleLookupTable indexedFileNames = new SimpleLookupTable(max == 0 ? 33 : max + 11); -// for (int i = 0; i < max; i++) -// indexedFileNames.put(paths[i], DELETED); -// -// if (Util.isClassFileName(libraryFilePath.toPortableString())) -// indexedFileNames.put(libraryFilePath.toPortableString(), EXISTS); -// -// boolean needToReindex = indexedFileNames.elementSize != max; // a new file was added -// if (!needToReindex) { -// Object[] valueTable = indexedFileNames.valueTable; -// for (int i = 0, l = valueTable.length; i < l; i++) { -// if (valueTable[i] == DELETED) { -// needToReindex = true; // a file was deleted so re-index -// break; -// } -// } -// if (!needToReindex) { -// if (JobManager.VERBOSE) -// org.eclipse.wst.jsdt.internal.core.util.Util.verbose("-> no indexing required (index is consistent with library) for " //$NON-NLS-1$ -// + zip.getName() + " (" //$NON-NLS-1$ -// + (System.currentTimeMillis() - initialTime) + "ms)"); //$NON-NLS-1$ -// this.manager.saveIndex(index); // to ensure its placed into the saved state -// return true; -// } -// } -// } -// + // check if the file is not a JavaScript file (like a .jar) + if(Util.isArchiveFileName(libraryFilePath.lastSegment())) { + String[] paths = index.queryDocumentNames(""); // all file names //$NON-NLS-1$ + if (paths != null) { + int max = paths.length; + /* check integrity of the existing index file + * if the length is equal to 0, we want to index the whole jar again + * If not, then we want to check that there is no missing entry, if + * one entry is missing then we recreate the index + */ + String EXISTS = "OK"; //$NON-NLS-1$ + String DELETED = "DELETED"; //$NON-NLS-1$ + SimpleLookupTable indexedFileNames = new SimpleLookupTable(max == 0 ? 33 : max + 11); + for (int i = 0; i < max; i++) + indexedFileNames.put(paths[i], DELETED); + + if (Util.isClassFileName(libraryFilePath.toPortableString())) + indexedFileNames.put(libraryFilePath.toPortableString(), EXISTS); + + boolean needToReindex = indexedFileNames.elementSize != max; // a new file was added + if (!needToReindex) { + Object[] valueTable = indexedFileNames.valueTable; + for (int i = 0, l = valueTable.length; i < l; i++) { + if (valueTable[i] == DELETED) { + needToReindex = true; // a file was deleted so re-index + break; + } + } + if (!needToReindex) { + if (JobManager.VERBOSE) + org.eclipse.wst.jsdt.internal.core.util.Util.verbose("-> no indexing required (index is consistent with library) for " //$NON-NLS-1$ + + libraryFilePath.lastSegment() + " (" //$NON-NLS-1$ + + (System.currentTimeMillis() - initialTime) + "ms)"); //$NON-NLS-1$ + this.manager.saveIndex(index); // to ensure its placed into the saved state + return true; + } + } + } + } + // Index the jar for the first time or reindex the jar in case the previous index file has been corrupted // index already existed: recreate it so that we forget about previous entries SearchParticipant participant = SearchEngine.getDefaultSearchParticipant(); @@ -143,29 +160,53 @@ class AddLibraryFileToIndex extends IndexRequest { return false; } -// for (Enumeration e = zip.entries(); e.hasMoreElements();) { -// if (this.isCancelled) { -// if (JobManager.VERBOSE) -// org.eclipse.wst.jsdt.internal.core.util.Util.verbose("-> indexing of " + zip.getName() + " has been cancelled"); //$NON-NLS-1$ //$NON-NLS-2$ -// return false; -// } -// -// // iterate each entry to index it -// ZipEntry ze = (ZipEntry) e.nextElement(); -// if (Util.isClassFileName(ze.getName())) { -// final byte[] classFileBytes = org.eclipse.wst.jsdt.internal.compiler.util.Util.getZipEntryByteContent(ze, zip); -// JavaSearchDocument entryDocument = new JavaSearchDocument(ze, libraryFilePath, classFileBytes, participant); -// this.manager.indexDocument(entryDocument, participant, index, this.containerPath); -// } -// } - IPath filePath=(this.absolutePath!=null)?this.absolutePath : this.containerPath; + IPath filePath = (this.absolutePath != null) ? this.absolutePath : this.containerPath; File file = new File(filePath.toOSString()); - if (file.isFile()) - indexFile(file, participant, index, libraryFilePath); - else - { - indexDirectory(file, participant, index, libraryFilePath); + if (file.isFile()) { + if (org.eclipse.wst.jsdt.internal.core.util.Util.isJavaLikeFileName(file.getName())) { + if (this.exclusionPatterns == null && this.inclusionPatterns == null) { + indexFile(file, participant, index, libraryFilePath); + } else { + if (!Util.isExcluded(file.getPath().toCharArray(), inclusionPatterns, exclusionPatterns, false)) { + indexFile(file, participant, index, libraryFilePath); + } + } + } + else if (org.eclipse.wst.jsdt.internal.compiler.util.Util.isArchiveFileName(file.getName())){ + ZipFile zip = new ZipFile(file); + for (Enumeration e = zip.entries(); e.hasMoreElements();) { + if (this.isCancelled) { + if (JobManager.VERBOSE) + org.eclipse.wst.jsdt.internal.core.util.Util.verbose("-> indexing of " + zip.getName() + " has been cancelled"); //$NON-NLS-1$ //$NON-NLS-2$ + return false; + } + + // iterate each entry to index it + ZipEntry ze = (ZipEntry) e.nextElement(); + if (Util.isClassFileName(ze.getName())) { + InputStreamReader inputStreamReader = new InputStreamReader(zip.getInputStream(ze), "utf8"); //$NON-NLS-1$ + StringBuffer buffer = new StringBuffer(); + char c[] = new char[2048]; + int length = 0; + while ((length = inputStreamReader.read(c)) > -1) { + buffer.append(c, 0, length); + } + JavaSearchDocument entryDocument = new JavaSearchDocument(ze, libraryFilePath, buffer.toString().toCharArray(), participant); + this.manager.indexDocument(entryDocument, participant, index, this.containerPath); + } + } + } + } else { + if (this.exclusionPatterns == null && this.inclusionPatterns == null) { + indexDirectory(file, participant, index, libraryFilePath); + } else if(exclusionPatterns != null && inclusionPatterns == null) { + if (!Util.isExcluded(file.getPath().toCharArray(), inclusionPatterns, exclusionPatterns, true)) { + indexDirectory(file, participant, index, libraryFilePath); + } + } else { + indexDirectory(file, participant, index, libraryFilePath); + } } this.manager.saveIndex(index); @@ -210,10 +251,26 @@ class AddLibraryFileToIndex extends IndexRequest { File[] files = file.listFiles(); if (files!=null) for (int i = 0; i < files.length; i++) { - if (files[i].isDirectory()) - indexDirectory(files[i], participant, index, libraryFilePath); - else if (Util.isClassFileName(files[i].getName())) - indexFile(files[i], participant, index, libraryFilePath); + if (files[i].isDirectory()) { + if (this.exclusionPatterns == null && this.inclusionPatterns == null) { + indexDirectory(files[i], participant, index, libraryFilePath); + } else if(exclusionPatterns != null && inclusionPatterns == null) { + if (!Util.isExcluded(files[i].getPath().toCharArray(), inclusionPatterns, exclusionPatterns, true)) { + indexDirectory(files[i], participant, index, libraryFilePath); + } + } else { + indexDirectory(files[i], participant, index, libraryFilePath); + } + } + else if (Util.isClassFileName(files[i].getName())) { + if (this.exclusionPatterns == null && this.inclusionPatterns == null) { + indexFile(files[i], participant, index, libraryFilePath); + } else { + if (!Util.isExcluded(files[i].getPath().toCharArray(), inclusionPatterns, exclusionPatterns, false)) { + indexFile(files[i], participant, index, libraryFilePath); + } + } + } } } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/IIndexConstants.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/IIndexConstants.java index 5d6366cf..41a4cc19 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/IIndexConstants.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/IIndexConstants.java @@ -14,43 +14,49 @@ package org.eclipse.wst.jsdt.internal.core.search.indexing; public interface IIndexConstants { /* index encoding */ - char[] REF= "ref".toCharArray(); //$NON-NLS-1$ - char[] METHOD_REF= "methodRef".toCharArray(); //$NON-NLS-1$ - char[] CONSTRUCTOR_REF= "constructorRef".toCharArray(); //$NON-NLS-1$ - char[] SUPER_REF = "superRef".toCharArray(); //$NON-NLS-1$ - char[] TYPE_DECL = "typeDecl".toCharArray(); //$NON-NLS-1$ - char[] METHOD_DECL= "methodDecl".toCharArray(); //$NON-NLS-1$ - char[] FUNCTION_DECL= "functionDecl".toCharArray(); //$NON-NLS-1$ - char[] CONSTRUCTOR_DECL= "constructorDecl".toCharArray(); //$NON-NLS-1$ - char[] FIELD_DECL= "fieldDecl".toCharArray(); //$NON-NLS-1$ - char[] VAR_DECL= "varDecl".toCharArray(); //$NON-NLS-1$ - char[] OBJECT = "Object".toCharArray(); //$NON-NLS-1$ - char[][] COUNTS= + final char[] REF= "ref".toCharArray(); //$NON-NLS-1$ + final char[] METHOD_REF= "methodRef".toCharArray(); //$NON-NLS-1$ + final char[] CONSTRUCTOR_REF= "constructorRef".toCharArray(); //$NON-NLS-1$ + final char[] SUPER_REF = "superRef".toCharArray(); //$NON-NLS-1$ + final char[] TYPE_DECL = "typeDecl".toCharArray(); //$NON-NLS-1$ + final char[] METHOD_DECL= "methodDecl".toCharArray(); //$NON-NLS-1$ + final char[] FUNCTION_DECL= "functionDecl".toCharArray(); //$NON-NLS-1$ + final char[] CONSTRUCTOR_DECL= "constructorDecl".toCharArray(); //$NON-NLS-1$ + final char[] FIELD_DECL= "fieldDecl".toCharArray(); //$NON-NLS-1$ + final char[] VAR_DECL= "varDecl".toCharArray(); //$NON-NLS-1$ + final char[] TYPE_SYNONYMS = "typeSynonyms".toCharArray(); //$NON-NLS-1$ + final char[] OBJECT = "Object".toCharArray(); //$NON-NLS-1$ + final char [] WINDOW = "Window".toCharArray(); //$NON-NLS-1$ + final char[] GLOBAL = "Global".toCharArray(); //$NON-NLS-1$ + final char[] GLOBAL_SYMBOL = "@G".toCharArray(); //$NON-NLS-1$ + final char[][] COUNTS= new char[][] { new char[] {'/', '0'}, new char[] {'/', '1'}, new char[] {'/', '2'}, new char[] {'/', '3'}, new char[] {'/', '4'}, new char[] {'/', '5'}, new char[] {'/', '6'}, new char[] {'/', '7'}, new char[] {'/', '8'}, new char[] {'/', '9'} }; - char CLASS_SUFFIX = 'C'; - char TYPE_SUFFIX = 0; - char SEPARATOR= '/'; - char PARAMETER_SEPARATOR= ','; - char SECONDARY_SUFFIX = 'S'; + final char CLASS_SUFFIX = 'C'; + final char TYPE_SUFFIX = 0; + final char SEPARATOR= '/'; + final char PARAMETER_SEPARATOR= ','; + final char SECONDARY_SUFFIX = 'S'; + final char DOT = '.'; - char[] ONE_STAR = new char[] {'*'}; - char[][] ONE_STAR_CHAR = new char[][] {ONE_STAR}; + final char[] ONE_STAR = new char[] {'*'}; + final char[][] ONE_STAR_CHAR = new char[][] {ONE_STAR}; // used as special marker for enclosing type name of local and anonymous classes - char ZERO_CHAR = '0'; - char[] ONE_ZERO = new char[] { ZERO_CHAR }; - char[][] ONE_ZERO_CHAR = new char[][] {ONE_ZERO}; + final char ZERO_CHAR = '0'; + final char[] ONE_ZERO = new char[] { ZERO_CHAR }; + final char[][] ONE_ZERO_CHAR = new char[][] {ONE_ZERO}; - int PKG_REF_PATTERN = 0x0001; - int PKG_DECL_PATTERN = 0x0002; - int TYPE_REF_PATTERN = 0x0004; - int TYPE_DECL_PATTERN = 0x0008; - int SUPER_REF_PATTERN = 0x0010; - int CONSTRUCTOR_PATTERN = 0x0020; - int FIELD_PATTERN = 0x0040; - int METHOD_PATTERN = 0x0080; - int OR_PATTERN = 0x0100; - int LOCAL_VAR_PATTERN = 0x0200; + final int PKG_REF_PATTERN = 0x0001; + final int PKG_DECL_PATTERN = 0x0002; + final int TYPE_REF_PATTERN = 0x0004; + final int TYPE_DECL_PATTERN = 0x0008; + final int SUPER_REF_PATTERN = 0x0010; + final int CONSTRUCTOR_PATTERN = 0x0020; + final int FIELD_PATTERN = 0x0040; + final int METHOD_PATTERN = 0x0080; + final int OR_PATTERN = 0x0100; + final int LOCAL_VAR_PATTERN = 0x0200; + final int TYPE_SYNONYMS_PATTERN = 0x0300; } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/IndexManager.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/IndexManager.java index fc1ad236..c590828c 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/IndexManager.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/IndexManager.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -391,14 +391,17 @@ public void indexLibrary(IIncludePathEntry entry, IProject requestingProject) { if (JavaScriptCore.getPlugin() == null) return; IndexRequest request = null; Object target = JavaModel.getTarget(ResourcesPlugin.getWorkspace().getRoot(), entry.getPath(), true); + char[][] inclusionPatterns = ((ClasspathEntry)entry).fullInclusionPatternChars(); + char[][] exclusionPatterns = ((ClasspathEntry)entry).fullExclusionPatternChars(); + if(target instanceof IFolder || target instanceof IProject){ - char[][] inclusionPatterns = ((ClasspathEntry)entry).fullInclusionPatternChars(); - char[][] exclusionPatterns = ((ClasspathEntry)entry).fullExclusionPatternChars(); - request = new AddLibraryFolderToIndex(entry.getPath(), requestingProject, inclusionPatterns, exclusionPatterns, this); - }else - request = new AddLibraryFileToIndex(entry.getPath(), this); + } + else if (target instanceof IFile) + request = new AddLibraryFileToIndex((IFile) target, this); + else + request = new AddLibraryFileToIndex(entry.getPath(), inclusionPatterns, exclusionPatterns, this); if (!isJobWaiting(request)) this.request(request); @@ -494,11 +497,13 @@ private void rebuildIndex(IPath indexLocation, IPath containerPath) { request = new IndexAllProject(p, this); } else if (target instanceof IFolder) { request = new IndexBinaryFolder((IFolder) target, this); -// } else if (target instanceof IFile) { -// request = new AddJarFileToIndex((IFile) target, this); + } else if (target instanceof IFile && org.eclipse.wst.jsdt.internal.compiler.util.Util.isArchiveFileName(((IFile)target).getName())) { + request = new AddJarFileToIndex((IFile) target, this); } else if (target instanceof File) { - request = new AddLibraryFileToIndex(containerPath, this); -// request = new AddJarFileToIndex(containerPath, this); + if (org.eclipse.wst.jsdt.internal.compiler.util.Util.isArchiveFileName(((File) target).getName())) + request = new AddJarFileToIndex(containerPath, this); + else + request = new AddLibraryFileToIndex(containerPath, this); } if (request != null) request(request); @@ -637,6 +642,35 @@ public synchronized void reset() { this.indexLocations = new SimpleLookupTable(); this.javaPluginLocation = null; } +/** + * Resets the index for a given path. + * Returns true if the index was reset, false otherwise. + */ +public synchronized boolean resetIndex(IPath containerPath) { + // only called to over write an existing cached index... + String containerPathString = containerPath.getDevice() == null ? containerPath.toString() : containerPath.toOSString(); + try { + // Path is already canonical + IPath indexLocation = computeIndexLocation(containerPath); + Index index = getIndex(indexLocation); + if (VERBOSE) { + Util.verbose("-> reseting index: "+indexLocation+" for path: "+containerPathString); //$NON-NLS-1$ //$NON-NLS-2$ + } + if (index == null) { + // the index does not exist, try to recreate it + return recreateIndex(containerPath) != null; + } + index.reset(); + return true; + } catch (IOException e) { + // The file could not be created. Possible reason: the project has been deleted. + if (VERBOSE) { + Util.verbose("-> failed to reset index for path: "+containerPathString); //$NON-NLS-1$ + e.printStackTrace(); + } + return false; + } +} public void saveIndex(Index index) throws IOException { // must have permission to write from the write monitor if (index.hasChanged()) { diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/IndexingParser.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/IndexingParser.java index f85199ce..5d62e484 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/IndexingParser.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/IndexingParser.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/SourceIndexer.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/SourceIndexer.java index dedc317d..25b3c0eb 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/SourceIndexer.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/SourceIndexer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -11,18 +11,30 @@ *******************************************************************************/ package org.eclipse.wst.jsdt.internal.core.search.indexing; +import java.io.File; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.Enumeration; +import java.util.zip.ZipEntry; +import java.util.zip.ZipException; +import java.util.zip.ZipFile; + import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.wst.jsdt.core.JavaScriptCore; import org.eclipse.wst.jsdt.core.search.SearchDocument; +import org.eclipse.wst.jsdt.core.search.SearchEngine; +import org.eclipse.wst.jsdt.core.search.SearchParticipant; import org.eclipse.wst.jsdt.internal.compiler.SourceElementParser; import org.eclipse.wst.jsdt.internal.compiler.util.SuffixConstants; +import org.eclipse.wst.jsdt.internal.compiler.util.Util; import org.eclipse.wst.jsdt.internal.core.BasicCompilationUnit; import org.eclipse.wst.jsdt.internal.core.JavaModelManager; +import org.eclipse.wst.jsdt.internal.core.Logger; +import org.eclipse.wst.jsdt.internal.core.index.Index; import org.eclipse.wst.jsdt.internal.core.search.JavaSearchDocument; -import org.eclipse.wst.jsdt.internal.core.search.processing.JobManager; import org.eclipse.wst.jsdt.internal.oaametadata.LibraryAPIs; import org.eclipse.wst.jsdt.internal.oaametadata.MetadataReader; import org.eclipse.wst.jsdt.internal.oaametadata.MetadataSourceElementNotifier; @@ -79,9 +91,7 @@ public class SourceIndexer extends AbstractIndexer implements SuffixConstants { try { parser.parseCompilationUnit(compilationUnit, true/*full parse*/); } catch (Exception e) { - if (JobManager.VERBOSE) { - e.printStackTrace(); - } + Logger.logException("Error while indexing document", e); } } public void indexMetadata() { @@ -112,5 +122,52 @@ public class SourceIndexer extends AbstractIndexer implements SuffixConstants { new MetadataSourceElementNotifier(apis,requestor).notifyRequestor(); } + public void indexArchive() { + /* + * index the individual documents in the archive into the single index + * file for the archive's path + */ + IPath jarPath = new Path(this.document.getPath()); + + File file = new File(jarPath.toOSString()); + if (file.isFile()) { + IndexManager indexManager = JavaModelManager.getJavaModelManager().getIndexManager(); + Index index = indexManager.getIndexForUpdate(jarPath, false /*don't reuse index file*/, true /*create if none*/); + SearchParticipant participant = SearchEngine.getDefaultSearchParticipant(); + ZipFile zip = null; + try { + zip = new ZipFile(file); + for (Enumeration e = zip.entries(); e.hasMoreElements();) { + // iterate each entry to index it + ZipEntry ze = (ZipEntry) e.nextElement(); + if (Util.isClassFileName(ze.getName())) { + final byte[] classFileBytes = org.eclipse.wst.jsdt.internal.compiler.util.Util.getZipEntryByteContent(ze, zip); + JavaSearchDocument entryDocument = new JavaSearchDocument(ze, jarPath, ByteBuffer.wrap(classFileBytes).asCharBuffer().array(), participant); + indexManager.indexDocument(entryDocument, participant, index, jarPath); + } + } + indexManager.saveIndex(index); + } + catch (ZipException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + finally { + if (zip != null) { + try { + zip.close(); + } + catch (IOException e) { + } + if(index != null) { + } + } + } + } + } } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/SourceIndexerRequestor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/SourceIndexerRequestor.java index 5fadb995..7143f3c3 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/SourceIndexerRequestor.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/indexing/SourceIndexerRequestor.java @@ -65,8 +65,8 @@ public void acceptLineSeparatorPositions(int[] positions) { /** * @see ISourceElementRequestor#acceptMethodReference(char[], int, int) */ -public void acceptMethodReference(char[] methodName, int argCount, int sourcePosition) { - this.indexer.addMethodReference(methodName, argCount); +public void acceptMethodReference(char[] methodName, int sourcePosition) { + this.indexer.addMethodReference(methodName); } /** * @see ISourceElementRequestor#acceptPackage(int, int, char[]) @@ -126,7 +126,14 @@ public char[][] enclosingTypeNames(){ } private void enterClass(TypeInfo typeInfo) { - if(typeInfo.anonymousMember) { + /* do not enter the "fake" GLOBAL type, otherwise + * would have to build every file when doing global searches + */ + if(typeInfo.name == IIndexConstants.GLOBAL_SYMBOL) { + return; + } + + if(typeInfo.anonymousMember && !typeInfo.isIndexed) { this.pushTypeName(typeInfo.name); return; } @@ -147,12 +154,11 @@ private void enterClass(TypeInfo typeInfo) { char [] typeName=typeInfo.name; char [] pkgName=this.packageName; int index; - if ( (index=CharOperation.lastIndexOf('.',typeName)) >0) - { + if ( (index=CharOperation.lastIndexOf('.',typeName)) >0) { pkgName=CharOperation.subarray(typeName, 0, index); typeName=CharOperation.subarray(typeName, index+1, typeName.length); } - this.indexer.addClassDeclaration(typeInfo.modifiers, pkgName, typeName, typeNames, typeInfo.superclass, typeInfo.secondary); + this.indexer.addClassDeclaration(typeInfo.modifiers, pkgName, typeName, typeNames, typeInfo.superclass, typeInfo.secondary, typeInfo.synonyms); this.pushTypeName(typeInfo.name); } /** @@ -172,11 +178,10 @@ public void enterConstructor(MethodInfo methodInfo) { * @see ISourceElementRequestor#enterField(FieldInfo) */ public void enterField(FieldInfo fieldInfo) { - if (depth>0 || this.methodDepth==0) - { - boolean isVar=depth==0; - this.indexer.addFieldDeclaration(fieldInfo.type, fieldInfo.name,isVar); - } + boolean isVar=depth==0; + this.indexer.addFieldDeclaration(fieldInfo.type, fieldInfo.name, fieldInfo.declaringType, fieldInfo.modifiers, + isVar); + this.methodDepth++; } /** @@ -190,7 +195,9 @@ public void enterInitializer(int declarationSourceStart, int modifiers) { */ public void enterMethod(MethodInfo methodInfo) { boolean isFunction=this.depth==0; - this.indexer.addMethodDeclaration(methodInfo.name, methodInfo.parameterTypes, methodInfo.returnType,isFunction); + this.indexer.addMethodDeclaration(methodInfo.name, methodInfo.parameterTypes, + methodInfo.parameterNames, methodInfo.returnType, methodInfo.declaringType, + isFunction, methodInfo.modifiers); this.methodDepth++; } /** diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/ClassFileMatchLocator.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/ClassFileMatchLocator.java index 66989681..b775ece3 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/ClassFileMatchLocator.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/ClassFileMatchLocator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -17,7 +17,6 @@ import org.eclipse.wst.jsdt.core.Signature; import org.eclipse.wst.jsdt.core.compiler.CharOperation; import org.eclipse.wst.jsdt.core.search.SearchMatch; import org.eclipse.wst.jsdt.core.search.SearchPattern; -import org.eclipse.wst.jsdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.wst.jsdt.internal.compiler.env.IBinaryField; import org.eclipse.wst.jsdt.internal.compiler.env.IBinaryMethod; import org.eclipse.wst.jsdt.internal.compiler.env.IBinaryType; @@ -32,6 +31,7 @@ import org.eclipse.wst.jsdt.internal.core.ResolvedBinaryField; import org.eclipse.wst.jsdt.internal.core.ResolvedBinaryMethod; import org.eclipse.wst.jsdt.internal.core.ResolvedBinaryType; import org.eclipse.wst.jsdt.internal.core.search.indexing.IIndexConstants; +import org.eclipse.wst.jsdt.internal.core.util.QualificationHelpers; public class ClassFileMatchLocator implements IIndexConstants { @@ -61,6 +61,14 @@ private boolean checkTypeName(char[] simpleName, char[] qualification, char[] fu if (wildcardPattern == null) return true; return CharOperation.match(wildcardPattern, fullyQualifiedTypeName, isCaseSensitive); } + +private boolean checkTypeName(char[] typeName1, char[] typeName2, boolean isCaseSensitive, boolean isCamelCase) { + char[][] typeNameSeperated = QualificationHelpers.seperateFullyQualifedName(typeName1); + + char[] wildcardPattern = PatternLocator.qualifiedPattern(typeNameSeperated[QualificationHelpers.SIMPLE_NAMES_INDEX], typeNameSeperated[QualificationHelpers.QULIFIERS_INDEX]); + if (wildcardPattern == null) return true; + return CharOperation.match(wildcardPattern, typeName2, isCaseSensitive); +} /** * Locate declaration in the current class file. This class file is always in a jar. */ @@ -192,7 +200,7 @@ boolean matchField(FieldPattern pattern, Object binaryInfo, IBinaryType enclosin IBinaryField field = (IBinaryField) binaryInfo; if (!pattern.matchesName(pattern.name, field.getName())) return false; - if (!checkDeclaringType(enclosingBinaryType, pattern.declaringSimpleName, pattern.declaringQualification, pattern.isCaseSensitive(), pattern.isCamelCase())) + if (!checkDeclaringType(enclosingBinaryType, pattern.getDeclaringSimpleName(), pattern.getDeclaringQualification(), pattern.isCaseSensitive(), pattern.isCamelCase())) return false; char[] fieldTypeSignature = Signature.toCharArray(convertClassFileFormat(field.getTypeName())); @@ -204,11 +212,11 @@ boolean matchMethod(MethodPattern pattern, Object binaryInfo, IBinaryType enclos IBinaryMethod method = (IBinaryMethod) binaryInfo; if (!pattern.matchesName(pattern.selector, method.getSelector())) return false; - if (!checkDeclaringType(enclosingBinaryType, pattern.declaringSimpleName, pattern.declaringQualification, pattern.isCaseSensitive(), pattern.isCamelCase())) + if (!checkDeclaringType(enclosingBinaryType, pattern.getDeclaringSimpleName(), pattern.getDeclaringQualification(), pattern.isCaseSensitive(), pattern.isCamelCase())) return false; // look at return type only if declaring type is not specified - boolean checkReturnType = pattern.declaringSimpleName == null && (pattern.returnSimpleName != null || pattern.returnQualification != null); + boolean checkReturnType = pattern.getDeclaringSimpleName() == null && (pattern.returnSimpleName != null || pattern.returnQualification != null); boolean checkParameters = pattern.parameterSimpleNames != null; if (checkReturnType || checkParameters) { char[] methodDescriptor = convertClassFileFormat(method.getMethodDescriptor()); @@ -230,7 +238,7 @@ boolean matchSuperTypeReference(SuperTypeReferencePattern pattern, Object binary char[] vmName = type.getSuperclassName(); if (vmName != null) { char[] superclassName = convertClassFileFormat(vmName); - if (checkTypeName(pattern.superSimpleName, pattern.superQualification, superclassName, pattern.isCaseSensitive(), pattern.isCamelCase())) + if (checkTypeName(pattern.typeName, superclassName, pattern.isCaseSensitive(), pattern.isCamelCase())) return true; } return false; @@ -240,27 +248,20 @@ boolean matchTypeDeclaration(TypeDeclarationPattern pattern, Object binaryInfo, IBinaryType type = (IBinaryType) binaryInfo; char[] fullyQualifiedTypeName = convertClassFileFormat(type.getName()); - boolean qualifiedPattern = pattern instanceof QualifiedTypeDeclarationPattern; - if (pattern.enclosingTypeNames == null || qualifiedPattern) { + if (pattern.enclosingTypeNames == null) { char[] simpleName = (pattern.getMatchMode() == SearchPattern.R_PREFIX_MATCH) ? CharOperation.concat(pattern.simpleName, IIndexConstants.ONE_STAR) : pattern.simpleName; - char[] pkg = qualifiedPattern ? ((QualifiedTypeDeclarationPattern)pattern).qualification : pattern.pkg; + char[] pkg = pattern.qualification; if (!checkTypeName(simpleName, pkg, fullyQualifiedTypeName, pattern.isCaseSensitive(), pattern.isCamelCase())) return false; } else { char[] enclosingTypeName = CharOperation.concatWith(pattern.enclosingTypeNames, '.'); - char[] patternString = pattern.pkg == null + char[] patternString = pattern.qualification == null ? enclosingTypeName - : CharOperation.concat(pattern.pkg, enclosingTypeName, '.'); + : CharOperation.concat(pattern.qualification, enclosingTypeName, '.'); if (!checkTypeName(pattern.simpleName, patternString, fullyQualifiedTypeName, pattern.isCaseSensitive(), pattern.isCamelCase())) return false; } - int kind = TypeDeclaration.kind(type.getModifiers()); - switch (pattern.typeSuffix) { - case CLASS_SUFFIX: - return kind == TypeDeclaration.CLASS_DECL; - case TYPE_SUFFIX: // nothing - } return true; } } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/ConstructorDeclarationPattern.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/ConstructorDeclarationPattern.java deleted file mode 100644 index 8cd2aa2c..00000000 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/ConstructorDeclarationPattern.java +++ /dev/null @@ -1,250 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.jsdt.internal.core.search.matching; - -import org.eclipse.wst.jsdt.core.compiler.CharOperation; -import org.eclipse.wst.jsdt.core.search.SearchPattern; -import org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants; - -/** - *

      Pattern used to find and store constructor declarations.

      - */ -public class ConstructorDeclarationPattern extends ConstructorPattern { - public int modifiers; - public char[][] parameterTypes; - public char[][] parameterNames; - - public ConstructorDeclarationPattern(char[] declaringSimpleName, int matchRule) { - this(matchRule); - this.declaringSimpleName = (this.isCaseSensitive || this.isCamelCase) ? declaringSimpleName : CharOperation.toLowerCase(declaringSimpleName); - this.findDeclarations = true; - this.findReferences = false; - this.parameterCount = -1; - } - - ConstructorDeclarationPattern(int matchRule) { - super(matchRule); - } - - public SearchPattern getBlankPattern() { - return new ConstructorDeclarationPattern(R_EXACT_MATCH | R_CASE_SENSITIVE); - } - public char[][] getIndexCategories() { - return DECL_CATEGORIES; - } - public boolean matchesDecodedKey(SearchPattern decodedPattern) { - ConstructorDeclarationPattern pattern = (ConstructorDeclarationPattern) decodedPattern; - - return (this.parameterCount == pattern.parameterCount || this.parameterCount == -1 || this.varargs) - && matchesName(this.declaringSimpleName, pattern.declaringSimpleName); - } - - /** - *

      Decodes an index key made with {@link #createDeclarationIndexKey(char[], int, char[][], char[][], int)} into the - * parameters of this pattern.

      - * - * @see org.eclipse.wst.jsdt.internal.core.search.matching.ConstructorPattern#decodeIndexKey(char[]) - * - * @see #createDeclarationIndexKey(char[], int, char[][], char[][], int) - */ - public void decodeIndexKey(char[] key) { - //decode type name - int last = key.length - 1; - int slash = CharOperation.indexOf(SEPARATOR, key, 0); - this.declaringSimpleName = CharOperation.subarray(key, 0, slash); - - int start = slash + 1; - slash = CharOperation.indexOf(SEPARATOR, key, start); - last = slash - 1; - - //decode parameter count - this.parameterCount = 0; - int power = 1; - for (int i = last; i >= start; i--) { - if (i == last) { - this.parameterCount = key[i] - '0'; - } else { - power *= 10; - this.parameterCount += power * (key[i] - '0'); - } - } - - // initialize optional fields - this.modifiers = 0; - this.parameterTypes = null; - this.parameterNames = null; - - /* if no parameters just decode modifiers - * else decode parameters and modifiers - */ - start = slash + 1; - if (this.parameterCount == 0) { - slash = slash + 3; - last = slash - 1; - - this.modifiers = key[last-1] + (key[last]<<16); - } else if (this.parameterCount > 0){ - slash = CharOperation.indexOf(SEPARATOR, key, start); - last = slash - 1; - - - this.parameterTypes = CharOperation.splitOn(PARAMETER_SEPARATOR, key, start, slash); - - start = slash + 1; - slash = CharOperation.indexOf(SEPARATOR, key, start); - last = slash - 1; - - if (slash != start) { - this.parameterNames = CharOperation.splitOn(PARAMETER_SEPARATOR, key, start, slash); - } - - slash = slash + 3; - last = slash - 1; - - this.modifiers = key[last-1] + (key[last]<<16); - } else { - this.modifiers = ClassFileConstants.AccPublic; - } - } - - /** - *

      Creates a constructor index key based on the given information to be placed in the index.

      - * - * @param typeName Name of the type the constructor is for - * @param parameterCount Number of parameters for the constructor, or -1 for a default constructor - * @param parameterTypes Type names of the parameters, should be same length as parameterCount - * @param parameterNames Names of the parameters, should be same length as parameterCount - * @param modifiers Modifiers to the constructor such as public/private - * - * @return Constructor index key based on the given information to be used in an index - */ - public static char[] createDeclarationIndexKey( - char[] typeName, - int parameterCount, - char[][] parameterTypes, - char[][] parameterNames, - int modifiers) { - - char[] countChars; - char[] parameterTypesChars = null; - char[] parameterNamesChars = null; - - //use pre-made char array for arg counts less then 10, else build a new one - countChars = parameterCount < 10 ? COUNTS[parameterCount] : ("/" + String.valueOf(parameterCount)).toCharArray(); //$NON-NLS-1$ - - if (parameterCount > 0) { - //get param types - if (parameterTypes != null && parameterTypes.length == parameterCount) { - char[][] parameterTypeErasures = new char[parameterCount][]; - for (int i = 0; i < parameterTypes.length; i++) { - parameterTypeErasures[i] = getTypeErasure(parameterTypes[i]); - } - parameterTypesChars = CharOperation.concatWith(parameterTypeErasures, PARAMETER_SEPARATOR, false); - } - - //get param names - if (parameterNames != null && parameterNames.length == parameterCount) { - parameterNamesChars = CharOperation.concatWith(parameterNames, PARAMETER_SEPARATOR); - } - } - - //get lengths - int typeNameLength = typeName == null ? 0 : typeName.length; - int countCharsLength = countChars.length; - int parameterTypesLength = parameterTypesChars == null ? 0 : parameterTypesChars.length; - int parameterNamesLength = parameterNamesChars == null ? 0 : parameterNamesChars.length; - - int resultLength = typeNameLength + countCharsLength; - - //add length for parameters and separators - if (parameterCount > 0) { - resultLength += parameterTypesLength + parameterNamesLength + 2; //SEPARATOR=1 + SEPARATOR=1 - } - - //add length for modifiers and separator - resultLength += 3; - - //create result char array - char[] result = new char[resultLength]; - - //add type name to result - int pos = 0; - if (typeNameLength > 0) { - System.arraycopy(typeName, 0, result, pos, typeNameLength); - pos += typeNameLength; - } - - //add param count to result - if (countCharsLength > 0) { - System.arraycopy(countChars, 0, result, pos, countCharsLength); - pos += countCharsLength; - } - - // if params add to result - if (parameterCount > 0) { - //add param types - result[pos++] = SEPARATOR; - if (parameterTypesLength > 0) { - System.arraycopy(parameterTypesChars, 0, result, pos, parameterTypesLength); - - pos += parameterTypesLength; - } - - //add param names - result[pos++] = SEPARATOR; - if (parameterNamesLength > 0) { - System.arraycopy(parameterNamesChars, 0, result, pos, parameterNamesLength); - pos += parameterNamesLength; - } - - } - - //add modifiers - result[pos++] = SEPARATOR; - result[pos++] = (char) modifiers; - result[pos++] = (char) (modifiers>>16); - - return result; - } - - private static char[] getTypeErasure(char[] typeName) { - char[] typeErasurename = new char[0]; - if(typeName != null) { - int index; - if ((index = CharOperation.indexOf('<', typeName)) == -1) return typeName; - - int length = typeName.length; - typeErasurename = new char[length - 2]; - - System.arraycopy(typeName, 0, typeErasurename, 0, index); - - int depth = 1; - for (int i = index + 1; i < length; i++) { - switch (typeName[i]) { - case '<': - depth++; - break; - case '>': - depth--; - break; - default: - if (depth == 0) { - typeErasurename[index++] = typeName[i]; - } - break; - } - } - - System.arraycopy(typeErasurename, 0, typeErasurename = new char[index], 0, index); - } - return typeErasurename; - } -} diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/ConstructorLocator.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/ConstructorLocator.java index 1dbbf080..bb34f966 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/ConstructorLocator.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/ConstructorLocator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -13,8 +13,8 @@ package org.eclipse.wst.jsdt.internal.core.search.matching; import org.eclipse.core.runtime.CoreException; import org.eclipse.wst.jsdt.core.IJavaScriptElement; import org.eclipse.wst.jsdt.core.compiler.CharOperation; +import org.eclipse.wst.jsdt.core.infer.InferredMethod; import org.eclipse.wst.jsdt.core.search.SearchMatch; -import org.eclipse.wst.jsdt.core.search.SearchPattern; import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode; import org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.wst.jsdt.internal.compiler.ast.AllocationExpression; @@ -35,324 +35,416 @@ import org.eclipse.wst.jsdt.internal.compiler.util.Util; public class ConstructorLocator extends PatternLocator { -protected ConstructorPattern pattern; + protected ConstructorPattern pattern; -public ConstructorLocator(ConstructorPattern pattern) { - super(pattern); + public ConstructorLocator(ConstructorPattern pattern) { + super(pattern); - this.pattern = pattern; -} -public int match(ASTNode node, MatchingNodeSet nodeSet) { // interested in ExplicitConstructorCall - if (!this.pattern.findReferences) return IMPOSSIBLE_MATCH; - if (!(node instanceof ExplicitConstructorCall)) return IMPOSSIBLE_MATCH; + this.pattern = pattern; + } - if (!matchParametersCount(node, ((ExplicitConstructorCall) node).arguments)) return IMPOSSIBLE_MATCH; + public int match(ASTNode node, MatchingNodeSet nodeSet) { // interested in + // ExplicitConstructorCall + if (!this.pattern.findReferences) + return IMPOSSIBLE_MATCH; + if (!(node instanceof ExplicitConstructorCall)) + return IMPOSSIBLE_MATCH; - return nodeSet.addMatch(node, ((InternalSearchPattern)this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH); -} -public int match(ConstructorDeclaration node, MatchingNodeSet nodeSet) { - int referencesLevel = this.pattern.findReferences ? matchLevelForReferences(node) : IMPOSSIBLE_MATCH; - int declarationsLevel = this.pattern.findDeclarations ? matchLevelForDeclarations(node) : IMPOSSIBLE_MATCH; + if (!matchParametersCount(node, ((ExplicitConstructorCall) node).arguments)) + return IMPOSSIBLE_MATCH; - return nodeSet.addMatch(node, referencesLevel >= declarationsLevel ? referencesLevel : declarationsLevel); // use the stronger match -} -public int match(Expression node, MatchingNodeSet nodeSet) { // interested in AllocationExpression - if (!this.pattern.findReferences) return IMPOSSIBLE_MATCH; - if (!(node instanceof AllocationExpression)) return IMPOSSIBLE_MATCH; - - // constructor name is simple type name - AllocationExpression allocation = (AllocationExpression) node; - char[] typeName = getTypeName(allocation); - if (typeName==null) - return IMPOSSIBLE_MATCH; + return nodeSet.addMatch(node, ((InternalSearchPattern) this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH); + } + + public int match(ConstructorDeclaration node, MatchingNodeSet nodeSet) { + int referencesLevel = this.pattern.findReferences ? matchLevelForReferences(node) : IMPOSSIBLE_MATCH; + int declarationsLevel = this.pattern.findDeclarations ? matchLevelForDeclarations(node) : IMPOSSIBLE_MATCH; + + return nodeSet.addMatch(node, referencesLevel >= declarationsLevel ? referencesLevel : declarationsLevel); // use + // the stronger match + } + + public int match(Expression node, MatchingNodeSet nodeSet) { // interested + // in AllocationExpression + if (!this.pattern.findReferences) + return IMPOSSIBLE_MATCH; + if (!(node instanceof AllocationExpression)) + return IMPOSSIBLE_MATCH; + + // constructor name is simple type name + AllocationExpression allocation = (AllocationExpression) node; + char[] typeName = getTypeName(allocation); + if (typeName == null) + return IMPOSSIBLE_MATCH; - if (this.pattern.declaringSimpleName != null && !matchesName(this.pattern.declaringSimpleName, typeName)) + if (matchesTypeName(typeName)) + return nodeSet.addMatch(node, ((InternalSearchPattern)this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH); + return IMPOSSIBLE_MATCH; + } -// if (!matchParametersCount(node, allocation.arguments)) return IMPOSSIBLE_MATCH; + private char[] getTypeName(AllocationExpression allocation) { + char[] typeName = null; - return nodeSet.addMatch(node, ((InternalSearchPattern)this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH); -} -private char[] getTypeName(AllocationExpression allocation) { - char[]typeName =null; -// if (allocation.type!=null) -// typeName = allocation.type.getTypeName(); -// else if (allocation.member instanceof SingleNameReference) - typeName= ((SingleNameReference)allocation.member).token; + typeName = ((SingleNameReference) allocation.member).token; else if (allocation.member instanceof FieldReference) - typeName=Util.getTypeName(allocation.member); - return typeName; -} -public int match(FieldDeclaration field, MatchingNodeSet nodeSet) { - if (!this.pattern.findReferences) return IMPOSSIBLE_MATCH; - // look only for enum constant - if (field.type != null || !(field.initialization instanceof AllocationExpression)) return IMPOSSIBLE_MATCH; - -// AllocationExpression allocation = (AllocationExpression) field.initialization; - if (field.binding != null && field.binding.declaringClass != null) { - if (this.pattern.declaringSimpleName != null && !matchesName(this.pattern.declaringSimpleName, field.binding.declaringClass.sourceName())) + typeName = Util.getTypeName(allocation.member); + return typeName; + } + + private boolean matchesTypeName(char[] typeName) { + char[] patternName; + if (this.pattern.getSearchPrefix() != null) { + patternName = this.pattern.getSearchPrefix(); + } else { + patternName = this.pattern.declaringSimpleName; + } + if (matchesName(patternName, typeName)) + return true; + char [] pkg = this.pattern.declaringQualification; + if (this.pattern.getSearchPrefix() == null && pkg != null) { + if (pkg.length>0 && + matchesName(CharOperation.concat(pkg, this.pattern.declaringSimpleName, '.'), typeName)) + return true; + } else { + int index=CharOperation.lastIndexOf('.', typeName); + if (index>=0 && + matchesName(patternName, CharOperation.subarray(typeName, index+1,typeName.length))) + return true; + } + return false; + } + + public int match(FieldDeclaration field, MatchingNodeSet nodeSet) { + if (!this.pattern.findReferences) + return IMPOSSIBLE_MATCH; + // look only for enum constant + if (field.type != null || !(field.initialization instanceof AllocationExpression)) + return IMPOSSIBLE_MATCH; + + // AllocationExpression allocation = (AllocationExpression) + // field.initialization; + if (field.binding != null && field.binding.declaringClass != null) { + if (this.pattern.declaringSimpleName != null && !matchesName(this.pattern.declaringSimpleName, field.binding.declaringClass.sourceName())) + return IMPOSSIBLE_MATCH; + } + + return nodeSet.addMatch(field, ((InternalSearchPattern) this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH); + } + + /** + * Special case for message send in javadoc comment. They can be in fact + * bound to a contructor. + * + * @see "http://bugs.eclipse.org/bugs/show_bug.cgi?id=83285" + */ + public int match(MessageSend msgSend, MatchingNodeSet nodeSet) { + if ((msgSend.bits & ASTNode.InsideJavadoc) == 0) return IMPOSSIBLE_MATCH; + if (this.pattern.declaringSimpleName == null || CharOperation.equals(msgSend.selector, this.pattern.declaringSimpleName)) { + return nodeSet.addMatch(msgSend, ((InternalSearchPattern) this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH); + } + return IMPOSSIBLE_MATCH; } -// if (!matchParametersCount(field, allocation.arguments)) return IMPOSSIBLE_MATCH; + public int match(TypeDeclaration node, MatchingNodeSet nodeSet) { + if (!this.pattern.findReferences) + return IMPOSSIBLE_MATCH; - return nodeSet.addMatch(field, ((InternalSearchPattern)this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH); -} -//public int match(FunctionDeclaration node, MatchingNodeSet nodeSet) - SKIP IT -/** - * Special case for message send in javadoc comment. They can be in fact bound to a contructor. - * @see "http://bugs.eclipse.org/bugs/show_bug.cgi?id=83285" - */ -public int match(MessageSend msgSend, MatchingNodeSet nodeSet) { - if ((msgSend.bits & ASTNode.InsideJavadoc) == 0) return IMPOSSIBLE_MATCH; - if (this.pattern.declaringSimpleName == null || CharOperation.equals(msgSend.selector, this.pattern.declaringSimpleName)) { - return nodeSet.addMatch(msgSend, ((InternalSearchPattern)this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH); + // need to look for a generated default constructor + return nodeSet.addMatch(node, ((InternalSearchPattern) this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH); } - return IMPOSSIBLE_MATCH; -} -//public int match(Reference node, MatchingNodeSet nodeSet) - SKIP IT -public int match(TypeDeclaration node, MatchingNodeSet nodeSet) { - if (!this.pattern.findReferences) return IMPOSSIBLE_MATCH; + + /** + * @see org.eclipse.wst.jsdt.internal.core.search.matching.PatternLocator#match(org.eclipse.wst.jsdt.core.infer.InferredMethod, org.eclipse.wst.jsdt.internal.core.search.matching.MatchingNodeSet) + */ + public int match(InferredMethod inferredMethod, MatchingNodeSet nodeSet) { + if (!this.pattern.findDeclarations) return IMPOSSIBLE_MATCH; + + //must be a constructor + if(!inferredMethod.isConstructor) return IMPOSSIBLE_MATCH; + + if (!matchesTypeName(inferredMethod.name)) + return IMPOSSIBLE_MATCH; - // need to look for a generated default constructor - return nodeSet.addMatch(node, ((InternalSearchPattern)this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH); -} -//public int match(TypeReference node, MatchingNodeSet nodeSet) - SKIP IT - -protected int matchConstructor(MethodBinding constructor) { - if (!constructor.isConstructor()) return IMPOSSIBLE_MATCH; - - // declaring type, simple name has already been matched by matchIndexEntry() - int level = resolveLevelForType(this.pattern.declaringSimpleName, this.pattern.declaringQualification, constructor.declaringClass); - if (level == IMPOSSIBLE_MATCH) return IMPOSSIBLE_MATCH; - - // parameter types - int parameterCount = this.pattern.parameterCount; - if (parameterCount > -1) { - if (constructor.parameters == null) return INACCURATE_MATCH; - if (parameterCount != constructor.parameters.length) return IMPOSSIBLE_MATCH; - for (int i = 0; i < parameterCount; i++) { - // TODO (frederic) use this call to refine accuracy on parameter types -// int newLevel = resolveLevelForType(this.pattern.parameterSimpleNames[i], this.pattern.parameterQualifications[i], this.pattern.parametersTypeArguments[i], 0, constructor.parameters[i]); - int newLevel = resolveLevelForType(this.pattern.parameterSimpleNames[i], this.pattern.parameterQualifications[i], constructor.parameters[i]); - if (level > newLevel) { - if (newLevel == IMPOSSIBLE_MATCH) { -// if (isErasureMatch) { -// return ERASURE_MATCH; -// } - return IMPOSSIBLE_MATCH; + // Verify parameters types + boolean resolve = false; + if (this.pattern.parameterSimpleNames != null) { + int length = this.pattern.parameterSimpleNames.length; + ASTNode[] args = ((AbstractMethodDeclaration)inferredMethod.getFunctionDeclaration()).arguments; + int argsLength = args == null ? 0 : args.length; + if (length != argsLength) return IMPOSSIBLE_MATCH; + for (int i = 0; i < argsLength; i++) { + if (args != null && !matchesTypeReference(this.pattern.parameterSimpleNames[i], ((Argument) args[i]).type)) { + // Do not return as impossible when source level is at least 1.5 + if (this.mayBeGeneric) { + if (!((InternalSearchPattern)this.pattern).mustResolve) { + // Set resolution flag on node set in case of types was inferred in parameterized types from generic ones... + // (see bugs https://bugs.eclipse.org/bugs/show_bug.cgi?id=79990, 96761, 96763) + nodeSet.mustResolve = true; + resolve = true; + } + } else { + return IMPOSSIBLE_MATCH; + } } - level = newLevel; // can only be downgraded } } + + // Method declaration may match pattern + return nodeSet.addMatch(inferredMethod , resolve ? POSSIBLE_MATCH : ACCURATE_MATCH); } - return level; -} -protected int matchContainer() { - if (this.pattern.findReferences) return ALL_CONTAINER; // handles both declarations + references & just references - // COMPILATION_UNIT_CONTAINER - implicit constructor call: case of Y extends X and Y doesn't define any constructor - // CLASS_CONTAINER - implicit constructor call: case of constructor declaration with no explicit super call - // METHOD_CONTAINER - reference in another constructor - // FIELD_CONTAINER - anonymous in a field initializer - - // declarations are only found in Class - return CLASS_CONTAINER; -} -protected int matchLevelForReferences(ConstructorDeclaration constructor) { - ExplicitConstructorCall constructorCall = constructor.constructorCall; - if (constructorCall == null || constructorCall.accessMode != ExplicitConstructorCall.ImplicitSuper) - return IMPOSSIBLE_MATCH; - if (this.pattern.parameterSimpleNames != null) { - int length = this.pattern.parameterSimpleNames.length; - Expression[] args = constructorCall.arguments; - int argsLength = args == null ? 0 : args.length; - if (length != argsLength) return IMPOSSIBLE_MATCH; + protected int matchConstructor(MethodBinding constructor) { + if (!constructor.isConstructor()) + return IMPOSSIBLE_MATCH; + + // declaring type, simple name has already been matched by + // matchIndexEntry() + int level; + if (this.pattern.getSearchPrefix() != null) { + level = resolveLevelUsingSearchPrefix(this.pattern.getSearchPrefix(), constructor.declaringClass); + } else { + level = resolveLevelForType(this.pattern.declaringSimpleName, this.pattern.declaringQualification, constructor.declaringClass); + } + if (level == IMPOSSIBLE_MATCH) + return IMPOSSIBLE_MATCH; + + // parameter types + int parameterCount = this.pattern.parameterNames != null ? this.pattern.parameterNames.length : 0; + if (parameterCount > -1) { + if (constructor.parameters == null) + return INACCURATE_MATCH; + if (parameterCount != constructor.parameters.length) + return IMPOSSIBLE_MATCH; + for (int i = 0; i < parameterCount; i++) { + // TODO (frederic) use this call to refine accuracy on + int newLevel = resolveLevelForType(this.pattern.parameterSimpleNames[i], this.pattern.parameterQualifications[i], constructor.parameters[i]); + if (level > newLevel) { + if (newLevel == IMPOSSIBLE_MATCH) { + return IMPOSSIBLE_MATCH; + } + level = newLevel; // can only be downgraded + } + } + } + return level; } - return ((InternalSearchPattern)this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH; -} -protected int matchLevelForDeclarations(ConstructorDeclaration constructor) { - // constructor name is stored in selector field - if (this.pattern.declaringSimpleName != null && !matchesName(this.pattern.declaringSimpleName, constructor.selector)) - return IMPOSSIBLE_MATCH; - if (this.pattern.parameterSimpleNames != null) { - int length = this.pattern.parameterSimpleNames.length; - Argument[] args = constructor.arguments; - int argsLength = args == null ? 0 : args.length; - if (length != argsLength) return IMPOSSIBLE_MATCH; + protected int matchContainer() { + if (this.pattern.findReferences) + return ALL_CONTAINER; // handles both declarations + references & + // just references + // COMPILATION_UNIT_CONTAINER - implicit constructor call: case of Y + // extends X and Y doesn't define any constructor + // CLASS_CONTAINER - implicit constructor call: case of constructor + // declaration with no explicit super call + // METHOD_CONTAINER - reference in another constructor + // FIELD_CONTAINER - anonymous in a field initializer + + // declarations are only found in Class + return CLASS_CONTAINER; } - // Verify type arguments (do not reject if pattern has no argument as it can be an erasure match) - if (this.pattern.hasConstructorArguments()) { - return IMPOSSIBLE_MATCH; + protected int matchLevelForReferences(ConstructorDeclaration constructor) { + ExplicitConstructorCall constructorCall = constructor.constructorCall; + if (constructorCall == null || constructorCall.accessMode != ExplicitConstructorCall.ImplicitSuper) + return IMPOSSIBLE_MATCH; + + if (this.pattern.parameterSimpleNames != null) { + int length = this.pattern.parameterSimpleNames.length; + Expression[] args = constructorCall.arguments; + int argsLength = args == null ? 0 : args.length; + if (length != argsLength) + return IMPOSSIBLE_MATCH; + } + return ((InternalSearchPattern) this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH; } - return ((InternalSearchPattern)this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH; -} -boolean matchParametersCount(ASTNode node, Expression[] args) { - if (this.pattern.parameterSimpleNames != null && (!this.pattern.varargs || ((node.bits & ASTNode.InsideJavadoc) != 0))) { - int length = this.pattern.parameterCount; - if (length < 0) length = this.pattern.parameterSimpleNames.length; - int argsLength = args == null ? 0 : args.length; - if (length != argsLength) { - return false; + protected int matchLevelForDeclarations(ConstructorDeclaration constructor) { + // constructor name is stored in selector field + if (this.pattern.declaringSimpleName != null && !matchesName(this.pattern.declaringSimpleName, constructor.getName())) + return IMPOSSIBLE_MATCH; + + if (this.pattern.parameterSimpleNames != null) { + int length = this.pattern.parameterSimpleNames.length; + Argument[] args = constructor.arguments; + int argsLength = args == null ? 0 : args.length; + if (length != argsLength) + return IMPOSSIBLE_MATCH; } + + return ((InternalSearchPattern) this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH; } - return true; -} -protected void matchReportReference(ASTNode reference, IJavaScriptElement element, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { - - MethodBinding constructorBinding = null; - boolean isSynthetic = false; - if (reference instanceof ExplicitConstructorCall) { - ExplicitConstructorCall call = (ExplicitConstructorCall) reference; - isSynthetic = call.isImplicitSuper(); - constructorBinding = call.binding; - } else if (reference instanceof AllocationExpression) { - AllocationExpression alloc = (AllocationExpression) reference; - constructorBinding = alloc.binding; - } else if (reference instanceof TypeDeclaration || reference instanceof FieldDeclaration) { - super.matchReportReference(reference, element, elementBinding, accuracy, locator); - if (match != null) return; + + boolean matchParametersCount(ASTNode node, Expression[] args) { + if (this.pattern.parameterSimpleNames != null && ((node.bits & ASTNode.InsideJavadoc) != 0)) { + int length = this.pattern.parameterNames != null ? this.pattern.parameterNames.length : 0; + if (length < 0) + length = this.pattern.parameterSimpleNames.length; + int argsLength = args == null ? 0 : args.length; + if (length != argsLength) { + return false; + } + } + return true; } - // Create search match - match = locator.newMethodReferenceMatch(element, elementBinding, accuracy, -1, -1, true, reference); + protected void matchReportReference(ASTNode reference, IJavaScriptElement element, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { + if (reference instanceof TypeDeclaration || reference instanceof FieldDeclaration) { + super.matchReportReference(reference, element, elementBinding, accuracy, locator); + if (match != null) + return; + } - if (this.pattern.hasConstructorArguments()) { // binding has no type params, compatible erasure if pattern does - match.setRule(SearchPattern.R_ERASURE_MATCH); - } + // Create search match + match = locator.newMethodReferenceMatch(element, elementBinding, accuracy, -1, -1, true, reference); - // See whether it is necessary to report or not - if (match.getRule() == 0) return; // impossible match - boolean report = (this.isErasureMatch && match.isErasure()) || (this.isEquivalentMatch && match.isEquivalent()) || match.isExact(); - if (!report) return; - - // Report match - int offset = reference.sourceStart; - match.setOffset(offset); - match.setLength(reference.sourceEnd - offset + 1); - if (reference instanceof FieldDeclaration) { // enum declaration - FieldDeclaration enumConstant = (FieldDeclaration) reference; - if (enumConstant.initialization instanceof QualifiedAllocationExpression) { - locator.reportAccurateEnumConstructorReference(match, enumConstant, (QualifiedAllocationExpression) enumConstant.initialization); + // See whether it is necessary to report or not + if (match.getRule() == 0) + return; // impossible match + boolean report = (this.isErasureMatch && match.isErasure()) || (this.isEquivalentMatch && match.isEquivalent()) || match.isExact(); + if (!report) return; + + // Report match + int offset = reference.sourceStart; + match.setOffset(offset); + match.setLength(reference.sourceEnd - offset + 1); + if (reference instanceof FieldDeclaration) { // enum declaration + FieldDeclaration enumConstant = (FieldDeclaration) reference; + if (enumConstant.initialization instanceof QualifiedAllocationExpression) { + locator.reportAccurateEnumConstructorReference(match, enumConstant, (QualifiedAllocationExpression) enumConstant.initialization); + return; + } } + locator.report(match); } - locator.report(match); -} -public SearchMatch newDeclarationMatch(ASTNode reference, IJavaScriptElement element, Binding binding, int accuracy, int length, MatchLocator locator) { - match = null; - int offset = reference.sourceStart; - if (this.pattern.findReferences) { - if (reference instanceof TypeDeclaration) { - TypeDeclaration type = (TypeDeclaration) reference; - AbstractMethodDeclaration[] methods = type.methods; - if (methods != null) { - for (int i = 0, max = methods.length; i < max; i++) { - AbstractMethodDeclaration method = methods[i]; - match = locator.newMethodReferenceMatch(element, binding, accuracy, offset, length, method.isConstructor(), method); + + public SearchMatch newDeclarationMatch(ASTNode reference, IJavaScriptElement element, Binding binding, int accuracy, int length, MatchLocator locator) { + match = null; + int offset = reference.sourceStart; + if (this.pattern.findReferences) { + if (reference instanceof TypeDeclaration) { + TypeDeclaration type = (TypeDeclaration) reference; + AbstractMethodDeclaration[] methods = type.methods; + if (methods != null) { + for (int i = 0, max = methods.length; i < max; i++) { + AbstractMethodDeclaration method = methods[i]; + match = locator.newMethodReferenceMatch(element, binding, accuracy, offset, length, method.isConstructor(), method); + } } } - } else if (reference instanceof ConstructorDeclaration) { - ConstructorDeclaration constructor = (ConstructorDeclaration) reference; - ExplicitConstructorCall call = constructor.constructorCall; - match = locator.newMethodReferenceMatch(element, binding, accuracy, offset, length, constructor.isConstructor(), constructor); + else if (reference instanceof ConstructorDeclaration) { + ConstructorDeclaration constructor = (ConstructorDeclaration) reference; + match = locator.newMethodReferenceMatch(element, binding, accuracy, offset, length, constructor.isConstructor(), constructor); + } } - } - if (match != null) { - return match; - } - // super implementation... - return locator.newDeclarationMatch(element, binding, accuracy, reference.sourceStart, length); -} -public int resolveLevel(ASTNode node) { - if (this.pattern.findReferences) { - if (node instanceof AllocationExpression) - return resolveLevel((AllocationExpression) node); - if (node instanceof ExplicitConstructorCall) - return resolveLevel(((ExplicitConstructorCall) node).binding); - if (node instanceof TypeDeclaration) - return resolveLevel((TypeDeclaration) node); - if (node instanceof FieldDeclaration) - return resolveLevel((FieldDeclaration) node); - if (node instanceof JavadocMessageSend) { - return resolveLevel(((JavadocMessageSend)node).binding); + if (match != null) { + return match; } + // super implementation... + return locator.newDeclarationMatch(element, binding, accuracy, reference.sourceStart, length); } - if (node instanceof ConstructorDeclaration) - return resolveLevel((ConstructorDeclaration) node, true); - return IMPOSSIBLE_MATCH; -} -protected int referenceType() { - return IJavaScriptElement.METHOD; -} -protected int resolveLevel(AllocationExpression allocation) { - // constructor name is simple type name - char[] typeName = getTypeName(allocation); - if (this.pattern.declaringSimpleName != null && !matchesName(this.pattern.declaringSimpleName, typeName)) - return IMPOSSIBLE_MATCH; - return resolveLevel(allocation.binding); -} -protected int resolveLevel(FieldDeclaration field) { - // only accept enum constants - if (field.type != null || field.binding == null) return IMPOSSIBLE_MATCH; - if (this.pattern.declaringSimpleName != null && !matchesName(this.pattern.declaringSimpleName, field.binding.type.sourceName())) + public int resolveLevel(ASTNode node) { + if (this.pattern.findReferences) { + if (node instanceof AllocationExpression) + return resolveLevel((AllocationExpression) node); + if (node instanceof ExplicitConstructorCall) + return resolveLevel(((ExplicitConstructorCall) node).binding); + if (node instanceof TypeDeclaration) + return resolveLevel((TypeDeclaration) node); + if (node instanceof FieldDeclaration) + return resolveLevel((FieldDeclaration) node); + if (node instanceof JavadocMessageSend) { + return resolveLevel(((JavadocMessageSend) node).binding); + } + } + if (node instanceof ConstructorDeclaration) + return resolveLevel((ConstructorDeclaration) node, true); return IMPOSSIBLE_MATCH; - if (!(field.initialization instanceof AllocationExpression) || field.initialization.resolvedType.isLocalType()) return IMPOSSIBLE_MATCH; + } - return resolveLevel(((AllocationExpression)field.initialization).binding); -} -public int resolveLevel(Binding binding) { - if (binding == null) return INACCURATE_MATCH; - if (!(binding instanceof MethodBinding)) return IMPOSSIBLE_MATCH; - - MethodBinding constructor = (MethodBinding) binding; - int level= matchConstructor(constructor); - if (level== IMPOSSIBLE_MATCH) { - if (constructor != constructor.original()) { - level= matchConstructor(constructor.original()); + protected int referenceType() { + return IJavaScriptElement.METHOD; + } + + protected int resolveLevel(AllocationExpression allocation) { + + return resolveLevel(allocation.binding); + } + + protected int resolveLevel(FieldDeclaration field) { + // only accept enum constants + if (field.type != null || field.binding == null) + return IMPOSSIBLE_MATCH; + if (this.pattern.declaringSimpleName != null && !matchesName(this.pattern.declaringSimpleName, field.binding.type.sourceName())) + return IMPOSSIBLE_MATCH; + if (!(field.initialization instanceof AllocationExpression) || field.initialization.resolvedType.isLocalType()) + return IMPOSSIBLE_MATCH; + + return resolveLevel(((AllocationExpression) field.initialization).binding); + } + + public int resolveLevel(Binding binding) { + if (binding == null) + return INACCURATE_MATCH; + if (!(binding instanceof MethodBinding)) + return IMPOSSIBLE_MATCH; + + MethodBinding constructor = (MethodBinding) binding; + int level = matchConstructor(constructor); + if (level == IMPOSSIBLE_MATCH) { + if (constructor != constructor.original()) { + level = matchConstructor(constructor.original()); + } } + return level; } - return level; -} -protected int resolveLevel(ConstructorDeclaration constructor, boolean checkDeclarations) { - int referencesLevel = IMPOSSIBLE_MATCH; - if (this.pattern.findReferences) { - ExplicitConstructorCall constructorCall = constructor.constructorCall; - if (constructorCall != null && constructorCall.accessMode == ExplicitConstructorCall.ImplicitSuper) { - // eliminate explicit super call as it will be treated with matchLevel(ExplicitConstructorCall, boolean) - int callCount = (constructorCall.arguments == null) ? 0 : constructorCall.arguments.length; - int patternCount = (this.pattern.parameterSimpleNames == null) ? 0 : this.pattern.parameterSimpleNames.length; - if (patternCount != callCount) { - referencesLevel = IMPOSSIBLE_MATCH; - } else { - referencesLevel = resolveLevel(constructorCall.binding); - if (referencesLevel == ACCURATE_MATCH) return ACCURATE_MATCH; // cannot get better + + protected int resolveLevel(ConstructorDeclaration constructor, boolean checkDeclarations) { + int referencesLevel = IMPOSSIBLE_MATCH; + if (this.pattern.findReferences) { + ExplicitConstructorCall constructorCall = constructor.constructorCall; + if (constructorCall != null && constructorCall.accessMode == ExplicitConstructorCall.ImplicitSuper) { + // eliminate explicit super call as it will be treated with + int callCount = (constructorCall.arguments == null) ? 0 : constructorCall.arguments.length; + int patternCount = (this.pattern.parameterSimpleNames == null) ? 0 : this.pattern.parameterSimpleNames.length; + if (patternCount != callCount) { + referencesLevel = IMPOSSIBLE_MATCH; + } + else { + referencesLevel = resolveLevel(constructorCall.binding); + if (referencesLevel == ACCURATE_MATCH) + return ACCURATE_MATCH; // cannot get better + } } } + if (!checkDeclarations) + return referencesLevel; + + int declarationsLevel = this.pattern.findDeclarations ? resolveLevel(constructor.getBinding()) : IMPOSSIBLE_MATCH; + return referencesLevel >= declarationsLevel ? referencesLevel : declarationsLevel; // answer + // the stronger match } - if (!checkDeclarations) return referencesLevel; - int declarationsLevel = this.pattern.findDeclarations ? resolveLevel(constructor.binding) : IMPOSSIBLE_MATCH; - return referencesLevel >= declarationsLevel ? referencesLevel : declarationsLevel; // answer the stronger match -} -protected int resolveLevel(TypeDeclaration type) { - // find default constructor - AbstractMethodDeclaration[] methods = type.methods; - if (methods != null) { - for (int i = 0, length = methods.length; i < length; i++) { - AbstractMethodDeclaration method = methods[i]; - if (method.isDefaultConstructor() && method.sourceStart < type.bodyStart) // if synthetic - return resolveLevel((ConstructorDeclaration) method, false); + protected int resolveLevel(TypeDeclaration type) { + // find default constructor + AbstractMethodDeclaration[] methods = type.methods; + if (methods != null) { + for (int i = 0, length = methods.length; i < length; i++) { + AbstractMethodDeclaration method = methods[i]; + if (method.isDefaultConstructor() && method.sourceStart < type.bodyStart) // if + // synthetic + return resolveLevel((ConstructorDeclaration) method, false); + } } + return IMPOSSIBLE_MATCH; + } + + public String toString() { + return "Locator for " + this.pattern.toString(); //$NON-NLS-1$ } - return IMPOSSIBLE_MATCH; -} -public String toString() { - return "Locator for " + this.pattern.toString(); //$NON-NLS-1$ -} } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/ConstructorPattern.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/ConstructorPattern.java index 3f458119..ba0a0c97 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/ConstructorPattern.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/ConstructorPattern.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2011, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -12,298 +12,597 @@ package org.eclipse.wst.jsdt.internal.core.search.matching; import java.io.IOException; -import org.eclipse.wst.jsdt.core.Flags; -import org.eclipse.wst.jsdt.core.IFunction; -import org.eclipse.wst.jsdt.core.JavaScriptModelException; import org.eclipse.wst.jsdt.core.compiler.CharOperation; import org.eclipse.wst.jsdt.core.search.SearchPattern; +import org.eclipse.wst.jsdt.internal.core.Logger; import org.eclipse.wst.jsdt.internal.core.index.EntryResult; import org.eclipse.wst.jsdt.internal.core.index.Index; -import org.eclipse.wst.jsdt.internal.core.util.Util; +import org.eclipse.wst.jsdt.internal.core.util.QualificationHelpers; +/** + *

      Pattern used to find and store constructor declarations.

      + */ public class ConstructorPattern extends JavaSearchPattern { + private final static char[][] REF_CATEGORIES = { CONSTRUCTOR_REF }; + private final static char[][] REF_AND_DECL_CATEGORIES = { CONSTRUCTOR_REF, CONSTRUCTOR_DECL }; + private final static char[][] DECL_CATEGORIES = { CONSTRUCTOR_DECL }; + + /** + *

      true if this pattern should match on constructor declarations, false otherwise.

      + */ + protected boolean findDeclarations; + + /** + *

      true if this pattern should match on constructor references, false otherwise.

      + */ + protected boolean findReferences; -protected boolean findDeclarations; -protected boolean findReferences; - -public char[] declaringQualification; -public char[] declaringSimpleName; - -public char[][] parameterQualifications; -public char[][] parameterSimpleNames; -public int parameterCount; -public boolean varargs = false; - -// Signatures and arguments for generic search -char[][][] parametersTypeSignatures; -char[][][][] parametersTypeArguments; -boolean constructorParameters = false; -char[][] constructorArguments; - -protected static char[][] REF_CATEGORIES = { CONSTRUCTOR_REF }; -protected static char[][] REF_AND_DECL_CATEGORIES = { CONSTRUCTOR_REF, CONSTRUCTOR_DECL }; -protected static char[][] DECL_CATEGORIES = { CONSTRUCTOR_DECL }; + /** + *

      Optional

      + * + *

      Qualification of the declaring type for this constructor.

      + */ + public char[] declaringQualification; + + /** + *

      Simple name of the declaring type for this constructor.

      + */ + public char[] declaringSimpleName; + + /** + *

      Optional

      + * + *

      Qualifications of the parameter types for this function.

      + * + *

      Note: If this field is defined then the {@link #parameterSimpleNames} must + * also be defined.

      + * + * @see #parameterSimpleNames + */ + public char[][] parameterQualifications; + + /** + *

      Optional

      + * + *

      Simple names of the parameter types for this constructor.

      + * + *

      Note: If this field is defined then the {@link #parameterQualifications} + * filed can be defined, but does not have to be.

      + * + * @see #parameterQualifications + */ + public char[][] parameterSimpleNames; + + /**

      names of the parameters

      */ + public char[][] parameterNames; + + /**

      Modifiers for the constructor

      */ + public int modifiers; + + /** + *

      Used when searing for constructors using a given prefix. + * This prefix will be used to match on either the {@link ConstructorPattern#declaringQualification} + * or the {@link ConstructorPattern#declaringSimpleName}.

      + * + * @see #ConstructorDeclarationPattern(char[], int) + * + * @see ConstructorPattern#declaringQualification + * @see ConstructorPattern#declaringSimpleName + */ + private char[] fSearchPrefix; -/** - * Constructor entries are encoded as TypeName '/' Arity: - * e.g. 'X/0' - */ -public static char[] createIndexKey(char[] typeName, int argCount) { - char[] countChars = argCount < 10 - ? COUNTS[argCount] - : ("/" + String.valueOf(argCount)).toCharArray(); //$NON-NLS-1$ - return CharOperation.concat(typeName, countChars); -} + /** + * + * @param matchRule + */ + private ConstructorPattern(int matchRule) { + super(CONSTRUCTOR_PATTERN, matchRule); + + this.findDeclarations = true; + this.findReferences = false; + } + + /** + *

      Constructor to use when the constructor declarations qualification and simple name + * are both known.

      + * + * @param declaringQualification + * @param declaringSimpleName + * @param matchRule + */ + public ConstructorPattern(char[] declaringQualification, char[] declaringSimpleName, int matchRule) { + this(matchRule); + + this.declaringQualification = (this.isCaseSensitive() || this.isCamelCase()) ? + declaringQualification : CharOperation.toLowerCase(declaringQualification); + this.declaringSimpleName = (this.isCaseSensitive() || this.isCamelCase()) ? + declaringSimpleName : CharOperation.toLowerCase(declaringSimpleName); + } + + /** + *

      Constructor to use when searching for a constructor declaration based on a given prefix.

      + * + * @param searchPrefix to match against either the fully qualified name or simple name of + * constructor declarations + * + * @param matchRule + * @deprecated + */ + public ConstructorPattern(char[] searchPrefix, int matchRule) { + this(matchRule); + + this.fSearchPrefix = searchPrefix; + } -ConstructorPattern(int matchRule) { - super(CONSTRUCTOR_PATTERN, matchRule); -} -public ConstructorPattern( - boolean findDeclarations, - boolean findReferences, - char[] declaringSimpleName, - char[] declaringQualification, - char[][] parameterQualifications, - char[][] parameterSimpleNames, - int matchRule) { + /** + *

      Constructor to use when searching for a constructor declaration based on a given prefix.

      + * + * @param searchPrefix to match against either the fully qualified name or simple name of + * constructor declarations + * @param findDeclarations return matches for declarations + * @param findReferences return matches for references + * @param matchRule one or more of the rule constants found in org.eclipse.wst.jsdt.core.search.SearchPattern + */ + public ConstructorPattern(char[] searchPrefix, int matchRule, boolean findDeclarations, boolean findReferences) { + this(matchRule); + + this.fSearchPrefix = (isCaseSensitive() || isCamelCase()) ? searchPrefix : CharOperation.toLowerCase(searchPrefix); + this.findDeclarations = findDeclarations; + this.findReferences = findReferences; + } + + /** + *

      Constructor to create a pattern that accepts all possible information about a constructor.

      + * + * @param findDeclarations + * @param findReferences + * @param declaringQualification + * @param declaringSimpleName + * @param parameterQualifications + * @param parameterSimpleNames + * @param matchRule + */ + public ConstructorPattern( + boolean findDeclarations, + boolean findReferences, + char[][] parameterQualifications, + char[][] parameterSimpleNames, + char[] declaringQualification, + char[] declaringSimpleName, + int matchRule) { - this(matchRule); + this(matchRule); - this.findDeclarations = findDeclarations; - this.findReferences = findReferences; + this.findDeclarations = findDeclarations; + this.findReferences = findReferences; - this.declaringQualification = isCaseSensitive() ? declaringQualification : CharOperation.toLowerCase(declaringQualification); - this.declaringSimpleName = (isCaseSensitive() || isCamelCase()) ? declaringSimpleName : CharOperation.toLowerCase(declaringSimpleName); - if (parameterSimpleNames != null) { - this.parameterCount = parameterSimpleNames.length; - boolean synthetic = this.parameterCount>0 && declaringQualification != null && CharOperation.equals(CharOperation.concat(parameterQualifications[0], parameterSimpleNames[0], '.'), declaringQualification); - int offset = 0; - if (synthetic) { - // skip first synthetic parameter - this.parameterCount--; - offset++; - } - this.parameterQualifications = new char[this.parameterCount][]; - this.parameterSimpleNames = new char[this.parameterCount][]; - for (int i = 0; i < this.parameterCount; i++) { - this.parameterQualifications[i] = isCaseSensitive() ? parameterQualifications[i+offset] : CharOperation.toLowerCase(parameterQualifications[i+offset]); - this.parameterSimpleNames[i] = isCaseSensitive() ? parameterSimpleNames[i+offset] : CharOperation.toLowerCase(parameterSimpleNames[i+offset]); + this.declaringQualification = isCaseSensitive() ? declaringQualification : CharOperation.toLowerCase(declaringQualification); + this.declaringSimpleName =isCaseSensitive() ? declaringSimpleName : CharOperation.toLowerCase(declaringSimpleName); + + if (parameterSimpleNames != null) { + this.parameterQualifications = new char[parameterSimpleNames.length][]; + this.parameterSimpleNames = new char[parameterSimpleNames.length][]; + for (int i = 0; i < this.parameterSimpleNames.length; i++) { + this.parameterQualifications[i] = isCaseSensitive() ? parameterQualifications[i] : CharOperation.toLowerCase(parameterQualifications[i]); + this.parameterSimpleNames[i] = isCaseSensitive() ? parameterSimpleNames[i] : CharOperation.toLowerCase(parameterSimpleNames[i]); + } } - } else { - this.parameterCount = -1; + + ((InternalSearchPattern)this).mustResolve = false; } - ((InternalSearchPattern)this).mustResolve = mustResolve(); -} -/* - * Instanciate a method pattern with signatures for generics search - */ -public ConstructorPattern( - boolean findDeclarations, - boolean findReferences, - char[] declaringSimpleName, - char[] declaringQualification, - char[][] parameterQualifications, - char[][] parameterSimpleNames, - String[] parameterSignatures, - IFunction method, -// boolean varargs, - int matchRule) { - - this(findDeclarations, - findReferences, - declaringSimpleName, - declaringQualification, - parameterQualifications, - parameterSimpleNames, - matchRule); - - // Set flags - try { - this.varargs = (method.getFlags() & Flags.AccVarargs) != 0; - } catch (JavaScriptModelException e) { - // do nothing + + /** + * @see org.eclipse.wst.jsdt.internal.core.search.matching.JavaSearchPattern#getBlankPattern() + */ + public SearchPattern getBlankPattern() { + return new ConstructorPattern(R_EXACT_MATCH | R_CASE_SENSITIVE); } - - constructorParameters = true; - // Store type signature and arguments for declaring type - storeTypeSignaturesAndArguments(method.getDeclaringType()); + /** + * @see org.eclipse.wst.jsdt.core.search.SearchPattern#getIndexCategories() + */ + public char[][] getIndexCategories() { + if (this.findReferences) + return this.findDeclarations ? REF_AND_DECL_CATEGORIES : REF_CATEGORIES; + if (this.findDeclarations) + return DECL_CATEGORIES; + return CharOperation.NO_CHAR_CHAR; + } - - // store type signatures and arguments for method parameters type - if (parameterSignatures != null) { - int length = parameterSignatures.length; - if (length > 0) { - parametersTypeSignatures = new char[length][][]; - parametersTypeArguments = new char[length][][][]; - for (int i=0; iMatches this pattern against another pattern using the following logic:
        + *
      • OR
          + *
        • AND
            + *
          • this pattern has a defined search prefix
          • + *
          • OR
              + *
            • this pattern's prefix matches the other patterns qualified name
            • + *
            • this pattern's prefix matches the other patterns simple name
            • + *
            • AND if after separating this pattern's prefix into a qualifier and simple name
                + *
              • this pattern's prefix qualifier matches the other patterns qualified name
              • + *
              • this pattern's prefix simple name matches the other patterns simple name
        • + *
        • AND
            + *
          • this pattern does not have a defined search prefix
          • + *
          • this pattern's qualified name equals the other patterns qualified name
          • + *
          • this pattern's simple name equals the other patterns simple name

    + * + * @see org.eclipse.wst.jsdt.internal.core.search.matching.ConstructorPattern#matchesDecodedKey(org.eclipse.wst.jsdt.core.search.SearchPattern) + */ + public boolean matchesDecodedKey(SearchPattern decodedPattern) { + ConstructorPattern pattern = (ConstructorPattern) decodedPattern; + char[][] seperatedSearchPrefix = QualificationHelpers.seperateFullyQualifedName(this.fSearchPrefix); + + return + ( + this.fSearchPrefix != null && + ( + matchesName(this.fSearchPrefix, pattern.declaringQualification) || + matchesName(this.fSearchPrefix, pattern.declaringSimpleName) || + ( + ( + CharOperation.equals(seperatedSearchPrefix[QualificationHelpers.QULIFIERS_INDEX], pattern.declaringQualification, isCaseSensitive) || + matchesQualificationPattern(seperatedSearchPrefix[QualificationHelpers.QULIFIERS_INDEX], pattern.declaringQualification, isCaseSensitive) + ) && + matchesName(seperatedSearchPrefix[QualificationHelpers.SIMPLE_NAMES_INDEX], pattern.declaringSimpleName) + ) + ) + ) || + ( + this.fSearchPrefix == null && + matchesName(this.declaringQualification, pattern.declaringQualification) && + matchesName(this.declaringSimpleName, pattern.declaringSimpleName) + ); } + + /** + * @see org.eclipse.wst.jsdt.internal.core.search.matching.ConstructorPattern#queryIn(org.eclipse.wst.jsdt.internal.core.index.Index) + */ + EntryResult[] queryIn(Index index) throws IOException { + EntryResult[] results = null; + + //determine the qualification and simple name patterns to use + char[] qualificationPattern; + char[] simpleNamePattern; + if(this.fSearchPrefix != null) { + char[][] seperatedSearchPrefix = QualificationHelpers.seperateFullyQualifedName(this.fSearchPrefix); + qualificationPattern = seperatedSearchPrefix[QualificationHelpers.QULIFIERS_INDEX]; + simpleNamePattern = seperatedSearchPrefix[QualificationHelpers.SIMPLE_NAMES_INDEX]; + } else { + qualificationPattern = this.declaringQualification; + simpleNamePattern = this.declaringSimpleName; + } + + //might have to do multiple searches + char[][] keys = null; + int[] matchRules = null; - // Store type signatures and arguments for method - constructorArguments = extractMethodArguments(method); - if (hasConstructorArguments()) ((InternalSearchPattern)this).mustResolve = true; -} -/* - * Instanciate a method pattern with signatures for generics search - */ -public ConstructorPattern( - boolean findDeclarations, - boolean findReferences, - char[] declaringSimpleName, - char[] declaringQualification, - String declaringSignature, - char[][] parameterQualifications, - char[][] parameterSimpleNames, - String[] parameterSignatures, - char[][] arguments, - int matchRule) { + switch(getMatchMode()) { + case R_EXACT_MATCH : + + /* doing an exact match on the type, but really doing a prefix match in the index for + * simpleName// or simpleName/qualification/ + */ + keys = new char[1][]; + matchRules = new int[1]; + //can not do an exact match with camel case + if (this.isCamelCase) break; + + if(qualificationPattern == null || qualificationPattern.length == 0) { + keys[0] = CharOperation.append(simpleNamePattern, SEPARATOR); + } else { + keys[0] = CharOperation.concat(simpleNamePattern, qualificationPattern, SEPARATOR); + } + + keys[0] = CharOperation.append(keys[0], SEPARATOR); + matchRules[0] = this.getMatchRule(); + matchRules[0] &= ~R_EXACT_MATCH; + matchRules[0] |= R_PREFIX_MATCH; + break; + case R_PREFIX_MATCH : + if(qualificationPattern != null && qualificationPattern.length > 0) { + if(simpleNamePattern == null || simpleNamePattern.length == 0) { + keys = new char[1][]; + matchRules = new int[1]; + } else { + keys = new char[2][]; + matchRules = new int[2]; + + /* search just simple name because can not search camel case simple name with qualification: + * simpleNamePattern + */ + keys[1] = simpleNamePattern; + matchRules[1] = this.getMatchRule(); + } + + /* do a pattern search using the entire pattern as the qualification: + * * /fSearchPrefix* + */ + char[] trimmedPrefix = this.fSearchPrefix; + if(this.fSearchPrefix != null && this.fSearchPrefix[this.fSearchPrefix.length - 1] == DOT) { + trimmedPrefix = CharOperation.subarray(this.fSearchPrefix, 0, this.fSearchPrefix.length - 1); + } + keys[0] = CharOperation.concat(ONE_STAR, trimmedPrefix, SEPARATOR); + keys[0] = CharOperation.concat(keys[0], ONE_STAR); + matchRules[0] = this.getMatchRule(); + matchRules[0] &= ~R_PREFIX_MATCH; + matchRules[0] |= R_PATTERN_MATCH; + } else { + if(simpleNamePattern == null || simpleNamePattern.length == 0) { + keys = new char[1][]; + matchRules = new int[1]; + } else { + keys = new char[2][]; + matchRules = new int[2]; + + /* first key to search for is using the simple name as the simple name using prefix match: + * simpleNamePattern + */ + keys[1] = simpleNamePattern; + matchRules[1] = this.getMatchRule(); + } + + /* second key to search for is using the simple name as the qualifier using a pattern match + * * /simpleNamePattern* + */ + keys[0] = CharOperation.concat(ONE_STAR, simpleNamePattern, SEPARATOR); + keys[0] = CharOperation.concat(keys[0], ONE_STAR); + matchRules[0] = this.getMatchRule(); + matchRules[0] &= ~R_PREFIX_MATCH; + matchRules[0] |= R_PATTERN_MATCH; + } + + break; + case R_PATTERN_MATCH : + /* create the pattern: + * simpleNamePattern/qualificationPattern/* + */ + if (this.fSearchPrefix != null) { + keys = new char[2][]; + matchRules = new int[2]; + + /* Key to search for is using the entire pattern as the qualification: + * * /fSearchPrefix/* + */ + keys[1] = CharOperation.concat(ONE_STAR, this.fSearchPrefix, SEPARATOR); + keys[1] = CharOperation.concat(keys[1], ONE_STAR, SEPARATOR); + matchRules[1] = this.getMatchRule(); + } else { + keys = new char[1][]; + matchRules = new int[1]; + } - this(findDeclarations, - findReferences, - declaringSimpleName, - declaringQualification, - parameterQualifications, - parameterSimpleNames, - matchRule); + //if no simple name use * + if (simpleNamePattern == null || simpleNamePattern.length == 0) { + simpleNamePattern = ONE_STAR; + } - // Store type signature and arguments for declaring type - if (declaringSignature != null) { - typeSignatures = Util.splitTypeLevelsSignature(declaringSignature); - setTypeArguments(Util.getAllTypeArguments(typeSignatures)); - } + //if no qualification use * + if (qualificationPattern == null || qualificationPattern.length == 0) { + qualificationPattern = ONE_STAR; + } - // Store type signatures and arguments for method parameters type - if (parameterSignatures != null) { - int length = parameterSignatures.length; - if (length > 0) { - parametersTypeSignatures = new char[length][][]; - parametersTypeArguments = new char[length][][][]; - for (int i=0; i 0) { + if(results == null) { + results = additionalResults; + } else { + EntryResult[] existingResults = results; + + results = new EntryResult[existingResults.length + additionalResults.length]; + + System.arraycopy(existingResults, 0, results, 0, existingResults.length); + System.arraycopy(additionalResults, 0, results, existingResults.length, additionalResults.length); + } } } - } - - // Store type signatures and arguments for method - constructorArguments = arguments; - if (arguments == null || arguments.length == 0) { - if (getTypeArguments() != null && getTypeArguments().length > 0) { - constructorArguments = getTypeArguments()[0]; + + // remove duplicates + int duplicateCount = 0; + for(int i = 0; results != null && i < results.length - 1; i++) { + for(int j = i + 1; j < results.length; j++) { + if(results [i] != null && results[j] != null && CharOperation.equals(results[i].getWord(), results[j].getWord())) { + results[j] = null; + duplicateCount++; + } + } } - } - if (hasConstructorArguments()) ((InternalSearchPattern)this).mustResolve = true; -} -public void decodeIndexKey(char[] key) { - int last = key.length - 1; - this.parameterCount = 0; - this.declaringSimpleName = null; - int power = 1; - for (int i=last; i>=0; i--) { - if (key[i] == SEPARATOR) { - System.arraycopy(key, 0, this.declaringSimpleName = new char[i], 0, i); - break; + + EntryResult[] uniqueResults = null; + if(duplicateCount > 0) { + uniqueResults = new EntryResult[results.length - duplicateCount]; + int uniqueIndex = 0; + for(int i = 0; i < results.length; i++) { + if(results [i] != null) { + uniqueResults[uniqueIndex] = results[i]; + uniqueIndex++; + } + } + results = uniqueResults; } - if (i == last) { - this.parameterCount = key[i] - '0'; + + return results; + } + + /** + *

    Decodes an index key made with {@link #createDeclarationIndexKey(char[], int, char[][], char[][], int)} into the + * parameters of this pattern.

    + * + * @see org.eclipse.wst.jsdt.internal.core.search.matching.ConstructorPattern#decodeIndexKey(char[]) + * + * @see #createDeclarationIndexKey(char[], int, char[][], char[][], int) + */ + public void decodeIndexKey(char[] key) { + char[][] seperated = CharOperation.splitOn(SEPARATOR, key); + + //decode type name + this.declaringSimpleName = seperated[0]; + this.declaringQualification = seperated[1]; + + //get parameter names + this.parameterNames = CharOperation.splitOn(PARAMETER_SEPARATOR, seperated[3]); + + // decode parameter types + char[][][] seperatedParamTypeNames = QualificationHelpers.seperateFullyQualifiedNames(seperated[2], parameterNames.length); + this.parameterQualifications = seperatedParamTypeNames[QualificationHelpers.QULIFIERS_INDEX]; + this.parameterSimpleNames = seperatedParamTypeNames[QualificationHelpers.SIMPLE_NAMES_INDEX]; + + // decode function modifiers + this.modifiers = seperated[4][0] + seperated[4][1]; + } + + /** + * @return the selector for the constructor + */ + public char[] getSelector() { + return QualificationHelpers.createFullyQualifiedName(this.declaringQualification, this.declaringSimpleName); + } + + /** + * @return the fully qualified type names for the parameters + */ + public char[][] getFullyQualifiedParameterTypeNames() { + return QualificationHelpers.createFullyQualifiedNames(this.parameterQualifications, this.parameterSimpleNames); + } + + /** + * @see org.eclipse.wst.jsdt.internal.core.search.matching.JavaSearchPattern#print(java.lang.StringBuffer) + */ + protected StringBuffer print(StringBuffer output) { + if (this.findDeclarations) { + output.append(this.findReferences + ? "ConstructorCombinedPattern: " //$NON-NLS-1$ + : "ConstructorDeclarationPattern: "); //$NON-NLS-1$ } else { - power *= 10; - this.parameterCount += power * (key[i] - '0'); + output.append("ConstructorReferencePattern: "); //$NON-NLS-1$ } - } -} -public SearchPattern getBlankPattern() { - return new ConstructorPattern(R_EXACT_MATCH | R_CASE_SENSITIVE); -} -public char[][] getIndexCategories() { - if (this.findReferences) - return this.findDeclarations ? REF_AND_DECL_CATEGORIES : REF_CATEGORIES; - if (this.findDeclarations) - return DECL_CATEGORIES; - return CharOperation.NO_CHAR_CHAR; -} -boolean hasConstructorArguments() { - return constructorArguments != null && constructorArguments.length > 0; -} -boolean hasConstructorParameters() { - return constructorParameters; -} -public boolean matchesDecodedKey(SearchPattern decodedPattern) { - ConstructorPattern pattern = (ConstructorPattern) decodedPattern; - - return (this.parameterCount == pattern.parameterCount || this.parameterCount == -1 || this.varargs) - && matchesName(this.declaringSimpleName, pattern.declaringSimpleName); -} -protected boolean mustResolve() { - if (this.declaringQualification != null) return true; + if (declaringQualification != null) + output.append(declaringQualification).append('.'); + if (declaringSimpleName != null) + output.append(declaringSimpleName); + else if (declaringQualification != null) + output.append("*"); //$NON-NLS-1$ - // parameter types - if (this.parameterSimpleNames != null) - for (int i = 0, max = this.parameterSimpleNames.length; i < max; i++) - if (this.parameterQualifications[i] != null) return true; - return this.findReferences; // need to check resolved default constructors and explicit constructor calls -} -EntryResult[] queryIn(Index index) throws IOException { - char[] key = this.declaringSimpleName; // can be null - int matchRule = getMatchRule(); - - switch(getMatchMode()) { - case R_EXACT_MATCH : - if (this.isCamelCase) break; - if (this.declaringSimpleName != null && this.parameterCount >= 0 && !this.varargs) - key = createIndexKey(this.declaringSimpleName, this.parameterCount); - else { // do a prefix query with the declaringSimpleName - matchRule &= ~R_EXACT_MATCH; - matchRule |= R_PREFIX_MATCH; + output.append('('); + char[][] parameterTypeNames = this.getFullyQualifiedParameterTypeNames(); + if (parameterTypeNames == null) { + output.append("..."); //$NON-NLS-1$ + } else { + for (int i = 0, max = parameterTypeNames.length; i < max; i++) { + if (i > 0) output.append(", "); //$NON-NLS-1$ + if (parameterTypeNames[i] != null) output.append(parameterTypeNames[i]).append('.'); } - break; - case R_PREFIX_MATCH : - // do a prefix query with the declaringSimpleName - break; - case R_PATTERN_MATCH : - if (this.parameterCount >= 0 && !this.varargs) - key = createIndexKey(this.declaringSimpleName == null ? ONE_STAR : this.declaringSimpleName, this.parameterCount); - else if (this.declaringSimpleName != null && this.declaringSimpleName[this.declaringSimpleName.length - 1] != '*') - key = CharOperation.concat(this.declaringSimpleName, ONE_STAR, SEPARATOR); - // else do a pattern query with just the declaringSimpleName - break; - case R_REGEXP_MATCH : - // TODO (frederic) implement regular expression match - break; + } + output.append(')'); + return super.print(output); } - - return index.query(getIndexCategories(), key, matchRule); // match rule is irrelevant when the key is null -} -protected StringBuffer print(StringBuffer output) { - if (this.findDeclarations) { - output.append(this.findReferences - ? "ConstructorCombinedPattern: " //$NON-NLS-1$ - : "ConstructorDeclarationPattern: "); //$NON-NLS-1$ - } else { - output.append("ConstructorReferencePattern: "); //$NON-NLS-1$ + + /** + *

    Creates a constructor index key based on the given information to be placed in the index.

    + * + *

    Key Syntax: + * typeSimpleName/typeQualification/parameterFullTypeNames/paramaterNames/modifiers

    + * + * @param typeName Name of the type the constructor is for + * @param parameterTypes Type names of the parameters, should be same length as parameterCount + * @param parameterNames Names of the parameters, should be same length as parameterCount + * @param modifiers Modifiers to the constructor such as public/private + * + * @return Constructor index key based on the given information to be used in an index + */ + public static char[] createIndexKey( + char[] typeName, + char[][] parameterTypes, + char[][] parameterNames, + int modifiers) { + + char[] parameterTypesChars = null; + char[] parameterNamesChars = null; + + //separate type name + char[][] seperatedTypeName = QualificationHelpers.seperateFullyQualifedName(typeName); + char[] qualification = seperatedTypeName[QualificationHelpers.QULIFIERS_INDEX]; + char[] simpleName = seperatedTypeName[QualificationHelpers.SIMPLE_NAMES_INDEX]; + + //get param types + if (parameterTypes != null) { + parameterTypesChars = CharOperation.concatWith(parameterTypes, PARAMETER_SEPARATOR, false); + } + + //get param names + if (parameterNames != null) { + parameterNamesChars = CharOperation.concatWith(parameterNames, PARAMETER_SEPARATOR); + } + + //get lengths + int simpleNameLength = simpleName == null ? 0 : simpleName.length; + int qualificationLength = qualification == null ? 0 : qualification.length; + int parameterTypesLength = (parameterTypesChars == null ? 0 : parameterTypesChars.length); + int parameterNamesLength = (parameterNamesChars == null ? 0 : parameterNamesChars.length); + + int resultLength = simpleNameLength + + 1 + qualificationLength + + 1 + parameterTypesLength + + 1 + parameterNamesLength + + 3; //modifiers + + //create result char array + char[] result = new char[resultLength]; + + //add simple type name to result + int pos = 0; + if (simpleNameLength > 0) { + System.arraycopy(simpleName, 0, result, pos, simpleNameLength); + pos += simpleNameLength; + } + + //add qualification to result + result[pos++] = SEPARATOR; + if (qualificationLength > 0) { + System.arraycopy(qualification, 0, result, pos, qualificationLength); + pos += qualificationLength; + } + + //add param types + result[pos++] = SEPARATOR; + if (parameterTypesLength > 0) { + System.arraycopy(parameterTypesChars, 0, result, pos, parameterTypesLength); + + pos += parameterTypesLength; + } + + //add param names + result[pos++] = SEPARATOR; + if (parameterNamesLength > 0) { + System.arraycopy(parameterNamesChars, 0, result, pos, parameterNamesLength); + pos += parameterNamesLength; + } + + //add modifiers + result[pos++] = SEPARATOR; + result[pos++] = (char) modifiers; + result[pos++] = (char) (modifiers>>16); + + return result; } - if (declaringQualification != null) - output.append(declaringQualification).append('.'); - if (declaringSimpleName != null) - output.append(declaringSimpleName); - else if (declaringQualification != null) - output.append("*"); //$NON-NLS-1$ - output.append('('); - if (parameterSimpleNames == null) { - output.append("..."); //$NON-NLS-1$ - } else { - for (int i = 0, max = parameterSimpleNames.length; i < max; i++) { - if (i > 0) output.append(", "); //$NON-NLS-1$ - if (parameterQualifications[i] != null) output.append(parameterQualifications[i]).append('.'); - if (parameterSimpleNames[i] == null) output.append('*'); else output.append(parameterSimpleNames[i]); - } + public char[] getSearchPrefix() { + return fSearchPrefix; } - output.append(')'); - return super.print(output); -} } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/DeclarationOfAccessedFieldsPattern.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/DeclarationOfAccessedFieldsPattern.java index 2fe392e0..d0d3f6d5 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/DeclarationOfAccessedFieldsPattern.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/DeclarationOfAccessedFieldsPattern.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -20,7 +20,7 @@ protected IJavaScriptElement enclosingElement; protected SimpleSet knownFields; public DeclarationOfAccessedFieldsPattern(IJavaScriptElement enclosingElement) { - super(false, true, true, false,null, null, null, null, null, R_PATTERN_MATCH, + super(false, true, true, false,null, null, null, null, R_PATTERN_MATCH, (enclosingElement instanceof IField) ?(IField)enclosingElement :null); this.enclosingElement = enclosingElement; diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/DeclarationOfReferencedMethodsPattern.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/DeclarationOfReferencedMethodsPattern.java index 6057147f..b6cffb1f 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/DeclarationOfReferencedMethodsPattern.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/DeclarationOfReferencedMethodsPattern.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -21,7 +21,7 @@ protected IJavaScriptElement enclosingElement; protected SimpleSet knownMethods; public DeclarationOfReferencedMethodsPattern(IJavaScriptElement enclosingElement) { - super(false, true, false,null, null, null, null, null, null, null, null, R_PATTERN_MATCH); + super(false, true, false,null, R_PATTERN_MATCH); this.enclosingElement = enclosingElement; this.knownMethods = new SimpleSet(); diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/FieldLocator.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/FieldLocator.java index b2b8425f..f6cc10e9 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/FieldLocator.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/FieldLocator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -146,18 +146,18 @@ protected int matchField(FieldBinding field, boolean matchName) { if (receiverBinding == null) { if (field == ArrayBinding.ArrayLength) // optimized case for length field of an array - return fieldPattern.declaringQualification == null && fieldPattern.declaringSimpleName == null + return fieldPattern.getDeclaringQualification() == null && fieldPattern.getDeclaringSimpleName() == null ? ACCURATE_MATCH : IMPOSSIBLE_MATCH; return INACCURATE_MATCH; } // Note there is no dynamic lookup for field access - int declaringLevel = resolveLevelForType(fieldPattern.declaringSimpleName, fieldPattern.declaringQualification, receiverBinding); + int declaringLevel = resolveLevelForType(fieldPattern.getDeclaringSimpleName(), fieldPattern.getDeclaringQualification(), receiverBinding); if (declaringLevel == IMPOSSIBLE_MATCH) return IMPOSSIBLE_MATCH; // look at field type only if declaring type is not specified - if (fieldPattern.declaringSimpleName == null) return declaringLevel; + if (fieldPattern.getDeclaringSimpleName() == null) return declaringLevel; // get real field binding FieldBinding fieldBinding = field; @@ -182,8 +182,8 @@ protected void matchLevelAndReportImportRef(ImportReference importRef, Binding b } protected int matchReference(Reference node, MatchingNodeSet nodeSet, boolean writeOnlyAccess) { if (node instanceof FieldReference) { - if (matchesName(this.pattern.name, ((FieldReference) node).token)) - return nodeSet.addMatch(node, ((InternalSearchPattern)this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH); + if (!this.fieldPattern.isVar && matchesName(this.pattern.name, ((FieldReference) node).token)) + return nodeSet.addMatch(node, ((InternalSearchPattern) this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH); return IMPOSSIBLE_MATCH; } return super.matchReference(node, nodeSet, writeOnlyAccess); @@ -378,6 +378,9 @@ public int resolveLevel(ASTNode possiblelMatchingNode) { return matchField(((FieldDeclaration) possiblelMatchingNode).binding, true); else if (possiblelMatchingNode instanceof LocalDeclaration) return matchLocalVariable(((LocalDeclaration) possiblelMatchingNode).binding, true); + else if (possiblelMatchingNode instanceof InferredAttribute) + return matchField(((InferredAttribute) possiblelMatchingNode).binding, true); + return IMPOSSIBLE_MATCH; } public int resolveLevel(Binding binding) { diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/FieldPattern.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/FieldPattern.java index 95fc070c..84334827 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/FieldPattern.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/FieldPattern.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -10,138 +10,477 @@ *******************************************************************************/ package org.eclipse.wst.jsdt.internal.core.search.matching; +import java.io.IOException; + import org.eclipse.wst.jsdt.core.IField; import org.eclipse.wst.jsdt.core.compiler.CharOperation; import org.eclipse.wst.jsdt.core.search.SearchPattern; -import org.eclipse.wst.jsdt.internal.core.util.Util; +import org.eclipse.wst.jsdt.internal.core.Logger; +import org.eclipse.wst.jsdt.internal.core.index.EntryResult; +import org.eclipse.wst.jsdt.internal.core.index.Index; +import org.eclipse.wst.jsdt.internal.core.util.QualificationHelpers; public class FieldPattern extends VariablePattern { + /** + *

    Optional

    + * + *

    Qualification of the declaring type containing this field.

    + * + *

    This can either be a single qualification if this pattern is representing a specific field + * defined on a specific type, or it can be a list of qualifications if it is a pattern for finding + * a field that could be defined on many different types.

    + * + *

    Note: If this field is defined then the {@link #declaringSimpleName} must + * also be defined.

    + * + * @see #declaringSimpleName + */ + private char[][] declaringQualification; + + /** + *

    Optional

    + * + *

    Simple name of the declaring type containing this field.

    + * + *

    This can either be a single simple name if this pattern is representing a specific field + * defined on a specific type, or it can be a list of simple names if it is a pattern for finding + * a field that could be defined on many different types.

    + * + *

    Note: If this field is defined then the {@link #declaringQualification} + * can be defined, but does not have to be.

    + * + * @see #declaringQualification + */ + private char[][] declaringSimpleName; + + // type + public char[] typeQualification; + public char[] typeSimpleName; + + // modifiers + public int modifiers; + + protected static char[][] REF_CATEGORIES = { REF }; + protected static char[][] REF_AND_DECL_CATEGORIES = { REF, FIELD_DECL, VAR_DECL }; + protected static char[][] DECL_CATEGORIES = { FIELD_DECL, VAR_DECL }; + + /** + * @deprecated this will be removed at some point + */ + protected boolean isVar; + + /** + *

    Creates a field pattern index key based on the given information.

    + * + * @param fieldName + * @param typeName + * @param declaringType + * @param modifiers + * @return + */ + public static char[] createIndexKey(char[] fieldName, char[] typeName, char[] declaringType, int modifiers) { + char[] indexKey = null; + + if(fieldName != null && fieldName.length > 0) { + //get lengths + int typeNameLength= (typeName == null ? 0 : typeName.length); + int declaringTypeLength = (declaringType == null ? 0 : declaringType.length); + + int resultLength = fieldName.length + + 1 + typeNameLength + + 1 + declaringTypeLength + + 3; //modifiers + + //create result char array + indexKey = new char[resultLength]; + + //add type name to result + int pos = 0; + System.arraycopy(fieldName, 0, indexKey, pos, fieldName.length); + pos += fieldName.length; + + //add declaring type + indexKey[pos++] = SEPARATOR; + if(declaringTypeLength > 0) { + System.arraycopy(declaringType, 0, indexKey, pos, declaringTypeLength); + pos += declaringTypeLength; + } + + //add type + indexKey[pos++] = SEPARATOR; + if(typeNameLength > 0) { + System.arraycopy(typeName, 0, indexKey, pos, typeNameLength); + pos += typeNameLength; + } + + //add modifiers + indexKey[pos++] = SEPARATOR; + indexKey[pos++] = (char) modifiers; + indexKey[pos++] = (char) (modifiers>>16); + } + + return indexKey; + } + + /** + *

    Constructor good for creating a pattern to find a field that could be defined + * on one of many different specified types.

    + * + * @param findDeclarations + * @param readAccess + * @param writeAccess + * @param isVar + * @param name + * @param possibleDeclaringTypes optional list of possible declaring types that the given selector must be + * defined on one of to be a valid match, or null to specify the field is not + * defined on a type + * @param typeQualification + * @param typeSimpleName + * @param matchRule + * @param field + */ + public FieldPattern( + boolean findDeclarations, + boolean readAccess, + boolean writeAccess, + boolean isVar, + char[] name, + char[][] possibleDeclaringTypes, + char[] typeQualification, + char[] typeSimpleName, + int matchRule, IField field) { + + super(FIELD_PATTERN, findDeclarations, readAccess, writeAccess, name, matchRule,field); + + this.isVar=isVar; + if(possibleDeclaringTypes != null) { + this.declaringQualification = new char[possibleDeclaringTypes.length][]; + this.declaringSimpleName = new char[possibleDeclaringTypes.length][]; + for(int i = 0; i < possibleDeclaringTypes.length; i++) { + char[][] seperatedDeclaringType = QualificationHelpers.seperateFullyQualifedName(possibleDeclaringTypes[i]); + this.declaringQualification[i] = isCaseSensitive() ? + seperatedDeclaringType[QualificationHelpers.QULIFIERS_INDEX] : CharOperation.toLowerCase(seperatedDeclaringType[QualificationHelpers.QULIFIERS_INDEX]); + this.declaringSimpleName[i] = isCaseSensitive() ? + seperatedDeclaringType[QualificationHelpers.SIMPLE_NAMES_INDEX] : CharOperation.toLowerCase(seperatedDeclaringType[QualificationHelpers.SIMPLE_NAMES_INDEX]); + } + } + this.typeQualification = isCaseSensitive() ? typeQualification : CharOperation.toLowerCase(typeQualification); + this.typeSimpleName = (isCaseSensitive() || isCamelCase()) ? typeSimpleName : CharOperation.toLowerCase(typeSimpleName); + + ((InternalSearchPattern)this).mustResolve = mustResolve(); + } + + /** + * + *

    Constructor useful for searching for a specific field on a specific type.

    + * + * @param findDeclarations + * @param readAccess + * @param writeAccess + * @param name + * @param declaringQualification + * @param declaringSimpleName + * @param matchRule + */ + public FieldPattern( + boolean findDeclarations, + boolean readAccess, + boolean writeAccess, + char[] name, + char[] declaringQualification, + char[] declaringSimpleName, + int matchRule) { + + this(findDeclarations, readAccess, writeAccess, false, + name, declaringQualification, declaringSimpleName, null, null, matchRule, null); + } + + /** + *

    Constructor useful for searching for a specific field on a specific type.

    + * + * @param findDeclarations + * @param readAccess + * @param writeAccess + * @param isVar + * @param name + * @param declaringQualification + * @param declaringSimpleName + * @param typeQualification + * @param typeSimpleName + * @param matchRule + * @param field + */ + public FieldPattern( + boolean findDeclarations, + boolean readAccess, + boolean writeAccess, + boolean isVar, + char[] name, + char[] declaringQualification, + char[] declaringSimpleName, + char[] typeQualification, + char[] typeSimpleName, + int matchRule, IField field) { + + super(FIELD_PATTERN, findDeclarations, readAccess, writeAccess, name, matchRule,field); + + this.isVar=isVar; + + this.setDeclaringQualification(declaringQualification); + this.setDeclaringSimpleName(declaringSimpleName); + this.typeQualification = isCaseSensitive() ? typeQualification : CharOperation.toLowerCase(typeQualification); + this.typeSimpleName = (isCaseSensitive() || isCamelCase()) ? typeSimpleName : CharOperation.toLowerCase(typeSimpleName); + + ((InternalSearchPattern)this).mustResolve = mustResolve(); + } + + /** + * @see org.eclipse.wst.jsdt.core.search.SearchPattern#decodeIndexKey(char[]) + */ + public void decodeIndexKey(char[] key) { + char[][] seperated = CharOperation.splitOn(SEPARATOR, key); + + //get the name + this.name = seperated[0]; + + if (seperated.length > 1) { + // get the declaring type + char[][] declaringType = QualificationHelpers.seperateFullyQualifedName(seperated[1]); + this.setDeclaringQualification(declaringType[QualificationHelpers.QULIFIERS_INDEX]); + this.setDeclaringSimpleName(declaringType[QualificationHelpers.SIMPLE_NAMES_INDEX]); -// declaring type -protected char[] declaringQualification; -protected char[] declaringSimpleName; - -// type -protected char[] typeQualification; -protected char[] typeSimpleName; - -protected static char[][] REF_CATEGORIES = { REF }; -protected static char[][] REF_AND_DECL_CATEGORIES = { REF, FIELD_DECL }; -protected static char[][] DECL_CATEGORIES = { FIELD_DECL }; -protected static char[][] VAR_REF_AND_DECL_CATEGORIES = { REF, VAR_DECL }; -protected static char[][] VAR_DECL_CATEGORIES = { VAR_DECL }; -protected boolean isVar; - -public static char[] createIndexKey(char[] fieldName) { - return fieldName; -} - -public FieldPattern( - boolean findDeclarations, - boolean readAccess, - boolean writeAccess, - boolean isVar, - char[] name, - char[] declaringQualification, - char[] declaringSimpleName, - char[] typeQualification, - char[] typeSimpleName, - int matchRule, IField field) { - - super(FIELD_PATTERN, findDeclarations, readAccess, writeAccess, name, matchRule,field); - - this.isVar=isVar; - this.declaringQualification = isCaseSensitive() ? declaringQualification : CharOperation.toLowerCase(declaringQualification); - this.declaringSimpleName = isCaseSensitive() ? declaringSimpleName : CharOperation.toLowerCase(declaringSimpleName); - this.typeQualification = isCaseSensitive() ? typeQualification : CharOperation.toLowerCase(typeQualification); - this.typeSimpleName = (isCaseSensitive() || isCamelCase()) ? typeSimpleName : CharOperation.toLowerCase(typeSimpleName); - - ((InternalSearchPattern)this).mustResolve = mustResolve(); -} -/* - * Instanciate a field pattern with additional information for generics search - */ -public FieldPattern( - boolean findDeclarations, - boolean readAccess, - boolean writeAccess, - boolean isVar, - char[] name, - char[] declaringQualification, - char[] declaringSimpleName, - char[] typeQualification, - char[] typeSimpleName, - String typeSignature, - int matchRule, IField field) { - - this(findDeclarations, readAccess, writeAccess, isVar, name, declaringQualification, declaringSimpleName, typeQualification, typeSimpleName, matchRule,field); + // get the type of the field + char[][] type = QualificationHelpers.seperateFullyQualifedName(seperated[2]); + this.typeQualification = type[QualificationHelpers.QULIFIERS_INDEX]; + this.typeSimpleName = type[QualificationHelpers.SIMPLE_NAMES_INDEX]; - // store type signatures and arguments - if (typeSignature != null) { - this.typeSignatures = Util.splitTypeLevelsSignature(typeSignature); - setTypeArguments(Util.getAllTypeArguments(this.typeSignatures)); + // get the modifiers + this.modifiers = seperated[3][0] + seperated[3][1]; + } } -} -public void decodeIndexKey(char[] key) { - this.name = key; -} -public SearchPattern getBlankPattern() { - return new FieldPattern(false, false, false, isVar, null, null, null, null, null, R_EXACT_MATCH | R_CASE_SENSITIVE,null); -} -public char[] getIndexKey() { - return this.name; -} -public char[][] getIndexCategories() { + + /** + * @see org.eclipse.wst.jsdt.internal.core.search.matching.JavaSearchPattern#getBlankPattern() + */ + public SearchPattern getBlankPattern() { + return new FieldPattern(false, false, false, isVar, null, null, null, null, R_EXACT_MATCH | R_CASE_SENSITIVE,null); + } + + /** + * @see org.eclipse.wst.jsdt.core.search.SearchPattern#getIndexKey() + */ + public char[] getIndexKey() { + return this.name; + } + + /** + * @see org.eclipse.wst.jsdt.internal.core.search.matching.InternalSearchPattern#queryIn(org.eclipse.wst.jsdt.internal.core.index.Index) + */ + EntryResult[] queryIn(Index index) throws IOException { + //might have to do multiple searches + EntryResult[] results = null; + char[][] keys = null; + int[] matchRules = null; + + if (this.findReferences && (this.findDeclarations || this.writeAccess)) { + keys = new char[2][]; + matchRules = new int[2]; + } else { + keys = new char[1][]; + matchRules = new int[1]; + } + + keys[0] = this.name; // can be null + matchRules[0] = getMatchRule(); + + if (this.findDeclarations || this.writeAccess) { + switch (getMatchMode()) { + case R_EXACT_MATCH : + // can not do an exact match with camel case + if (this.isCamelCase) + break; - if (this.isVar) { - if (this.findReferences) - return this.findDeclarations || this.writeAccess ? VAR_REF_AND_DECL_CATEGORIES - : REF_CATEGORIES; - if (this.findDeclarations) - return VAR_DECL_CATEGORIES; + /* + * do a prefix match on name/declaringType/ + */ + keys[0] = CharOperation.concat(this.name, QualificationHelpers.createFullyQualifiedName(this.getDeclaringQualification(), this.getDeclaringSimpleName()), SEPARATOR); + keys[0] = CharOperation.append(keys[0], SEPARATOR); + matchRules[0] &= ~R_EXACT_MATCH; + matchRules[0] |= R_PREFIX_MATCH; + break; + case R_PREFIX_MATCH : + break; + case R_PATTERN_MATCH : + keys[0] = createSearchIndexKey(this.name, this.getDeclaringQualification(), this.getDeclaringSimpleName()); + break; + case R_REGEXP_MATCH : + Logger.log(Logger.WARNING, "Regular expression matching is not yet implimented for MethodPattern"); + break; + } + } + + if (this.findReferences && (this.findDeclarations || this.writeAccess)) { + keys[1] = this.name; // can be null + matchRules[1] = getMatchRule(); + } + + //run a search for each search key + for (int i = 0; i < keys.length; ++i) { + //run search + EntryResult[] additionalResults = index.query(getIndexCategories(), keys[i], matchRules[i]); + + //collect results + if (additionalResults != null && additionalResults.length > 0) { + if (results == null) { + results = additionalResults; + } else { + EntryResult[] existingResults = results; + + results = new EntryResult[existingResults.length + additionalResults.length]; + + System.arraycopy(existingResults, 0, results, 0, existingResults.length); + System.arraycopy(additionalResults, 0, results, existingResults.length, additionalResults.length); + } + } + } + return results; } - else { + public char[][] getIndexCategories() { if (this.findReferences) return this.findDeclarations || this.writeAccess ? REF_AND_DECL_CATEGORIES : REF_CATEGORIES; if (this.findDeclarations) return DECL_CATEGORIES; - + + return CharOperation.NO_CHAR_CHAR; + } + + /** + * @see org.eclipse.wst.jsdt.core.search.SearchPattern#matchesDecodedKey(org.eclipse.wst.jsdt.core.search.SearchPattern) + */ + public boolean matchesDecodedKey(SearchPattern decodedPattern) { + boolean matches = false; + if(decodedPattern instanceof FieldPattern) { + FieldPattern pattern = (FieldPattern) decodedPattern; + + matches = matchesName(this.name, pattern.name); + + if(matches && this.declaringSimpleName != null) { + boolean foundTypeMatch = false; + for(int i = 0; i < this.declaringSimpleName.length; i++) { + if(matchesName(this.declaringQualification[i], pattern.getDeclaringQualification()) + && matchesName(this.declaringSimpleName[i], pattern.getDeclaringSimpleName())) { + foundTypeMatch = true; + break; + } + } + if(!foundTypeMatch) + matches = false; + } + } + + return matches; + } + + /** + * @return the declaring qualification for this pattern, or null if no declaring qualification + */ + public char[] getDeclaringQualification() { + return this.declaringQualification != null && this.declaringQualification.length > 0 ? + this.declaringQualification[0] : null; + } + + /** + * @return the declaring simple name for this pattern, or null if no declaring simple name + */ + public char[] getDeclaringSimpleName() { + return this.declaringSimpleName != null && this.declaringSimpleName.length > 0 ? + this.declaringSimpleName[0] : null; + } + + /** + *

    Sets the declaring qualification for this pattern.

    + *

    If the declaring qualification is set then the declaring simple name must also be set.

    + * + * @param declaringQualification declaring qualification for this pattern + * + * @see #setDeclaringSimpleName(char[]) + */ + private void setDeclaringQualification(char[] declaringQualification) { + this.declaringQualification = new char[1][]; + this.declaringQualification[0] = declaringQualification; + } + + /** + *

    Sets the declaring simple name for this pattern

    + * + * @param declaringSimpleName declaring simple name for this pattern + */ + private void setDeclaringSimpleName(char[] declaringSimpleName) { + this.declaringSimpleName = new char[1][]; + this.declaringSimpleName[0] = declaringSimpleName; + } + + /** + * @see org.eclipse.wst.jsdt.internal.core.search.matching.VariablePattern#mustResolve() + */ + protected boolean mustResolve() { + if (!isVar && this.findDeclarations) + return true; + + return false; + } + + /** + * @see org.eclipse.wst.jsdt.internal.core.search.matching.JavaSearchPattern#print(java.lang.StringBuffer) + */ + protected StringBuffer print(StringBuffer output) { + if (this.findDeclarations) { + output.append(this.findReferences + ? "FieldCombinedPattern: " //$NON-NLS-1$ + : "FieldDeclarationPattern: "); //$NON-NLS-1$ + } else { + output.append("FieldReferencePattern: "); //$NON-NLS-1$ + } + if (this.getDeclaringQualification() != null) output.append(this.getDeclaringQualification()).append('.'); + if (this.getDeclaringSimpleName() != null) + output.append(this.getDeclaringSimpleName()).append('.'); + else if (this.getDeclaringSimpleName() != null) output.append("*."); //$NON-NLS-1$ + if (name == null) { + output.append("*"); //$NON-NLS-1$ + } else { + output.append(name); + } + if (typeQualification != null) + output.append(" --> ").append(typeQualification).append('.'); //$NON-NLS-1$ + else if (typeSimpleName != null) output.append(" --> "); //$NON-NLS-1$ + if (typeSimpleName != null) + output.append(typeSimpleName); + else if (typeQualification != null) output.append("*"); //$NON-NLS-1$ + return super.print(output); + } + + /** + *

    Create an index key for search the index for any field that matches the given selector, + * on the optionally defined declaring type.

    + * + * @param name + * @param declaringQualification + * @param declaringSimpleName + * + * @return + */ + private static char[] createSearchIndexKey(char[] name, + char[] declaringQualification, char[] declaringSimpleName) { + + char[] declaringFullTypeName = null; + if(declaringSimpleName != null) { + declaringFullTypeName = QualificationHelpers.createFullyQualifiedName(declaringQualification, declaringSimpleName); + } + + return createIndexKey(name, + ONE_STAR, + declaringFullTypeName != null ? declaringFullTypeName : ONE_STAR, + 0); } - return CharOperation.NO_CHAR_CHAR; -} -public boolean matchesDecodedKey(SearchPattern decodedPattern) { - return true; // index key is not encoded so query results all match -} -protected boolean mustResolve() { - if (this.declaringSimpleName != null || this.declaringQualification != null) return true; - if (this.typeSimpleName != null || this.typeQualification != null) return true; - - return super.mustResolve(); -} -protected StringBuffer print(StringBuffer output) { - if (this.findDeclarations) { - output.append(this.findReferences - ? "FieldCombinedPattern: " //$NON-NLS-1$ - : "FieldDeclarationPattern: "); //$NON-NLS-1$ - } else { - output.append("FieldReferencePattern: "); //$NON-NLS-1$ - } - if (declaringQualification != null) output.append(declaringQualification).append('.'); - if (declaringSimpleName != null) - output.append(declaringSimpleName).append('.'); - else if (declaringQualification != null) output.append("*."); //$NON-NLS-1$ - if (name == null) { - output.append("*"); //$NON-NLS-1$ - } else { - output.append(name); - } - if (typeQualification != null) - output.append(" --> ").append(typeQualification).append('.'); //$NON-NLS-1$ - else if (typeSimpleName != null) output.append(" --> "); //$NON-NLS-1$ - if (typeSimpleName != null) - output.append(typeSimpleName); - else if (typeQualification != null) output.append("*"); //$NON-NLS-1$ - return super.print(output); -} } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/MatchLocator.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/MatchLocator.java index d050aad0..bbfa7715 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/MatchLocator.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/MatchLocator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2012 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -232,6 +232,12 @@ class ReportMatchingVisitor extends ASTVisitor int accuracy = (level != null && matchedClassContainer) ? level.intValue() : -1; try { reportMatching(localDeclaration, null, null, enclosingElement, accuracy, typeInHierarchy, nodeSet); + + //check for a method declaration nested under the local declaration to report + AbstractMethodDeclaration methodDeclaration = AbstractMethodDeclaration.findMethodDeclaration(localDeclaration); + if(methodDeclaration != null && methodDeclaration instanceof MethodDeclaration) { + visit((MethodDeclaration)methodDeclaration, scope); + } } catch (CoreException e) { exception=e; } @@ -471,7 +477,7 @@ public void accept(ICompilationUnit sourceUnit, char[][] typeNames, AccessRestri } } public void accept(ICompilationUnit sourceUnit, AccessRestriction accessRestriction) { - accept(sourceUnit, new char[0][0], accessRestriction); + accept(sourceUnit, CharOperation.NO_CHAR_CHAR, accessRestriction); } @@ -635,10 +641,14 @@ protected IJavaScriptElement createHandle(AbstractMethodDeclaration method, IJav } } - char [] methodName=method.isInferred()?method.inferredMethod.name:method.selector; - if (methodName==null) - return null; - return createMethodHandle(parent, new String(methodName), parameterTypeSignatures); + String methodName = null; + if (method.getName() != null) { + methodName = new String( method.getName()); + } + else { + methodName = "___anonymous"; //$NON-NLS-1$ + } + return createMethodHandle(parent, methodName, parameterTypeSignatures); } /* * Create method handle. @@ -780,10 +790,7 @@ protected IJavaScriptElement createImportHandle(ImportReference importRef) { // binary types do not contain import statements so just answer the top-level type as the element IType binaryType = ((ClassFile) openable).getType(); - String typeName = binaryType.getElementName(); - int lastDollar = typeName.lastIndexOf('$'); - if (lastDollar == -1) return binaryType; - return createTypeHandle(typeName.substring(0, lastDollar)); + return binaryType; } /** * Creates an IType from the given simple top level type name. @@ -925,11 +932,7 @@ public MethodBinding getMethodBinding(MethodPattern methodPattern) { return null; } // Get binding from unit scope - char[] typeName = PatternLocator.qualifiedPattern(methodPattern.declaringSimpleName, methodPattern.declaringQualification); - if (typeName == null) { - if (methodPattern.declaringType == null) return null; - typeName = methodPattern.declaringType.getFullyQualifiedName().toCharArray(); - } + char[] typeName = PatternLocator.qualifiedPattern(methodPattern.getDeclaringSimpleName(), methodPattern.getDeclaringQualification()); TypeBinding declaringTypeBinding = getType(typeName, typeName); if (declaringTypeBinding != null) { if (declaringTypeBinding.isArrayType()) { @@ -1094,7 +1097,6 @@ protected void locateMatches(JavaProject javaProject, PossibleMatch[] possibleMa if (this.progressMonitor != null && this.progressMonitor.isCanceled()) throw new OperationCanceledException(); PossibleMatch possibleMatch = this.matchesToProcess[i]; - this.matchesToProcess[i] = null; // release reference to processed possible match try { process(possibleMatch, bindingsWereCreated); } catch (AbortCompilation e) { @@ -2001,7 +2003,7 @@ protected void reportMatching(TypeDeclaration type, AbstractMethodDeclaration me match = this.patternLocator.newDeclarationMatch(type, parent, type.binding, accuracy, type.sourceEnd-offset+1, this); } else { int length = scanner.currentPosition - nameSourceStart; - match = this.patternLocator.newDeclarationMatch(method, enclosingElement, method.binding, accuracy, length, this); + match = this.patternLocator.newDeclarationMatch(method, enclosingElement, method.getBinding(), accuracy, length, this); } if (match != null) { report(match); @@ -2014,7 +2016,7 @@ protected void reportMatching(TypeDeclaration type, AbstractMethodDeclaration me if ((method.bits & ASTNode.HasLocalType) != 0) { if (enclosingElement == null) enclosingElement = createHandle(method, parent); - LocalDeclarationVisitor localDeclarationVisitor = new LocalDeclarationVisitor(enclosingElement, method.binding, nodeSet); + LocalDeclarationVisitor localDeclarationVisitor = new LocalDeclarationVisitor(enclosingElement, method.getBinding(), nodeSet); try { method.traverse(localDeclarationVisitor, (ClassScope) null); } catch (WrappedCoreException e) { @@ -2033,7 +2035,7 @@ protected void reportMatching(TypeDeclaration type, AbstractMethodDeclaration me for (int i = 0, l = nodes.length; i < l; i++) { ASTNode node = nodes[i]; Integer level = (Integer) nodeSet.matchingNodes.removeKey(node); - this.patternLocator.matchReportReference(node, enclosingElement, method.binding, method.scope, level.intValue(), this); + this.patternLocator.matchReportReference(node, enclosingElement, method.getBinding(), method.getScope(), level.intValue(), this); } return; } @@ -2386,10 +2388,7 @@ protected void reportMatching(LocalDeclaration field, LocalDeclaration[] otherFi // Look in initializer ASTNode[] nodes = nodeSet.matchingNodes(field.sourceStart, field.declarationSourceEnd); if (nodes != null) { - if ((this.matchContainer & PatternLocator.FIELD_CONTAINER) == 0) { - for (int i = 0, l = nodes.length; i < l; i++) - nodeSet.matchingNodes.removeKey(nodes[i]); - } else { + if ((this.matchContainer & PatternLocator.FIELD_CONTAINER) != 0) { if (enclosingElement == null) { enclosingElement = createHandle(field, parent); } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/MatchLocatorParser.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/MatchLocatorParser.java index fb9ad9b5..c68f165e 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/MatchLocatorParser.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/MatchLocatorParser.java @@ -294,22 +294,21 @@ public void parseBodies(CompilationUnitDeclaration unit) { ProgramElement[] statements = unit.statements; if (statements != null) for (int i = 0; i < statements.length; i++) { - if (statements[i] instanceof LocalDeclaration) - { + if (statements[i] instanceof LocalDeclaration){ ((LocalDeclaration)statements[i]).traverse(localDeclarationVisitor, null); - if (patternLocator instanceof FieldLocator) + if (patternLocator instanceof FieldLocator) { ((FieldLocator)patternLocator).matchLocalDeclaration((LocalDeclaration)statements[i], this.nodeSet); + } } - else if (statements[i] instanceof AbstractMethodDeclaration) - { - AbstractMethodDeclaration methodDeclaration=(AbstractMethodDeclaration)statements[i]; -// this.parse(methodDeclaration, unit); + + //check if the statement contains a method declaration + AbstractMethodDeclaration methodDeclaration = AbstractMethodDeclaration.findMethodDeclaration(statements[i]); + if (methodDeclaration != null && methodDeclaration instanceof MethodDeclaration) { methodDeclaration.traverse(localDeclarationVisitor, (Scope) null); - if (this.patternLocator instanceof MethodLocator) - ((MethodLocator)this.patternLocator).match((MethodDeclaration)statements[i], this.nodeSet); - + if (this.patternLocator instanceof MethodLocator) { + ((MethodLocator)this.patternLocator).match((MethodDeclaration)methodDeclaration, this.nodeSet); + } } - } unit.traverseInferredTypes(localDeclarationVisitor, null); diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/MatchingNodeSet.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/MatchingNodeSet.java index 3edc1133..05d15637 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/MatchingNodeSet.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/MatchingNodeSet.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/MethodLocator.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/MethodLocator.java index c411a15d..b31697e4 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/MethodLocator.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/MethodLocator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -24,7 +24,6 @@ import org.eclipse.wst.jsdt.core.compiler.CharOperation; import org.eclipse.wst.jsdt.core.infer.InferredMethod; import org.eclipse.wst.jsdt.core.search.MethodDeclarationMatch; import org.eclipse.wst.jsdt.core.search.SearchMatch; -import org.eclipse.wst.jsdt.core.search.SearchPattern; import org.eclipse.wst.jsdt.internal.compiler.ast.ASTNode; import org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.wst.jsdt.internal.compiler.ast.Argument; @@ -43,6 +42,8 @@ import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeConstants; import org.eclipse.wst.jsdt.internal.compiler.util.SimpleSet; import org.eclipse.wst.jsdt.internal.core.JavaElement; import org.eclipse.wst.jsdt.internal.core.search.BasicSearchEngine; +import org.eclipse.wst.jsdt.internal.core.search.indexing.IIndexConstants; +import org.eclipse.wst.jsdt.internal.core.util.QualificationHelpers; public class MethodLocator extends PatternLocator { @@ -76,10 +77,10 @@ public void initializePolymorphicSearch(MatchLocator locator) { this.allSuperDeclaringTypeNames = new SuperTypeNamesCollector( this.pattern, - this.pattern.declaringSimpleName, - this.pattern.declaringQualification, + this.pattern.getDeclaringSimpleName(), + this.pattern.getDeclaringQualification(), locator, - this.pattern.declaringType, + null, locator.progressMonitor).collect(); } catch (JavaScriptModelException e) { // inaccurate matches will be found @@ -117,9 +118,10 @@ public int match(ASTNode node, MatchingNodeSet nodeSet) { //public int match(FieldDeclaration node, MatchingNodeSet nodeSet) - SKIP IT public int match(MethodDeclaration node, MatchingNodeSet nodeSet) { if (!this.pattern.findDeclarations) return IMPOSSIBLE_MATCH; - + // Matches are already attempted on InferredMethods + if (node.isInferred()) return IMPOSSIBLE_MATCH; // Verify method name - if (!matchesName(this.pattern.selector, node.getSafeName())) return IMPOSSIBLE_MATCH; + if (!matchesName(this.pattern.selector, node.getName())) return IMPOSSIBLE_MATCH; // Verify parameters types boolean resolve = ((InternalSearchPattern)this.pattern).mustResolve; @@ -146,11 +148,6 @@ public int match(MethodDeclaration node, MatchingNodeSet nodeSet) { } } - // Verify type arguments (do not reject if pattern has no argument as it can be an erasure match) - if (this.pattern.hasMethodArguments()) { - return IMPOSSIBLE_MATCH; - } - // Method declaration may match pattern return nodeSet.addMatch(node, resolve ? POSSIBLE_MATCH : ACCURATE_MATCH); } @@ -158,7 +155,7 @@ public int match(MessageSend node, MatchingNodeSet nodeSet) { if (!this.pattern.findReferences) return IMPOSSIBLE_MATCH; if (!matchesName(this.pattern.selector, node.selector)) return IMPOSSIBLE_MATCH; - if (this.pattern.parameterSimpleNames != null && (!this.pattern.varargs || ((node.bits & ASTNode.InsideJavadoc) != 0))) { + if (this.pattern.parameterSimpleNames != null && ((node.bits & ASTNode.InsideJavadoc) != 0)) { int length = this.pattern.parameterSimpleNames.length; ASTNode[] args = node.arguments; int argsLength = args == null ? 0 : args.length; @@ -187,8 +184,9 @@ protected int matchMethod(MethodBinding method, boolean skipImpossibleArg) { if (!matchesName(this.pattern.selector, method.selector)) return IMPOSSIBLE_MATCH; int level = ACCURATE_MATCH; + // look at return type only if declaring type is not specified - if (this.pattern.declaringSimpleName == null) { + if (this.pattern.getDeclaringSimpleName() == null) { // TODO (frederic) use this call to refine accuracy on return type // int newLevel = resolveLevelForType(this.pattern.returnSimpleName, this.pattern.returnQualification, this.pattern.returnTypeArguments, 0, method.returnType); int newLevel = resolveLevelForType(this.pattern.returnSimpleName, this.pattern.returnQualification, method.returnType); @@ -196,46 +194,8 @@ protected int matchMethod(MethodBinding method, boolean skipImpossibleArg) { if (newLevel == IMPOSSIBLE_MATCH) return IMPOSSIBLE_MATCH; level = newLevel; // can only be downgraded } - } - - // parameter types - int parameterCount = this.pattern.parameterSimpleNames == null ? -1 : this.pattern.parameterSimpleNames.length; - if (parameterCount > -1) { - // global verification -// if (method.parameters == null) return INACCURATE_MATCH; -// if (parameterCount != method.parameters.length) return IMPOSSIBLE_MATCH; -// if (!method.isValidBinding() && ((ProblemMethodBinding)method).problemId() == ProblemReasons.Ambiguous) { -// // return inaccurate match for ambiguous call (bug 80890) -// return INACCURATE_MATCH; -// } -// -// // verify each parameter -// for (int i = 0; i < parameterCount; i++) { -// TypeBinding argType = method.parameters[i]; -// int newLevel = IMPOSSIBLE_MATCH; -// if (argType.isMemberType()) { -// // only compare source name for member type (bug 41018) -// newLevel = CharOperation.match(this.pattern.parameterSimpleNames[i], argType.sourceName(), this.isCaseSensitive) -// ? ACCURATE_MATCH -// : IMPOSSIBLE_MATCH; -// } else { -// // TODO (frederic) use this call to refine accuracy on parameter types -//// newLevel = resolveLevelForType(this.pattern.parameterSimpleNames[i], this.pattern.parameterQualifications[i], this.pattern.parametersTypeArguments[i], 0, argType); -// newLevel = resolveLevelForType(this.pattern.parameterSimpleNames[i], this.pattern.parameterQualifications[i], argType); -// } -// if (level > newLevel) { -// if (newLevel == IMPOSSIBLE_MATCH) { -// if (skipImpossibleArg) { -// // Do not consider match as impossible while finding declarations and source level >= 1.5 -// // (see bugs https://bugs.eclipse.org/bugs/show_bug.cgi?id=79990, 96761, 96763) -// newLevel = level; -// } else { -// return IMPOSSIBLE_MATCH; -// } -// } -// level = newLevel; // can only be downgraded -// } -// } + } else if (!CharOperation.equals(this.pattern.getDeclaringSimpleName(), IIndexConstants.GLOBAL_SYMBOL, false)) { + level = resolveLevelForType(this.pattern.getDeclaringSimpleName(), this.pattern.getDeclaringQualification(), method.declaringClass); } return level; @@ -245,7 +205,7 @@ private boolean matchOverriddenMethod(ReferenceBinding type, MethodBinding metho // matches superclass if (!CharOperation.equals(type.compoundName, TypeConstants.JAVA_LANG_OBJECT)) { - ReferenceBinding superClass = type.superclass(); + ReferenceBinding superClass = type.getSuperBinding(); if (matchOverriddenMethod(superClass, method, matchMethod)) { return true; } @@ -295,11 +255,6 @@ protected void matchReportReference(ASTNode reference, IJavaScriptElement elemen } } void matchReportReference(MessageSend messageSend, MatchLocator locator, MethodBinding methodBinding) throws CoreException { - - if (this.pattern.hasMethodArguments()) { // binding has no type params, compatible erasure if pattern does - match.setRule(SearchPattern.R_ERASURE_MATCH); - } - // See whether it is necessary to report or not if (match.getRule() == 0) return; // impossible match boolean report = (this.isErasureMatch && match.isErasure()) || (this.isEquivalentMatch && match.isEquivalent()) || match.isExact(); @@ -311,23 +266,7 @@ void matchReportReference(MessageSend messageSend, MatchLocator locator, MethodB match.setLength(messageSend.sourceEnd - offset + 1); locator.report(match); } -/* - * Return whether method parameters are equals to pattern ones. - */ -private boolean methodParametersEqualsPattern(MethodBinding method) { - TypeBinding[] methodParameters = method.parameters; - - int length = methodParameters.length; - if (length != this.pattern.parameterSimpleNames.length) return false; - for (int i = 0; i < length; i++) { - char[] paramQualifiedName = qualifiedPattern(this.pattern.parameterSimpleNames[i], this.pattern.parameterQualifications[i]); - if (!CharOperation.match(paramQualifiedName, methodParameters[i].readableName(), this.isCaseSensitive)) { - return false; - } - } - return true; -} public SearchMatch newDeclarationMatch(ASTNode reference, IJavaScriptElement element, Binding elementBinding, int accuracy, int length, MatchLocator locator) { if (elementBinding != null) { MethodBinding methodBinding = (MethodBinding) elementBinding; @@ -412,14 +351,14 @@ protected void reportDeclaration(MethodBinding methodBinding, MatchLocator locat AbstractMethodDeclaration methodDecl = null; AbstractMethodDeclaration[] methodDecls = typeDecl.methods; for (int i = 0, length = methodDecls.length; i < length; i++) { - if (CharOperation.equals(bindingSelector, methodDecls[i].selector)) { + if (CharOperation.equals(bindingSelector, methodDecls[i].getName())) { methodDecl = methodDecls[i]; break; } } if (methodDecl != null) { int offset = methodDecl.sourceStart; - Binding binding = methodDecl.binding; + Binding binding = methodDecl.getBinding(); if (binding != null) method = (IFunction) ((JavaElement) method).resolved(binding); match = new MethodDeclarationMatch(method, SearchMatch.A_ACCURATE, offset, methodDecl.sourceEnd-offset+1, locator.getParticipant(), resource); @@ -436,7 +375,7 @@ public int resolveLevel(ASTNode possibleMatchingNode) { } if (this.pattern.findDeclarations) { if (possibleMatchingNode instanceof MethodDeclaration) { - return resolveLevel(((MethodDeclaration) possibleMatchingNode).binding); + return resolveLevel(((MethodDeclaration) possibleMatchingNode).getBinding()); } else if (possibleMatchingNode instanceof InferredMethod) return resolveLevel(((InferredMethod) possibleMatchingNode).methodBinding); @@ -460,12 +399,12 @@ public int resolveLevel(Binding binding) { } // declaring type - char[] qualifiedPattern = qualifiedPattern(this.pattern.declaringSimpleName, this.pattern.declaringQualification); + char[] qualifiedPattern = qualifiedPattern(this.pattern.getDeclaringSimpleName(), this.pattern.getDeclaringQualification()); if (qualifiedPattern == null) return methodLevel; // since any declaring class will do boolean subType = !method.isStatic() && !method.isPrivate(); - if (subType && this.pattern.declaringQualification != null && method.declaringClass != null && method.declaringClass.fPackage != null) { - subType = CharOperation.compareWith(this.pattern.declaringQualification, method.declaringClass.fPackage.shortReadableName()) == 0; + if (subType && this.pattern.getDeclaringQualification() != null && method.declaringClass != null && method.declaringClass.fPackage != null) { + subType = CharOperation.compareWith(this.pattern.getDeclaringQualification(), method.declaringClass.fPackage.shortReadableName()) == 0; } int declaringLevel = subType ? resolveLevelAsSubtype(qualifiedPattern, method.declaringClass, null) @@ -496,7 +435,7 @@ protected int resolveLevel(MessageSend messageSend) { } // receiver type - char[] qualifiedPattern = qualifiedPattern(this.pattern.declaringSimpleName, this.pattern.declaringQualification); + char[] qualifiedPattern = qualifiedPattern(this.pattern.getDeclaringSimpleName(), this.pattern.getDeclaringQualification()); if (qualifiedPattern == null) return methodLevel; // since any declaring class will do int declaringLevel; @@ -552,7 +491,7 @@ protected int resolveLevelAsSubtype(char[] qualifiedPattern, ReferenceBinding ty // matches superclass if (!CharOperation.equals(type.compoundName, TypeConstants.JAVA_LANG_OBJECT)) { - level = resolveLevelAsSubtype(qualifiedPattern, type.superclass(), argumentTypes); + level = resolveLevelAsSubtype(qualifiedPattern, type.getSuperBinding(), argumentTypes); if (level != IMPOSSIBLE_MATCH) { if (argumentTypes != null) { // need to verify if method may be overridden @@ -597,9 +536,13 @@ public int match(InferredMethod inferredMethod, MatchingNodeSet nodeSet) { // Verify method name if (!matchesName(this.pattern.selector, inferredMethod.name)) return IMPOSSIBLE_MATCH; + + boolean resolve = ((InternalSearchPattern)this.pattern).mustResolve; + + // Verify type name + if(!resolve && inferredMethod.inType != null && !matchesName(QualificationHelpers.createFullyQualifiedName(this.pattern.getDeclaringQualification(), this.pattern.getDeclaringSimpleName()), inferredMethod.inType.getName())) return IMPOSSIBLE_MATCH; // Verify parameters types - boolean resolve = ((InternalSearchPattern)this.pattern).mustResolve; if (this.pattern.parameterSimpleNames != null) { int length = this.pattern.parameterSimpleNames.length; ASTNode[] args = ((AbstractMethodDeclaration)inferredMethod.getFunctionDeclaration()).arguments; @@ -615,7 +558,7 @@ public int match(InferredMethod inferredMethod, MatchingNodeSet nodeSet) { nodeSet.mustResolve = true; resolve = true; } - this.methodDeclarationsWithInvalidParam.put((AbstractMethodDeclaration)inferredMethod.getFunctionDeclaration(), null); + this.methodDeclarationsWithInvalidParam.put(inferredMethod.getFunctionDeclaration(), null); } else { return IMPOSSIBLE_MATCH; } @@ -623,11 +566,6 @@ public int match(InferredMethod inferredMethod, MatchingNodeSet nodeSet) { } } - // Verify type arguments (do not reject if pattern has no argument as it can be an erasure match) -// if (this.pattern.hasMethodArguments()) { -// if (node.typeParameters == null || node.typeParameters.length != this.pattern.methodArguments.length) return IMPOSSIBLE_MATCH; -// } - // Method declaration may match pattern return nodeSet.addMatch(inferredMethod , resolve ? POSSIBLE_MATCH : ACCURATE_MATCH); } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/MethodPattern.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/MethodPattern.java index 703bb57d..ff7304c3 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/MethodPattern.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/MethodPattern.java @@ -12,369 +12,642 @@ package org.eclipse.wst.jsdt.internal.core.search.matching; import java.io.IOException; -import org.eclipse.wst.jsdt.core.Flags; -import org.eclipse.wst.jsdt.core.IFunction; -import org.eclipse.wst.jsdt.core.IType; -import org.eclipse.wst.jsdt.core.JavaScriptModelException; import org.eclipse.wst.jsdt.core.compiler.CharOperation; import org.eclipse.wst.jsdt.core.search.SearchPattern; +import org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants; +import org.eclipse.wst.jsdt.internal.core.Logger; import org.eclipse.wst.jsdt.internal.core.index.EntryResult; import org.eclipse.wst.jsdt.internal.core.index.Index; -import org.eclipse.wst.jsdt.internal.core.util.Util; - -public class MethodPattern extends JavaSearchPattern { - -protected boolean findDeclarations; -protected boolean findReferences; - -public char[] selector; - -public char[] declaringQualification; -public char[] declaringSimpleName; - -public char[] returnQualification; -public char[] returnSimpleName; - -public char[][] parameterQualifications; -public char[][] parameterSimpleNames; -public int parameterCount; -public boolean varargs = false; - -protected boolean isFunction; -// extra reference info -protected IType declaringType; - -// Signatures and arguments for generic search -char[][] returnTypeSignatures; -char[][][] returnTypeArguments; -char[][][] parametersTypeSignatures; -char[][][][] parametersTypeArguments; -boolean methodParameters = false; -char[][] methodArguments; - -protected static char[][] REF_CATEGORIES = { METHOD_REF }; -protected static char[][] REF_AND_DECL_CATEGORIES = { METHOD_REF, METHOD_DECL }; -protected static char[][] DECL_CATEGORIES = { METHOD_DECL }; -protected static char[][] FUNCTION_REF_AND_DECL_CATEGORIES = { METHOD_REF, FUNCTION_DECL, METHOD_DECL }; -protected static char[][] FUNCTION_DECL_CATEGORIES = { FUNCTION_DECL, METHOD_DECL }; +import org.eclipse.wst.jsdt.internal.core.util.QualificationHelpers; /** - * Method entries are encoded as selector '/' Arity: - * e.g. 'foo/0' + *

    Pattern used when adding functions to an index or searching an index for functions.

    */ -public static char[] createIndexKey(char[] selector, int argCount) { - char[] countChars = argCount < 10 - ? COUNTS[argCount] - : ("/" + String.valueOf(argCount)).toCharArray(); //$NON-NLS-1$ - return CharOperation.concat(selector, countChars); -} - -MethodPattern(int matchRule, boolean isFunction) { - super(METHOD_PATTERN, matchRule); - this.isFunction=isFunction; -} -public MethodPattern( - boolean findDeclarations, - boolean findReferences, - boolean isFunction, - char[] selector, - char[] declaringQualification, - char[] declaringSimpleName, - char[] returnQualification, - char[] returnSimpleName, - char[][] parameterQualifications, - char[][] parameterSimpleNames, - IType declaringType, - int matchRule) { - - this(matchRule,isFunction); - - this.findDeclarations = findDeclarations; - this.findReferences = findReferences; - - this.selector = (isCaseSensitive() || isCamelCase()) ? selector : CharOperation.toLowerCase(selector); - this.declaringQualification = isCaseSensitive() ? declaringQualification : CharOperation.toLowerCase(declaringQualification); - this.declaringSimpleName = isCaseSensitive() ? declaringSimpleName : CharOperation.toLowerCase(declaringSimpleName); - this.returnQualification = isCaseSensitive() ? returnQualification : CharOperation.toLowerCase(returnQualification); - this.returnSimpleName = isCaseSensitive() ? returnSimpleName : CharOperation.toLowerCase(returnSimpleName); - if (parameterSimpleNames != null) { - this.parameterCount = parameterSimpleNames.length; - this.parameterQualifications = new char[this.parameterCount][]; - this.parameterSimpleNames = new char[this.parameterCount][]; - for (int i = 0; i < this.parameterCount; i++) { - this.parameterQualifications[i] = isCaseSensitive() ? parameterQualifications[i] : CharOperation.toLowerCase(parameterQualifications[i]); - this.parameterSimpleNames[i] = isCaseSensitive() ? parameterSimpleNames[i] : CharOperation.toLowerCase(parameterSimpleNames[i]); - } - } else { - this.parameterCount = -1; - } - this.declaringType = declaringType; - ((InternalSearchPattern)this).mustResolve = mustResolve(); -} -/* - * Instanciate a method pattern with signatures for generics search - */ -public MethodPattern( - boolean findDeclarations, - boolean findReferences, - boolean isFunction, - char[] selector, - char[] declaringQualification, - char[] declaringSimpleName, - char[] returnQualification, - char[] returnSimpleName, - String returnSignature, - char[][] parameterQualifications, - char[][] parameterSimpleNames, - String[] parameterSignatures, - IFunction method, - int matchRule) { +public class MethodPattern extends JavaSearchPattern { - this(findDeclarations, - findReferences, - isFunction, - selector, - declaringQualification, - declaringSimpleName, - returnQualification, - returnSimpleName, - parameterQualifications, - parameterSimpleNames, - method.getDeclaringType(), - matchRule); + protected static final char[][] REF_CATEGORIES = { METHOD_REF }; + protected static final char[][] REF_AND_DECL_CATEGORIES = { METHOD_REF, METHOD_DECL }; + protected static final char[][] DECL_CATEGORIES = { METHOD_DECL }; + protected static final char[][] FUNCTION_REF_AND_DECL_CATEGORIES = { METHOD_REF, FUNCTION_DECL, METHOD_DECL }; + protected static final char[][] FUNCTION_DECL_CATEGORIES = { FUNCTION_DECL, METHOD_DECL }; + + /** + *

    Required

    + * + *

    Name of the function

    + */ + public char[] selector; + + /** + *

    Optional

    + * + *

    Qualifications of the parameter types for this function.

    + *

    This should have the same length as {@link #parameterCount}, or + * null if {@link #parameterCount} is 0

    + * + *

    Note: If this field is defined then the {@link #parameterSimpleNames} must + * also be defined.

    + * + * @see #parameterSimpleNames + */ + public char[][] parameterQualifications; + + /** + *

    Optional

    + * + *

    Simple names of the parameter types for this function.

    + *

    This should have the same length as {@link #parameterCount}, or + * null if {@link #parameterCount} is 0

    + * + *

    Note: If this field is defined then the {@link #parameterQualifications} + * filed can be defined, but does not have to be.

    + * + * @see #parameterQualifications + */ + public char[][] parameterSimpleNames; + + /** + *

    Required if {@link #parameterCount} is greater then 0

    + * + *

    Names of the defined parameters for this function.

    + *

    This should have the same length as {@link #parameterCount}, or + * null if {@link #parameterCount} is 0

    + */ + public char[][] parameterNames; + + /** + *

    Optional

    + * + *

    Qualification of the return type of this function.

    + * + *

    Note: If this field is defined then the {@link #returnSimpleName} must + * also be defined.

    + */ + public char[] returnQualification; + + /** + *

    Optional

    + * + *

    Simple name of the return type of this function.

    + * + *

    This can either be a single simple name if this pattern is representing a specific function + * defined on a specific type, or it can be a list of simple names if it is a pattern for finding + * a function that could be defined on many different types.

    + * + *

    Note: If this field is defined then the {@link #returnQualification} + * filed can be defined, but does not have to be.

    + */ + public char[] returnSimpleName; + + /** + *

    Optional

    + * + *

    Qualification of the declaring type containing this function.

    + * + *

    This can either be a single qualification if this pattern is representing a specific function + * defined on a specific type, or it can be a list of qualifications if it is a pattern for finding + * a function that could be defined on many different types.

    + * + *

    Note: If this field is defined then the {@link #declaringSimpleName} must + * also be defined.

    + * + * @see #declaringSimpleName + */ + private char[][] declaringQualification; + + /** + *

    Optional

    + * + *

    Simple name of the declaring type containing this function.

    + * + *

    This can either be a single simple name if this pattern is representing a specific function + * defined on a specific type, or it can be a list of simple names if it is a pattern for finding + * a function that could be defined on many different types.

    + * + *

    Note: If this field is defined then the {@link #declaringQualification} + * can be defined, but does not have to be.

    + * + * @see #declaringQualification + */ + private char[][] declaringSimpleName; + + /** + *

    Optional

    + * + *

    Any modifiers for this function.

    + * + * @see ClassFileConstants + */ + public int modifiers; + + /** + *

    When using this pattern to do a search true to + * find function declarations that match this pattern, false otherwise.

    + */ + protected boolean findDeclarations; + + /** + *

    When using this pattern to do a search true to + * find function references that match this pattern, false otherwise.

    + */ + protected boolean findReferences; + + /** + *

    true if this pattern represents a function, + * false otherwise.

    + * + *

    NOTE: this whole concept should be removed, a function is a function is a function.

    + */ + protected boolean isFunction; - // Set flags - try { - this.varargs = (method.getFlags() & Flags.AccVarargs) != 0; - } catch (JavaScriptModelException e) { - // do nothing + /** + *

    Internal constructor for creating plank patterns

    + * + * @param matchRule match rule used when comparing this pattern to search results + * @param isFunction true if this pattern represents a function, + * false otherwise + */ + MethodPattern(int matchRule, boolean isFunction) { + super(METHOD_PATTERN, matchRule); + this.isFunction=isFunction; } - methodParameters = true; - - if (declaringType!=null) { - // Store type signature and arguments for declaring type - storeTypeSignaturesAndArguments(declaringType); + /** + *

    Useful constructor when creating a pattern to search for index matches + * while doing content assist.

    + * + * @param findDeclarations when using this pattern to do a search true to + * find function declarations that match this pattern, false otherwise. + * @param findReferences hen using this pattern to do a search true to + * find function references that match this pattern, false otherwise + * @param isFunction true if this pattern represents a function, + * false otherwise + * @param selector pattern for the name of the function + * @param selectorMatchRule match rule used when comparing this pattern to search results. + * This dictates what type of pattern is present, if any, in the specified selector + * + * @see SearchPattern + */ + public MethodPattern(boolean findDeclarations, + boolean findReferences, + boolean isFunction, + char[] selector, + int selectorMatchRule) { + this(findDeclarations, findReferences, isFunction, selector, + null, null, null, null, null, null, + selectorMatchRule); } - // Store type signatures and arguments for return type - if (returnSignature != null) { - returnTypeSignatures = Util.splitTypeLevelsSignature(returnSignature); - returnTypeArguments = Util.getAllTypeArguments(returnTypeSignatures); - } - - // Store type signatures and arguments for method parameters type - if (parameterSignatures != null) { - int length = parameterSignatures.length; - if (length > 0) { - parametersTypeSignatures = new char[length][][]; - parametersTypeArguments = new char[length][][][]; - for (int i=0; iUseful constructor for finding index matches based on content assist pattern.

    + * + * @param findDeclarations when using this pattern to do a search true to + * find function declarations that match this pattern, false otherwise. + * @param findReferences hen using this pattern to do a search true to + * find function references that match this pattern, false otherwise + * @param selector pattern for the name of the function + * @param possibleDeclaringTypes optional list of possible declaring types that the given selector must be + * defined on one of to be a valid match, or null to specify the function is not + * defined on a type + * @param selectorMatchRule match rule used when comparing this pattern to search results. + * This dictates what type of pattern is present, if any, in the specified selector + */ + public MethodPattern(boolean findDeclarations, boolean findReferences, + char[] selector, char[][] possibleDeclaringTypes, + int selectorMatchRule){ + + this(selectorMatchRule, true); + + this.findDeclarations = findDeclarations; + this.findReferences = findReferences; + this.selector = (isCaseSensitive() || isCamelCase()) ? selector : CharOperation.toLowerCase(selector); + + if(possibleDeclaringTypes != null) { + this.declaringQualification = new char[possibleDeclaringTypes.length][]; + this.declaringSimpleName = new char[possibleDeclaringTypes.length][]; + for(int i = 0; i < possibleDeclaringTypes.length; i++) { + char[][] seperatedDeclaringType = QualificationHelpers.seperateFullyQualifedName(possibleDeclaringTypes[i]); + this.declaringQualification[i] = isCaseSensitive() ? + seperatedDeclaringType[QualificationHelpers.QULIFIERS_INDEX] : CharOperation.toLowerCase(seperatedDeclaringType[QualificationHelpers.QULIFIERS_INDEX]); + this.declaringSimpleName[i] = isCaseSensitive() ? + seperatedDeclaringType[QualificationHelpers.SIMPLE_NAMES_INDEX] : CharOperation.toLowerCase(seperatedDeclaringType[QualificationHelpers.SIMPLE_NAMES_INDEX]); } + } else { + this.declaringQualification = null; + this.declaringSimpleName = null; } } + + /** + *

    Constructor to create a pattern that accepts all possible information about a function.

    + * + * @param findDeclarations + * @param findReferences + * @param isFunction + * @param selector + * @param declaringQualification + * @param declaringSimpleName + * @param returnQualification + * @param returnSimpleName + * @param parameterQualifications + * @param parameterSimpleNames + * @param matchRule + */ + public MethodPattern( + boolean findDeclarations, + boolean findReferences, + boolean isFunction, + char[] selector, + char[][] parameterQualifications, + char[][] parameterSimpleNames, + char[] returnQualification, + char[] returnSimpleName, + char[] declaringQualification, + char[] declaringSimpleName, + int matchRule) { - // Store type signatures and arguments for method - methodArguments = extractMethodArguments(method); - if (hasMethodArguments()) ((InternalSearchPattern)this).mustResolve = true; -} -/* - * Instanciate a method pattern with signatures for generics search - */ -public MethodPattern( - boolean findDeclarations, - boolean findReferences, - boolean isFunction, - char[] selector, - char[] declaringQualification, - char[] declaringSimpleName, - String declaringSignature, - char[] returnQualification, - char[] returnSimpleName, - String returnSignature, - char[][] parameterQualifications, - char[][] parameterSimpleNames, - String[] parameterSignatures, - char[][] arguments, - int matchRule) { + this(matchRule,isFunction); - this(findDeclarations, - findReferences, - isFunction, - selector, - declaringQualification, - declaringSimpleName, - returnQualification, - returnSimpleName, - parameterQualifications, - parameterSimpleNames, - null, - matchRule); + this.findDeclarations = findDeclarations; + this.findReferences = findReferences; - // Store type signature and arguments for declaring type - if (declaringSignature != null) { - typeSignatures = Util.splitTypeLevelsSignature(declaringSignature); - setTypeArguments(Util.getAllTypeArguments(typeSignatures)); + this.selector = (isCaseSensitive() || isCamelCase()) ? selector : CharOperation.toLowerCase(selector); + this.setDeclaringQualification(isCaseSensitive() ? declaringQualification : CharOperation.toLowerCase(declaringQualification)); + this.setDeclaringSimpleName(isCaseSensitive() ? declaringSimpleName : CharOperation.toLowerCase(declaringSimpleName)); + this.returnQualification = isCaseSensitive() ? returnQualification : CharOperation.toLowerCase(returnQualification); + this.returnSimpleName = isCaseSensitive() ? returnSimpleName : CharOperation.toLowerCase(returnSimpleName); + + if (parameterSimpleNames != null) { + this.parameterQualifications = new char[parameterSimpleNames.length][]; + this.parameterSimpleNames = new char[parameterSimpleNames.length][]; + for (int i = 0; i < this.parameterSimpleNames.length; i++) { + this.parameterQualifications[i] = isCaseSensitive() ? parameterQualifications[i] : CharOperation.toLowerCase(parameterQualifications[i]); + this.parameterSimpleNames[i] = isCaseSensitive() ? parameterSimpleNames[i] : CharOperation.toLowerCase(parameterSimpleNames[i]); + } + } + ((InternalSearchPattern)this).mustResolve = false; } - - // Store type signatures and arguments for return type - if (returnSignature != null) { - returnTypeSignatures = Util.splitTypeLevelsSignature(returnSignature); - returnTypeArguments = Util.getAllTypeArguments(returnTypeSignatures); + + /** + *

    Given an index key created by this class decodes that key into the + * various fields of this pattern.

    + * + * @param key to decode into the fields of this pattern + * + * @see #createIndexKey(char[]) + * @see #createIndexKey(char[], char[][], char[][], char[], char[], int) + * @see #createSearchIndexKey(char[], char[], char[]) + */ + public void decodeIndexKey(char[] key) { + char[][] seperated = CharOperation.splitOn(SEPARATOR, key); + + //get the selector + this.selector = seperated[0]; + + //get parameter names + char[][] parameterNames = CharOperation.splitOn(PARAMETER_SEPARATOR, seperated[2]); + if(parameterNames.length > 0) { + this.parameterNames = parameterNames; + } else { + this.parameterNames = null; + } + + //get parameter types + char[][][] parameterTypes = QualificationHelpers.seperateFullyQualifiedNames(seperated[1], parameterNames.length); + this.parameterQualifications = parameterTypes[QualificationHelpers.QULIFIERS_INDEX]; + this.parameterSimpleNames = parameterTypes[QualificationHelpers.SIMPLE_NAMES_INDEX]; + + //get the return type + char[][] returnType = QualificationHelpers.seperateFullyQualifedName(seperated[3]); + this.returnQualification = returnType[QualificationHelpers.QULIFIERS_INDEX]; + this.returnSimpleName = returnType[QualificationHelpers.SIMPLE_NAMES_INDEX]; + + //get the declaration type + char[][] declaringType = QualificationHelpers.seperateFullyQualifedName(seperated[4]); + this.setDeclaringQualification(declaringType[QualificationHelpers.QULIFIERS_INDEX]); + this.setDeclaringSimpleName(declaringType[QualificationHelpers.SIMPLE_NAMES_INDEX]); + + //get the modifiers + this.modifiers = seperated[5][0] + seperated[5][1]; } - - // Store type signatures and arguments for method parameters type - if (parameterSignatures != null) { - int length = parameterSignatures.length; - if (length > 0) { - parametersTypeSignatures = new char[length][][]; - parametersTypeArguments = new char[length][][][]; - for (int i=0; i=0; i--) { - if (key[i] == SEPARATOR) { - System.arraycopy(key, 0, this.selector = new char[i], 0, i); - break; + + /** + * @return the declaring qualification for this pattern, or null if no declaring qualification + */ + public char[] getDeclaringQualification() { + return this.declaringQualification != null && this.declaringQualification.length > 0 ? + this.declaringQualification[0] : null; + } + + /** + * @return the declaring simple name for this pattern, or null if no declaring simple name + */ + public char[] getDeclaringSimpleName() { + return this.declaringSimpleName != null && this.declaringSimpleName.length > 0 ? + this.declaringSimpleName[0] : null; + } + + /** + *

    Sets the declaring qualification for this pattern.

    + *

    If the declaring qualification is set then the declaring simple name must also be set.

    + * + * @param declaringQualification declaring qualification for this pattern + * + * @see #setDeclaringSimpleName(char[]) + */ + private void setDeclaringQualification(char[] declaringQualification) { + this.declaringQualification = new char[1][]; + this.declaringQualification[0] = declaringQualification; + } + + /** + *

    Sets the declaring simple name for this pattern

    + * + * @param declaringSimpleName declaring simple name for this pattern + */ + private void setDeclaringSimpleName(char[] declaringSimpleName) { + this.declaringSimpleName = new char[1][]; + this.declaringSimpleName[0] = declaringSimpleName; + } + + /** + * @see org.eclipse.wst.jsdt.internal.core.search.matching.InternalSearchPattern#isPolymorphicSearch() + */ + boolean isPolymorphicSearch() { + return this.findReferences; + } + + /** + * @see org.eclipse.wst.jsdt.internal.core.search.matching.InternalSearchPattern#queryIn(org.eclipse.wst.jsdt.internal.core.index.Index) + */ + EntryResult[] queryIn(Index index) throws IOException { + char[] key = this.selector; // can be null + int matchRule = getMatchRule(); + + int matchRuleToUse = matchRule; + switch(getMatchMode()) { + case R_EXACT_MATCH : + if (this.isCamelCase) break; + key = createSearchIndexKey(this.selector, + this.getDeclaringQualification(), this.getDeclaringSimpleName()); + matchRuleToUse &= ~R_EXACT_MATCH; + matchRuleToUse |= R_PATTERN_MATCH; + break; + case R_PREFIX_MATCH : + break; + case R_PATTERN_MATCH : + key = createSearchIndexKey(this.selector, + this.getDeclaringQualification(), this.getDeclaringSimpleName()); + break; + case R_REGEXP_MATCH : + Logger.log(Logger.WARNING, "Regular expression matching is not yet implimented for MethodPattern"); + break; } - if (i == last) { - this.parameterCount = key[i] - '0'; + + return index.query(getIndexCategories(), key, matchRuleToUse); // match rule is irrelevant when the key is null + } + + /** + * @see org.eclipse.wst.jsdt.internal.core.search.matching.JavaSearchPattern#print(java.lang.StringBuffer) + */ + protected StringBuffer print(StringBuffer output) { + if (this.findDeclarations) { + output.append(this.findReferences + ? "MethodCombinedPattern: " //$NON-NLS-1$ + : "MethodDeclarationPattern: "); //$NON-NLS-1$ } else { - power *= 10; - this.parameterCount += power * (key[i] - '0'); + output.append("MethodReferencePattern: "); //$NON-NLS-1$ } - } -} -public SearchPattern getBlankPattern() { - return new MethodPattern(R_EXACT_MATCH | R_CASE_SENSITIVE,isFunction); -} -public char[][] getIndexCategories() { - if (this.findReferences) - return this.findDeclarations ? - (isFunction ? FUNCTION_REF_AND_DECL_CATEGORIES : REF_AND_DECL_CATEGORIES) - : REF_CATEGORIES; - if (this.findDeclarations) - return isFunction ? FUNCTION_DECL_CATEGORIES : DECL_CATEGORIES; - return CharOperation.NO_CHAR_CHAR; -} -boolean hasMethodArguments() { - return methodArguments != null && methodArguments.length > 0; -} -boolean hasMethodParameters() { - return methodParameters; -} -boolean isPolymorphicSearch() { - return this.findReferences; -} -public boolean matchesDecodedKey(SearchPattern decodedPattern) { - MethodPattern pattern = (MethodPattern) decodedPattern; + if (this.getDeclaringQualification() != null) + output.append(this.getDeclaringQualification()).append('.'); + if (this.getDeclaringSimpleName() != null) + output.append(this.getDeclaringSimpleName()).append('.'); + else if (this.getDeclaringQualification() != null) + output.append("*."); //$NON-NLS-1$ - return (this.parameterCount == pattern.parameterCount || this.parameterCount == -1 || this.varargs) - && matchesName(this.selector, pattern.selector); -} -/** - * Returns whether a method declaration or message send must be resolved to - * find out if this method pattern matches it. - */ -protected boolean mustResolve() { - // declaring type - // If declaring type is specified - even with simple name - always resolves - if (declaringSimpleName != null || declaringQualification != null) return true; - - // return type - // If return type is specified - even with simple name - always resolves - if (returnSimpleName != null || returnQualification != null) return true; - - // parameter types - if (parameterSimpleNames != null) - for (int i = 0, max = parameterSimpleNames.length; i < max; i++) - if (parameterQualifications[i] != null) return true; - return false; -} -EntryResult[] queryIn(Index index) throws IOException { - char[] key = this.selector; // can be null - int matchRule = getMatchRule(); - - switch(getMatchMode()) { - case R_EXACT_MATCH : - if (this.isCamelCase) break; - if (this.selector != null && this.parameterCount >= 0 && !this.varargs) - key = createIndexKey(this.selector, this.parameterCount); - else { // do a prefix query with the selector - matchRule &= ~R_EXACT_MATCH; - matchRule |= R_PREFIX_MATCH; + if (selector != null) + output.append(selector); + else + output.append("*"); //$NON-NLS-1$ + output.append('('); + if (parameterSimpleNames == null) { + output.append("..."); //$NON-NLS-1$ + } else { + for (int i = 0, max = parameterSimpleNames.length; i < max; i++) { + if (i > 0) output.append(", "); //$NON-NLS-1$ + if (parameterQualifications[i] != null) output.append(parameterQualifications[i]).append('.'); + if (parameterSimpleNames[i] == null) output.append('*'); else output.append(parameterSimpleNames[i]); } - break; - case R_PREFIX_MATCH : - // do a prefix query with the selector - break; - case R_PATTERN_MATCH : - if (this.parameterCount >= 0 && !this.varargs) - key = createIndexKey(this.selector == null ? ONE_STAR : this.selector, this.parameterCount); - else if (this.selector != null && this.selector[this.selector.length - 1] != '*') - key = CharOperation.concat(this.selector, ONE_STAR, SEPARATOR); - // else do a pattern query with just the selector - break; - case R_REGEXP_MATCH : - // TODO (frederic) implement regular expression match - break; + } + output.append(')'); + if (returnQualification != null) + output.append(" --> ").append(returnQualification).append('.'); //$NON-NLS-1$ + else if (returnSimpleName != null) + output.append(" --> "); //$NON-NLS-1$ + if (returnSimpleName != null) + output.append(returnSimpleName); + else if (returnQualification != null) + output.append("*"); //$NON-NLS-1$ + return super.print(output); } - - return index.query(getIndexCategories(), key, matchRule); // match rule is irrelevant when the key is null -} -protected StringBuffer print(StringBuffer output) { - if (this.findDeclarations) { - output.append(this.findReferences - ? "MethodCombinedPattern: " //$NON-NLS-1$ - : "MethodDeclarationPattern: "); //$NON-NLS-1$ - } else { - output.append("MethodReferencePattern: "); //$NON-NLS-1$ + + /** + *

    Create an index key from a selector and a parameter count.

    + * + *

    Note Currently used to index function references, but the + * validity of this use is questionable.

    + * + * @param selector + * + * @return a function index key created from a selector and a parameter count + */ + public static char[] createIndexKey(char[] selector) { + return createIndexKey(selector, null, null, null, null, 0); } - if (declaringQualification != null) - output.append(declaringQualification).append('.'); - if (declaringSimpleName != null) - output.append(declaringSimpleName).append('.'); - else if (declaringQualification != null) - output.append("*."); //$NON-NLS-1$ - - if (selector != null) - output.append(selector); - else - output.append("*"); //$NON-NLS-1$ - output.append('('); - if (parameterSimpleNames == null) { - output.append("..."); //$NON-NLS-1$ - } else { - for (int i = 0, max = parameterSimpleNames.length; i < max; i++) { - if (i > 0) output.append(", "); //$NON-NLS-1$ - if (parameterQualifications[i] != null) output.append(parameterQualifications[i]).append('.'); - if (parameterSimpleNames[i] == null) output.append('*'); else output.append(parameterSimpleNames[i]); + + /** + *

    Creates an index key based on the given function definition information.

    + * + *

    Key Syntax: + * selector/parameterFullTypeNames/paramaterNames/returnFulLTypeName/declaringFullTypeName/modifiers

    + * + *

    + * Examples:

      + *
    • myFunction//// - function with no parameters and no return type
    • + *
    • myFunction///String/ - function with no parameters with a return type
    • + *
    • myFunction////foo.bar.Type - function on a type with no parameters and no return type
    • + *
    • myFunction///String/foo.bar.Type - function on a type with no parameters with a return type
    • + *
    • myFunction//param1,param2// - function with no parameter types, with parameter names with no return type
    • + *
    • myFunction//param1,param2/String/ - function with no parameter types, with parameter names with a return type
    • + *
    • myFunction//param1,param2//foo.bar.Type - function on a type with no parameter types, with parameter names with no return type
    • + *
    • myFunction//param1,param2/String/foo.bar.Type - function on a type with no parameter types, with parameter names with a return type
    • + *
    • myFunction/String,Number/param1,param2// - function with parameter types and names with no return type
    • + *
    • myFunction/String,Number/param1,param2/String/ - function with parameter types and names with a return type
    • + *
    • myFunction/String,Number/param1,param2//foo.bar.Type - function on a type with parameter types and names with no return type
    • + *
    • myFunction/String,Number/param1,param2/String/foo.bar.Type - function on a type with parameter types and names with a return type
    • + *
    • myFunction/,Number/param1,param2// - function where only one of the parameters has a type
    • + *
    • myFunction/,Number/param1,param2/String/ - function where only one of the parameters has a type with a return type
    • + *
    • myFunction/,Number/param1,param2//foo.bar.Type - function on a type where only one of the parameters has a type
    • + *
    • myFunction/,Number/param1,param2/String/foo.bar.Type - function on a type where only one of the parameters has a type with a return type
    • + *

    + * + * @param selector + * @param parameterFullTypeNames + * @param parameterNames + * @param declaringFullTypeName + * @param returnFullTypeName + * @param modifiers + * + * @see #decodeIndexKey(char[]) + * + * @return a key that can be put in an index or used to search an index for functions + */ + public static char[] createIndexKey(char[] selector, + char[][] parameterFullTypeNames, + char[][] parameterNames, + char[] declaringFullTypeName, + char[] returnFullTypeName, + int modifiers) { + + char[] indexKey = null; + + if(selector != null && selector.length > 0) { + char[] parameterTypesChars = CharOperation.NO_CHAR; + char[] parameterNamesChars = CharOperation.NO_CHAR; + + + //get param types + if (parameterFullTypeNames != null) { + parameterTypesChars = CharOperation.concatWith(parameterFullTypeNames, PARAMETER_SEPARATOR, false); + } + + //get param names + if (parameterNames != null) { + parameterNamesChars = CharOperation.concatWith(parameterNames, PARAMETER_SEPARATOR); + } + + //get lengths + int parameterTypesLength = (parameterTypesChars == null ? 0 : parameterTypesChars.length); + int parameterNamesLength = (parameterNamesChars == null ? 0 : parameterNamesChars.length); + int returnTypeLength = (returnFullTypeName == null ? 0 : returnFullTypeName.length); + int delaringTypeLength = declaringFullTypeName == null ? 0 : declaringFullTypeName.length; + + int resultLength = selector.length + + 1 + parameterTypesLength + + 1 + parameterNamesLength + + 1 + returnTypeLength + + 1 + delaringTypeLength + + 3; //modifiers + + //create result char array + indexKey = new char[resultLength]; + + //add type name to result + int pos = 0; + System.arraycopy(selector, 0, indexKey, pos, selector.length); + pos += selector.length; + + //add param types + indexKey[pos++] = SEPARATOR; + if (parameterTypesLength > 0) { + System.arraycopy(parameterTypesChars, 0, indexKey, pos, parameterTypesLength); + pos += parameterTypesLength; + } + + //add param names + indexKey[pos++] = SEPARATOR; + if (parameterNamesLength > 0) { + System.arraycopy(parameterNamesChars, 0, indexKey, pos, parameterNamesLength); + pos += parameterNamesLength; + } + + //add return type + indexKey[pos++] = SEPARATOR; + if(returnTypeLength > 0) { + System.arraycopy(returnFullTypeName, 0, indexKey, pos, returnTypeLength); + pos += returnTypeLength; + } + + //add declaring type + indexKey[pos++] = SEPARATOR; + if(delaringTypeLength > 0) { + System.arraycopy(declaringFullTypeName, 0, indexKey, pos, delaringTypeLength); + pos += delaringTypeLength; + } + + //add modifiers + indexKey[pos++] = SEPARATOR; + indexKey[pos++] = (char) modifiers; + indexKey[pos++] = (char) (modifiers>>16); } + + return indexKey; + } + + /** + *

    Create an index key for search the index for any function that matches the given selector, + * on the optionally defined declaring type.

    + * + * @param selector + * @param declaringQualification + * @param declaringSimpleName + * + * @return + */ + private static char[] createSearchIndexKey(char[] selector, + char[] declaringQualification, char[] declaringSimpleName) { + + char[] declaringFullTypeName = null; + if(declaringSimpleName != null) { + declaringFullTypeName = QualificationHelpers.createFullyQualifiedName(declaringQualification, declaringSimpleName); + } + + return createIndexKey(selector, + ONE_STAR_CHAR, + ONE_STAR_CHAR, + declaringFullTypeName != null ? declaringFullTypeName : ONE_STAR, + ONE_STAR, + 0); } - output.append(')'); - if (returnQualification != null) - output.append(" --> ").append(returnQualification).append('.'); //$NON-NLS-1$ - else if (returnSimpleName != null) - output.append(" --> "); //$NON-NLS-1$ - if (returnSimpleName != null) - output.append(returnSimpleName); - else if (returnQualification != null) - output.append("*"); //$NON-NLS-1$ - return super.print(output); -} } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/MultiTypeDeclarationPattern.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/MultiTypeDeclarationPattern.java index b40807d5..9289cf8f 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/MultiTypeDeclarationPattern.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/MultiTypeDeclarationPattern.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -17,175 +17,200 @@ import org.eclipse.wst.jsdt.core.search.SearchPattern; import org.eclipse.wst.jsdt.internal.core.index.EntryResult; import org.eclipse.wst.jsdt.internal.core.index.Index; -public class MultiTypeDeclarationPattern extends JavaSearchPattern { - -public char[][] simpleNames; -public char[][] qualifications; - -// set to CLASS_SUFFIX for only matching classes -// set to INTERFACE_SUFFIX for only matching interfaces -// set to ENUM_SUFFIX for only matching enums -// set to ANNOTATION_TYPE_SUFFIX for only matching annotation types -// set to TYPE_SUFFIX for matching both classes and interfaces -public char typeSuffix; - -protected static char[][] CATEGORIES = { TYPE_DECL }; - -public MultiTypeDeclarationPattern( - char[][] qualifications, - char[][] simpleNames, - char typeSuffix, - int matchRule) { - - this(matchRule); - - if (isCaseSensitive() || qualifications == null) { - this.qualifications = qualifications; - } else { - int length = qualifications.length; - this.qualifications = new char[length][]; - for (int i = 0; i < length; i++) - this.qualifications[i] = CharOperation.toLowerCase(qualifications[i]); +/** + *

    Pattern used to search for multiple types simultaneously.

    + */ +public class MultiTypeDeclarationPattern extends TypeDeclarationPattern { + + /** + *

    List of type simple names to match on.

    + */ + private char[][] fSimpleNames; + + /** + *

    Optional

    + * + *

    List of qualifications to match on. If specified should be the + * same length as {@link #fSimpleNames} matching one to one the qualifications + * to the simple names.

    + */ + private char[][] fQualifications; + + /** + *

    Internal constructor for creating plank patterns

    + * + * @param matchRule match rule used when comparing this pattern to search results + */ + MultiTypeDeclarationPattern(int matchRule) { + super(matchRule); } - // null simple names are allowed (should return all names) - if (simpleNames != null) { - if ((isCaseSensitive() || isCamelCase()) ) { - this.simpleNames = simpleNames; + + /** + *

    Constructor used to search for multiple types simultaneously that may or may not have + * qualifications defined.

    + * + * @param qualifications Optional list of qualifications to go with the simple type names that are being searched for + * @param simpleNames List of simple type names being searched for + * @param matchRule match rule used when comparing this pattern to search results + */ + public MultiTypeDeclarationPattern(char[][] qualifications, + char[][] simpleNames, int matchRule) { + + this(matchRule); + + if (isCaseSensitive() || qualifications == null) { + this.fQualifications = qualifications; } else { - int length = simpleNames.length; - this.simpleNames = new char[length][]; + int length = qualifications.length; + this.fQualifications = new char[length][]; for (int i = 0; i < length; i++) - this.simpleNames[i] = CharOperation.toLowerCase(simpleNames[i]); + this.fQualifications[i] = CharOperation + .toLowerCase(qualifications[i]); } - } - this.typeSuffix = typeSuffix; - - ((InternalSearchPattern)this).mustResolve = typeSuffix != TYPE_SUFFIX; // only used to report type declarations, not their positions -} -MultiTypeDeclarationPattern(int matchRule) { - super(TYPE_DECL_PATTERN, matchRule); -} -public SearchPattern getBlankPattern() { - return new QualifiedTypeDeclarationPattern(R_EXACT_MATCH | R_CASE_SENSITIVE); -} -public char[][] getIndexCategories() { - return CATEGORIES; -} -public boolean matchesDecodedKey(SearchPattern decodedPattern) { - QualifiedTypeDeclarationPattern pattern = (QualifiedTypeDeclarationPattern) decodedPattern; - - // check type suffix - if (this.typeSuffix != pattern.typeSuffix && typeSuffix != TYPE_SUFFIX) { - if (!matchDifferentTypeSuffixes(this.typeSuffix, pattern.typeSuffix)) { - return false; + // null simple names are allowed (should return all names) + if (simpleNames != null) { + if ((isCaseSensitive() || isCamelCase())) { + this.fSimpleNames = simpleNames; + } else { + int length = simpleNames.length; + this.fSimpleNames = new char[length][]; + for (int i = 0; i < length; i++) + this.fSimpleNames[i] = CharOperation + .toLowerCase(simpleNames[i]); + } } } - // check qualified name - if (this.qualifications != null) { - int count = 0; - int max = this.qualifications.length; - if (max == 0 && pattern.qualification.length > 0) { - return false; + /** + *

    Iterates over all of the type names to match on for this pattern and then uses {@link TypeDeclarationPattern#matchesDecodedKey(SearchPattern)} + * to actually do the match checking.

    + * + * @see org.eclipse.wst.jsdt.internal.core.search.matching.TypeDeclarationPattern#matchesDecodedKey(org.eclipse.wst.jsdt.core.search.SearchPattern) + */ + public boolean matchesDecodedKey(SearchPattern decodedPattern) { + boolean foundMatch = false; + + //loop each type + int typesLength = this.getTypesLength(); + for(int i = 0; i < typesLength && !foundMatch; ++i) { + //set the simple name + if(this.fSimpleNames != null && this.fSimpleNames.length > i) { + this.simpleName = this.fSimpleNames[i]; + } else { + this.simpleName = null; + } + + //set the qualification + if(this.fQualifications != null && this.fQualifications.length > i) { + this.qualification = this.fQualifications[i]; + } else { + this.qualification = null; + } + + //check if match + foundMatch = super.matchesDecodedKey(decodedPattern); } - if (max > 0) { - for (; count < max; count++) - if (matchesName(this.qualifications[count], pattern.qualification)) - break; - if (count == max) return false; - } - } - - // check simple name (null are allowed) - if (this.simpleNames == null) return true; - int count = 0; - int max = this.simpleNames.length; - for (; count < max; count++) - if (matchesName(this.simpleNames[count], pattern.simpleName)) - break; - return count < max; -} -EntryResult[] queryIn(Index index) throws IOException { - if (this.simpleNames == null) { - // if no simple names then return all possible ones from index - return index.query(getIndexCategories(), null, -1); // match rule is irrelevant when the key is null + + //reset simple name and qualification + this.simpleName = null; + this.qualification = null; + + return foundMatch; } - int count = -1; - int numOfNames = this.simpleNames.length; - EntryResult[][] allResults = numOfNames > 1 ? new EntryResult[numOfNames][] : null; - for (int i = 0; i < numOfNames; i++) { - char[] key = this.simpleNames[i]; - int matchRule = getMatchRule(); - - switch(getMatchMode()) { - case R_PREFIX_MATCH : - // do a prefix query with the simpleName - break; - case R_EXACT_MATCH : - if (!this.isCamelCase) { - // do a prefix query with the simpleName - matchRule &= ~R_EXACT_MATCH; - matchRule |= R_PREFIX_MATCH; - key = CharOperation.append(key, SEPARATOR); + /** + *

    Iterates over all of the types names to match on for this pattern and then uses {@link TypeDeclarationPattern#queryIn(Index)} + * to actually do the querying.

    + * + * @see org.eclipse.wst.jsdt.internal.core.search.matching.TypeDeclarationPattern#queryIn(org.eclipse.wst.jsdt.internal.core.index.Index) + */ + EntryResult[] queryIn(Index index) throws IOException { + + EntryResult[] results = null; + + //loop each type + int typesLength = this.getTypesLength(); + for(int i = 0; i < typesLength; ++i) { + //set the simple name + if(this.fSimpleNames != null && this.fSimpleNames.length > i) { + this.simpleName = this.fSimpleNames[i]; + } else { + this.simpleName = null; + } + + //set the qualification + if(this.fQualifications != null && this.fQualifications.length > i) { + this.qualification = this.fQualifications[i]; + } else { + this.qualification = null; + } + + //run query using parent function now that one simple name and one qualification have been set + EntryResult[] additionalResults = super.queryIn(index); + + //collect results + if(additionalResults != null && additionalResults.length > 0) { + if(results == null) { + results = additionalResults; + } else { + EntryResult[] existingResults = results; + + results = new EntryResult[existingResults.length + additionalResults.length]; + + System.arraycopy(existingResults, 0, results, 0, existingResults.length); + System.arraycopy(additionalResults, 0, results, existingResults.length, additionalResults.length); } - break; - case R_PATTERN_MATCH : - if (key[key.length - 1] != '*') - key = CharOperation.concat(key, ONE_STAR, SEPARATOR); - break; - case R_REGEXP_MATCH : - // TODO (frederic) implement regular expression match - break; - } - - EntryResult[] entries = index.query(getIndexCategories(), key, matchRule); // match rule is irrelevant when the key is null - if (entries != null) { - if (allResults == null) return entries; - allResults[++count] = entries; + } } + + //reset simple name and qualification + this.simpleName = null; + this.qualification = null; + + return results; } - if (count == -1) return null; - int total = 0; - for (int i = 0; i <= count; i++) - total += allResults[i].length; - EntryResult[] allEntries = new EntryResult[total]; - int next = 0; - for (int i = 0; i <= count; i++) { - EntryResult[] entries = allResults[i]; - System.arraycopy(entries, 0, allEntries, next, entries.length); - next += entries.length; - } - return allEntries; -} -protected StringBuffer print(StringBuffer output) { - switch (this.typeSuffix){ - case CLASS_SUFFIX : - output.append("MultiClassDeclarationPattern: "); //$NON-NLS-1$ - break; - default : - output.append("MultiTypeDeclarationPattern: "); //$NON-NLS-1$ - break; - } - if (qualifications != null) { - output.append("qualifications: <"); //$NON-NLS-1$ - for (int i = 0; i < qualifications.length; i++){ - output.append(qualifications[i]); - if (i < qualifications.length - 1) - output.append(", "); //$NON-NLS-1$ + /** + * @see org.eclipse.wst.jsdt.internal.core.search.matching.TypeDeclarationPattern#print(java.lang.StringBuffer) + */ + protected StringBuffer print(StringBuffer output) { + output.append("MultiTypeDeclarationPattern: "); //$NON-NLS-1$ + if (fQualifications != null) { + output.append("qualifications: <"); //$NON-NLS-1$ + for (int i = 0; i < fQualifications.length; i++) { + output.append(fQualifications[i]); + if (i < fQualifications.length - 1) + output.append(", "); //$NON-NLS-1$ + } + output.append("> "); //$NON-NLS-1$ + } + if (fSimpleNames != null) { + output.append("simpleNames: <"); //$NON-NLS-1$ + for (int i = 0; i < fSimpleNames.length; i++) { + output.append(fSimpleNames[i]); + if (i < fSimpleNames.length - 1) + output.append(", "); //$NON-NLS-1$ + } + output.append(">"); //$NON-NLS-1$ } - output.append("> "); //$NON-NLS-1$ + return super.print(output); } - if (simpleNames != null) { - output.append("simpleNames: <"); //$NON-NLS-1$ - for (int i = 0; i < simpleNames.length; i++){ - output.append(simpleNames[i]); - if (i < simpleNames.length - 1) - output.append(", "); //$NON-NLS-1$ + + + /** + * @return length of {@link #fSimpleNames} or {@link #fQualifications}, whichever is longer + */ + private int getTypesLength() { + int length = 0; + if(this.fSimpleNames != null && this.fQualifications != null) { + length = (this.fSimpleNames.length > this.fQualifications.length) ? + this.fSimpleNames.length : this.fQualifications.length; + } else if(this.fSimpleNames != null) { + length = this.fSimpleNames.length; + } else if(this.fQualifications != null) { + length = this.fQualifications.length; } - output.append(">"); //$NON-NLS-1$ + + return length; } - return super.print(output); -} } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/OrLocator.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/OrLocator.java index ee237059..69e65c27 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/OrLocator.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/OrLocator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/OrPattern.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/OrPattern.java index a1eb576a..82f5c585 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/OrPattern.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/OrPattern.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -22,17 +22,8 @@ import org.eclipse.wst.jsdt.internal.core.search.indexing.IIndexConstants; public class OrPattern extends SearchPattern implements IIndexConstants { - protected SearchPattern[] patterns; - - /* - * Whether this pattern is erasure match. - */ -// boolean isErasureMatch; - - /** - * One of {@link #R_ERASURE_MATCH}, {@link #R_EQUIVALENT_MATCH}, {@link #R_FULL_MATCH}. - */ int matchCompatibility; + protected SearchPattern[] patterns; public OrPattern(SearchPattern leftPattern, SearchPattern rightPattern) { super(Math.max(leftPattern.getMatchRule(), rightPattern.getMatchRule())); @@ -75,6 +66,19 @@ public class OrPattern extends SearchPattern implements IIndexConstants { return null; } + public SearchPattern findPatternKind(int patternKind) { + for (int i = 0; i < patterns.length; i++) { + if (((InternalSearchPattern)patterns[i]).kind == patternKind) { + return patterns[i]; + } + } + return null; + } + + /** + * Whether this pattern is erasure match. + * @return boolean isErasureMatch; + */ boolean isErasureMatch() { return (this.matchCompatibility & R_ERASURE_MATCH) != 0; } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/PackageReferenceLocator.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/PackageReferenceLocator.java index 7389816f..d4fe40c9 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/PackageReferenceLocator.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/PackageReferenceLocator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/PatternLocator.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/PatternLocator.java index fda8902e..7dd3cd7b 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/PatternLocator.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/PatternLocator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -341,6 +341,25 @@ protected int matchNameValue(char[] pattern, char[] name) { } return IMPOSSIBLE_MATCH; } + +protected boolean isAccurateNameMatch(char[] pattern, char[] sourceName) { + if ((this.matchMode & SearchPattern.R_PREFIX_MATCH) != 0) { + if (CharOperation.prefixEquals(pattern, sourceName, this.isCaseSensitive)) { + return true; + } + } + if (this.isCamelCase) { + if (!this.isCaseSensitive || (pattern.length>0 && sourceName.length>0 && pattern[0] == sourceName[0])) { + if (CharOperation.camelCaseMatch(pattern, sourceName)) { + return true; + } + } + if (this.matchMode == SearchPattern.R_EXACT_MATCH) { + return CharOperation.prefixEquals(pattern, sourceName, this.isCaseSensitive); + } + } + return CharOperation.match(pattern, sourceName, this.isCaseSensitive); +} /** * Returns whether the given type reference matches the given pattern. */ @@ -437,7 +456,7 @@ public SearchMatch newDeclarationMatch(ASTNode reference, IJavaScriptElement ele int offset=(reference!=null )?reference.sourceStart : 0; if (reference instanceof AbstractMethodDeclaration) { AbstractMethodDeclaration method = (AbstractMethodDeclaration) reference; - if (method.selector==null && method.inferredMethod!=null) + if (method.getName()==null && method.inferredMethod!=null) { offset=method.inferredMethod.nameStart; if (length>=0) @@ -589,27 +608,10 @@ protected int resolveLevelForType(char[] simpleNamePattern, char[] qualification sourceName = getQualifiedSourceName(binding); } if (sourceName == null) return IMPOSSIBLE_MATCH; - if ((this.matchMode & SearchPattern.R_PREFIX_MATCH) != 0) { - if (CharOperation.prefixEquals(qualifiedPattern, sourceName, this.isCaseSensitive)) { - return ACCURATE_MATCH; - } - } - if (this.isCamelCase) { - if (!this.isCaseSensitive || (qualifiedPattern.length>0 && sourceName.length>0 && qualifiedPattern[0] == sourceName[0])) { - if (CharOperation.camelCaseMatch(qualifiedPattern, sourceName)) { - return ACCURATE_MATCH; - } - } - if (this.matchMode == SearchPattern.R_EXACT_MATCH) { - boolean matchPattern = CharOperation.prefixEquals(qualifiedPattern, sourceName, this.isCaseSensitive); - return matchPattern ? ACCURATE_MATCH : IMPOSSIBLE_MATCH; - } - } - boolean matchPattern = CharOperation.match(qualifiedPattern, sourceName, this.isCaseSensitive); + boolean matchPattern = isAccurateNameMatch(qualifiedPattern, sourceName); return matchPattern ? ACCURATE_MATCH : IMPOSSIBLE_MATCH; } - /** * Returns whether the given type binding matches the given qualified pattern. * Returns ACCURATE_MATCH if it does. @@ -669,6 +671,23 @@ protected int resolveLevelForType (char[] simpleNamePattern, return (patternTypeArguments[depth]==null || patternTypeArguments[depth].length==0) ? level : IMPOSSIBLE_MATCH; } + +protected int resolveLevelUsingSearchPrefix(char[] searchPrefix, TypeBinding binding) { + if (binding == TypeBinding.ANY || binding == TypeBinding.UNKNOWN) + return ACCURATE_MATCH; + + char[] sourceName = qualifiedSourceName(binding); + if (sourceName == null) return IMPOSSIBLE_MATCH; + + if (isAccurateNameMatch(searchPrefix, sourceName)) + return ACCURATE_MATCH; + + int index = CharOperation.lastIndexOf('.', sourceName); + if (index>=0 && isAccurateNameMatch(searchPrefix, CharOperation.subarray(sourceName, index+1,sourceName.length))) + return ACCURATE_MATCH; + + return IMPOSSIBLE_MATCH; +} public String toString(){ return "SearchPattern"; //$NON-NLS-1$ } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/QualifiedTypeDeclarationPattern.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/QualifiedTypeDeclarationPattern.java deleted file mode 100644 index 2b7bbae2..00000000 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/QualifiedTypeDeclarationPattern.java +++ /dev/null @@ -1,123 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.jsdt.internal.core.search.matching; - -import org.eclipse.wst.jsdt.core.compiler.CharOperation; -import org.eclipse.wst.jsdt.core.search.SearchPattern; -import org.eclipse.wst.jsdt.internal.core.search.indexing.IIndexConstants; - -public class QualifiedTypeDeclarationPattern extends TypeDeclarationPattern implements IIndexConstants { - -public char[] qualification; -PackageDeclarationPattern packagePattern; -public int packageIndex = -1; - -public QualifiedTypeDeclarationPattern(char[] qualification, char[] simpleName, char typeSuffix, int matchRule) { - this(matchRule); - - this.qualification = isCaseSensitive() ? qualification : CharOperation.toLowerCase(qualification); - this.simpleName = (isCaseSensitive() || isCamelCase()) ? simpleName : CharOperation.toLowerCase(simpleName); - this.typeSuffix = typeSuffix; - - ((InternalSearchPattern)this).mustResolve = this.qualification != null || typeSuffix != TYPE_SUFFIX; -} -public QualifiedTypeDeclarationPattern(char[] qualification, int qualificationMatchRule, char[] simpleName, char typeSuffix, int matchRule) { - this(qualification, simpleName, typeSuffix, matchRule); - this.packagePattern = new PackageDeclarationPattern(qualification, qualificationMatchRule); -} -QualifiedTypeDeclarationPattern(int matchRule) { - super(matchRule); -} -public void decodeIndexKey(char[] key) { - int slash = CharOperation.indexOf(SEPARATOR, key, 0); - this.simpleName = CharOperation.subarray(key, 0, slash); - - int start = ++slash; - if (key[start] == SEPARATOR) { - this.pkg = CharOperation.NO_CHAR; - } else { - slash = CharOperation.indexOf(SEPARATOR, key, start); - this.pkg = internedPackageNames.add(CharOperation.subarray(key, start, slash)); - } - this.qualification = this.pkg; - - // Continue key read by the end to decode modifiers - int last = key.length-1; - this.secondary = key[last] == 'S'; - if (this.secondary) { - last -= 2; - } - this.modifiers = key[last-1] + (key[last]<<16); - decodeModifiers(); - - // Retrieve enclosing type names - start = slash + 1; - last -= 2; // position of ending slash - if (start == last) { - this.enclosingTypeNames = CharOperation.NO_CHAR_CHAR; - } else { - int length = this.qualification.length; - int size = last - start; - System.arraycopy(this.qualification, 0, this.qualification = new char[length+1+size], 0, length); - this.qualification[length] = '.'; - if (last == (start+1) && key[start] == ZERO_CHAR) { - this.enclosingTypeNames = ONE_ZERO_CHAR; - this.qualification[length+1] = ZERO_CHAR; - } else { - this.enclosingTypeNames = CharOperation.splitOn('.', key, start, last); - System.arraycopy(key, start, this.qualification, length+1, size); - } - } -} -public SearchPattern getBlankPattern() { - return new QualifiedTypeDeclarationPattern(R_EXACT_MATCH | R_CASE_SENSITIVE); -} -public boolean matchesDecodedKey(SearchPattern decodedPattern) { - QualifiedTypeDeclarationPattern pattern = (QualifiedTypeDeclarationPattern) decodedPattern; - - // check type suffix - if (this.typeSuffix != pattern.typeSuffix && typeSuffix != TYPE_SUFFIX) { - if (!matchDifferentTypeSuffixes(this.typeSuffix, pattern.typeSuffix)) { - return false; - } - } - - // check name - if (matchesName(this.simpleName, pattern.simpleName) ) - { - if (this.qualification!=null && this.packagePattern!=null) - return matchesName(this.qualification,pattern.qualification); - return (this.qualification == null || this.packagePattern == null || this.packagePattern.matchesName(this.qualification, pattern.qualification)); - } - return false; -} -protected StringBuffer print(StringBuffer output) { - switch (this.typeSuffix){ - case CLASS_SUFFIX : - output.append("ClassDeclarationPattern: qualification<"); //$NON-NLS-1$ - break; - default : - output.append("TypeDeclarationPattern: qualification<"); //$NON-NLS-1$ - break; - } - if (this.qualification != null) - output.append(this.qualification); - else - output.append("*"); //$NON-NLS-1$ - output.append(">, type<"); //$NON-NLS-1$ - if (simpleName != null) - output.append(simpleName); - else - output.append("*"); //$NON-NLS-1$ - output.append("> "); //$NON-NLS-1$ - return super.print(output); -} -} diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/SecondaryTypeDeclarationPattern.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/SecondaryTypeDeclarationPattern.java index 8330b79d..8659eb3f 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/SecondaryTypeDeclarationPattern.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/SecondaryTypeDeclarationPattern.java @@ -15,14 +15,16 @@ import java.io.IOException; import org.eclipse.wst.jsdt.core.search.SearchPattern; import org.eclipse.wst.jsdt.internal.core.index.EntryResult; import org.eclipse.wst.jsdt.internal.core.index.Index; -import org.eclipse.wst.jsdt.internal.core.search.indexing.IIndexConstants; +/** + * @deprecated this will be removed at some point because it does not apply to JavaScript + */ public class SecondaryTypeDeclarationPattern extends TypeDeclarationPattern { private final static char[] SECONDARY_PATTERN_KEY = "*/S".toCharArray(); //$NON-NLS-1$ public SecondaryTypeDeclarationPattern() { - super(null, null, null, IIndexConstants.SECONDARY_SUFFIX, R_EXACT_MATCH | R_CASE_SENSITIVE); + super(R_EXACT_MATCH | R_CASE_SENSITIVE); } public SecondaryTypeDeclarationPattern(int matchRule) { @@ -41,7 +43,7 @@ protected StringBuffer print(StringBuffer output) { * @see org.eclipse.wst.jsdt.internal.core.search.matching.TypeDeclarationPattern#queryIn(org.eclipse.wst.jsdt.internal.core.index.Index) */ EntryResult[] queryIn(Index index) throws IOException { - return index.query(CATEGORIES, SECONDARY_PATTERN_KEY, R_PATTERN_MATCH | R_CASE_SENSITIVE); + return index.query(this.getIndexCategories(), SECONDARY_PATTERN_KEY, R_PATTERN_MATCH | R_CASE_SENSITIVE); } } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/SuperTypeNamesCollector.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/SuperTypeNamesCollector.java index 88a32cbb..89b76e41 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/SuperTypeNamesCollector.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/SuperTypeNamesCollector.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -13,8 +13,8 @@ package org.eclipse.wst.jsdt.internal.core.search.matching; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.wst.jsdt.core.IClassFile; -import org.eclipse.wst.jsdt.core.IJavaScriptUnit; import org.eclipse.wst.jsdt.core.IJavaScriptProject; +import org.eclipse.wst.jsdt.core.IJavaScriptUnit; import org.eclipse.wst.jsdt.core.IType; import org.eclipse.wst.jsdt.core.JavaScriptModelException; import org.eclipse.wst.jsdt.core.compiler.CharOperation; @@ -238,7 +238,7 @@ public char[][][] collect() throws JavaScriptModelException { * Collects the names of all the supertypes of the given type. */ protected void collectSuperTypeNames(ReferenceBinding binding) { - ReferenceBinding superclass = binding.superclass(); + ReferenceBinding superclass = binding.getSuperBinding(); if (superclass != null) { this.addToResult(superclass.compoundName); this.collectSuperTypeNames(superclass); @@ -251,10 +251,8 @@ protected String[] getPathsOfDeclaringType() { IJavaScriptSearchScope scope = SearchEngine.createWorkspaceScope(); IndexManager indexManager = JavaModelManager.getJavaModelManager().getIndexManager(); SearchPattern searchPattern = new TypeDeclarationPattern( - this.typeSimpleName != null ? null : this.typeQualification, // use the qualification only if no simple name - null, // do find member types + this.typeQualification, this.typeSimpleName, - IIndexConstants.TYPE_SUFFIX, this.pattern.getMatchRule()); IndexQueryRequestor searchRequestor = new IndexQueryRequestor(){ public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant, AccessRuleSet access) { @@ -288,15 +286,7 @@ protected boolean matches(char[][] compoundName) { return this.pattern.matchesName(this.typeQualification, CharOperation.concatWith(qualification, '.')); } - if (!CharOperation.endsWith(simpleName, this.typeSimpleName)) return false; - - // member type -> transform A.B.C$D into A.B.C.D - System.arraycopy(compoundName, 0, compoundName = new char[length+1][], 0, last); - int dollar = CharOperation.indexOf('$', simpleName); - if (dollar == -1) return false; - compoundName[last] = CharOperation.subarray(simpleName, 0, dollar); - compoundName[length] = CharOperation.subarray(simpleName, dollar+1, simpleName.length); - return this.matches(compoundName); + return false; } protected boolean matches(ReferenceBinding binding) { return binding != null && binding.compoundName != null && this.matches(binding.compoundName); diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/SuperTypeReferenceLocator.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/SuperTypeReferenceLocator.java index 73e7c9ce..8e583f50 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/SuperTypeReferenceLocator.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/SuperTypeReferenceLocator.java @@ -18,6 +18,7 @@ import org.eclipse.wst.jsdt.internal.compiler.ast.TypeReference; import org.eclipse.wst.jsdt.internal.compiler.lookup.Binding; import org.eclipse.wst.jsdt.internal.compiler.lookup.ReferenceBinding; import org.eclipse.wst.jsdt.internal.compiler.lookup.TypeBinding; +import org.eclipse.wst.jsdt.internal.core.util.QualificationHelpers; public class SuperTypeReferenceLocator extends PatternLocator { @@ -37,7 +38,7 @@ public SuperTypeReferenceLocator(SuperTypeReferencePattern pattern) { //public int match(Reference node, MatchingNodeSet nodeSet) - SKIP IT //public int match(TypeDeclaration node, MatchingNodeSet nodeSet) - SKIP IT public int match(TypeReference node, MatchingNodeSet nodeSet) { - if (this.pattern.superSimpleName == null) + if (this.pattern.superTypeName == null) return nodeSet.addMatch(node, ((InternalSearchPattern)this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH); char[] typeRefSimpleName = null; @@ -47,7 +48,7 @@ public int match(TypeReference node, MatchingNodeSet nodeSet) { char[][] tokens = ((QualifiedTypeReference) node).tokens; typeRefSimpleName = tokens[tokens.length-1]; } - if (matchesName(this.pattern.superSimpleName, typeRefSimpleName)) + if (matchesName(this.pattern.superTypeName, typeRefSimpleName)) return nodeSet.addMatch(node, ((InternalSearchPattern)this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH); return IMPOSSIBLE_MATCH; @@ -65,7 +66,8 @@ public int resolveLevel(ASTNode node) { TypeReference typeRef = (TypeReference) node; TypeBinding binding = typeRef.resolvedType; if (binding == null) return INACCURATE_MATCH; - return resolveLevelForType(this.pattern.superSimpleName, this.pattern.superQualification, binding); + char[][] superTypeName = QualificationHelpers.seperateFullyQualifedName(this.pattern.superTypeName); + return resolveLevelForType(superTypeName[QualificationHelpers.SIMPLE_NAMES_INDEX], superTypeName[QualificationHelpers.QULIFIERS_INDEX], binding); } public int resolveLevel(Binding binding) { if (binding == null) return INACCURATE_MATCH; @@ -73,8 +75,8 @@ public int resolveLevel(Binding binding) { ReferenceBinding type = (ReferenceBinding) binding; int level = IMPOSSIBLE_MATCH; - - level = resolveLevelForType(this.pattern.superSimpleName, this.pattern.superQualification, type.superclass()); + char[][] superTypeName = QualificationHelpers.seperateFullyQualifedName(this.pattern.superTypeName); + level = resolveLevelForType(superTypeName[QualificationHelpers.SIMPLE_NAMES_INDEX], superTypeName[QualificationHelpers.QULIFIERS_INDEX], type.getSuperBinding()); if (level == ACCURATE_MATCH) return ACCURATE_MATCH; return level; diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/SuperTypeReferencePattern.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/SuperTypeReferencePattern.java index 9611618a..925dab70 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/SuperTypeReferencePattern.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/SuperTypeReferencePattern.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 20112 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -19,203 +19,139 @@ import org.eclipse.wst.jsdt.internal.core.index.Index; public class SuperTypeReferencePattern extends JavaSearchPattern { -public char[] superQualification; -public char[] superSimpleName; - -public char[] pkgName; -public char[] simpleName; -public char[] enclosingTypeName; -public int modifiers; - -protected static char[][] CATEGORIES = { SUPER_REF }; - -public static char[] createIndexKey( - int modifiers, - char[] packageName, - char[] typeName, - char[][] enclosingTypeNames, - char[] superTypeName) { - - if (superTypeName == null) - superTypeName = OBJECT; - char[] superSimpleName = superTypeName;//CharOperation.lastSegment(superTypeName, '.'); - char[] superQualification = null; -// if (superSimpleName != superTypeName) { -// int length = superTypeName.length - superSimpleName.length - 1; -// superQualification = new char[length]; -// System.arraycopy(superTypeName, 0, superQualification, 0, length); -// } - - // if the supertype name contains a $, then split it into: source name and append the $ prefix to the qualification - // e.g. p.A$B ---> p.A$ + B - char[] superTypeSourceName = CharOperation.lastSegment(superSimpleName, '$'); - if (superTypeSourceName != superSimpleName) { - int start = superQualification == null ? 0 : superQualification.length + 1; - int prefixLength = superSimpleName.length - superTypeSourceName.length; - char[] mangledQualification = new char[start + prefixLength]; - if (superQualification != null) { - System.arraycopy(superQualification, 0, mangledQualification, 0, start-1); - mangledQualification[start-1] = '.'; + public char[] superTypeName; + public char[] typeName; + + protected static char[][] CATEGORIES = {SUPER_REF}; + + public static char[] createIndexKey(char[] typeName, char[] superTypeName) { + if (superTypeName == null) { + superTypeName = OBJECT; } - System.arraycopy(superSimpleName, 0, mangledQualification, start, prefixLength); - superQualification = mangledQualification; - superSimpleName = superTypeSourceName; - } - char[] simpleName = CharOperation.lastSegment(typeName, '.'); - char[] simpleNameTemp = new char[simpleName.length + packageName.length + 1]; - System.arraycopy(packageName, 0, simpleNameTemp, 0, packageName.length); - simpleNameTemp[packageName.length] = '.'; - System.arraycopy(simpleName, 0, simpleNameTemp, packageName.length + 1, simpleName.length); - - simpleName = simpleNameTemp; - char[] enclosingTypeName = CharOperation.concatWith(enclosingTypeNames, '$'); - if (superQualification != null && CharOperation.equals(superQualification, packageName)) - packageName = ONE_ZERO; // save some space - - // superSimpleName / superQualification / simpleName / enclosingTypeName / typeParameters / packageName / superClassOrInterface classOrInterface modifiers - int superLength = superSimpleName == null ? 0 : superSimpleName.length; - int superQLength = superQualification == null ? 0 : superQualification.length; - int simpleLength = simpleName == null ? 0 : simpleName.length; - int enclosingLength = enclosingTypeName == null ? 0 : enclosingTypeName.length; - int packageLength = packageName == null ? 0 : packageName.length; - char[] result = new char[superLength + superQLength + simpleLength + enclosingLength + packageLength + 9]; - int pos = 0; - if (superLength > 0) { - System.arraycopy(superSimpleName, 0, result, pos, superLength); - pos += superLength; + // superSimpleName / superQualification / simpleName / + // enclosingTypeName / typeParameters / packageName / superClassOrInterface + // classOrInterface modifiers + // superTypeName / typeName / modifiers + int superLength = superTypeName == null ? 0 : superTypeName.length; + int typeLength = typeName == null ? 0 : typeName.length; + char[] result = new char[superLength + typeLength + 1]; + int pos = 0; + if (superLength > 0) { + System.arraycopy(superTypeName, 0, result, pos, superLength); + pos += superLength; + } + result[pos++] = SEPARATOR; + if (typeLength > 0) { + System.arraycopy(typeName, 0, result, pos, typeLength); + pos += typeLength; + } + return result; } - result[pos++] = SEPARATOR; - if (superQLength > 0) { - System.arraycopy(superQualification, 0, result, pos, superQLength); - pos += superQLength; + + public SuperTypeReferencePattern(char[] superTypeName, int matchRule) { + this(matchRule); + + this.superTypeName = isCaseSensitive() ? superTypeName : CharOperation.toLowerCase(superTypeName); } - result[pos++] = SEPARATOR; - if (simpleLength > 0) { - System.arraycopy(simpleName, 0, result, pos, simpleLength); - pos += simpleLength; + + SuperTypeReferencePattern(int matchRule) { + super(SUPER_REF_PATTERN, matchRule); } - result[pos++] = SEPARATOR; - if (enclosingLength > 0) { - System.arraycopy(enclosingTypeName, 0, result, pos, enclosingLength); - pos += enclosingLength; + + /** + *

    + * superSimpleName / superQualification / simpleName / enclosingTypeName / + * typeParameters / pkgName / superClassOrInterface classOrInterface modifiers + *

    + * + * @see org.eclipse.wst.jsdt.core.search.SearchPattern#decodeIndexKey(char[]) + */ + public void decodeIndexKey(char[] key) { + int slash = CharOperation.indexOf(SEPARATOR, key, 0); + this.superTypeName = CharOperation.subarray(key, 0, slash); + + // some values may not have been know when indexed so decode as null + int start = slash + 1; + slash = CharOperation.indexOf(SEPARATOR, key, start); + this.typeName = CharOperation.subarray(key, start, slash); } - result[pos++] = SEPARATOR; - if (packageLength > 0) { - System.arraycopy(packageName, 0, result, pos, packageLength); - pos += packageLength; + + /** + * @see org.eclipse.wst.jsdt.internal.core.search.matching.JavaSearchPattern#getBlankPattern() + */ + public SearchPattern getBlankPattern() { + return new SuperTypeReferencePattern(R_EXACT_MATCH | R_CASE_SENSITIVE); } - result[pos++] = SEPARATOR; - result[pos] = (char) modifiers; - return result; -} -public SuperTypeReferencePattern( - char[] superQualification, - char[] superSimpleName, - int matchRule) { + /** + * @see org.eclipse.wst.jsdt.core.search.SearchPattern#getIndexCategories() + */ + public char[][] getIndexCategories() { + return CATEGORIES; + } - this(matchRule); + /** + * @see org.eclipse.wst.jsdt.core.search.SearchPattern#matchesDecodedKey(org.eclipse.wst.jsdt.core.search.SearchPattern) + */ + public boolean matchesDecodedKey(SearchPattern decodedPattern) { + SuperTypeReferencePattern pattern = (SuperTypeReferencePattern) decodedPattern; - this.superQualification = isCaseSensitive() ? superQualification : CharOperation.toLowerCase(superQualification); - this.superSimpleName = (isCaseSensitive() || isCamelCase()) ? superSimpleName : CharOperation.toLowerCase(superSimpleName); - ((InternalSearchPattern)this).mustResolve = superQualification != null; -} -SuperTypeReferencePattern(int matchRule) { - super(SUPER_REF_PATTERN, matchRule); -} -/* - * superSimpleName / superQualification / simpleName / enclosingTypeName / typeParameters / pkgName / superClassOrInterface classOrInterface modifiers - */ -public void decodeIndexKey(char[] key) { - int slash = CharOperation.indexOf(SEPARATOR, key, 0); - this.superSimpleName = CharOperation.subarray(key, 0, slash); - - // some values may not have been know when indexed so decode as null - int start = slash + 1; - slash = CharOperation.indexOf(SEPARATOR, key, start); - this.superQualification = slash == start ? null : CharOperation.subarray(key, start, slash); - - slash = CharOperation.indexOf(SEPARATOR, key, start = slash + 1); - this.simpleName = CharOperation.subarray(key, start, slash); - - start = ++slash; - if (key[start] == SEPARATOR) { - this.enclosingTypeName = null; - } else { - slash = CharOperation.indexOf(SEPARATOR, key, start); - if (slash == (start+1) && key[start] == ZERO_CHAR) { - this.enclosingTypeName = ONE_ZERO; - } else { - char[] names = CharOperation.subarray(key, start, slash); - this.enclosingTypeName = names; + if (pattern.superTypeName != null) { + if (!matchesName(this.superTypeName, pattern.superTypeName)) { + return false; + } } - } - start = ++slash; - if (key[start] == SEPARATOR) { - this.pkgName = null; - } else { - slash = CharOperation.indexOf(SEPARATOR, key, start); - if (slash == (start+1) && key[start] == ZERO_CHAR) { - this.pkgName = this.superQualification; - } else { - char[] names = CharOperation.subarray(key, start, slash); - this.pkgName = names; - } + return matchesName(this.typeName, pattern.typeName); } - this.modifiers = key[slash + 3]; // implicit cast to int type -} -public SearchPattern getBlankPattern() { - return new SuperTypeReferencePattern(R_EXACT_MATCH | R_CASE_SENSITIVE); -} -public char[][] getIndexCategories() { - return CATEGORIES; -} -public boolean matchesDecodedKey(SearchPattern decodedPattern) { - SuperTypeReferencePattern pattern = (SuperTypeReferencePattern) decodedPattern; - - if (pattern.superQualification != null) - if (!matchesName(this.superQualification, pattern.superQualification)) return false; + /** + * @see org.eclipse.wst.jsdt.internal.core.search.matching.InternalSearchPattern#queryIn(org.eclipse.wst.jsdt.internal.core.index.Index) + */ + EntryResult[] queryIn(Index index) throws IOException { + char[] key = this.superTypeName; // can be null + int matchRule = getMatchRule(); + + // cannot include the superQualification since it may not exist in the index + switch (getMatchMode()) { + case R_EXACT_MATCH : + if (this.isCamelCase) + break; + // do a prefix query with the superSimpleName + matchRule &= ~R_EXACT_MATCH; + matchRule |= R_PREFIX_MATCH; + if (this.superTypeName != null) + key = CharOperation.append(this.superTypeName, SEPARATOR); + break; + case R_PREFIX_MATCH : + // do a prefix query with the superSimpleName + break; + case R_PATTERN_MATCH : + // do a pattern query with the superSimpleName + break; + case R_REGEXP_MATCH : + // TODO (frederic) implement regular expression match + break; + } - return matchesName(this.superSimpleName, pattern.superSimpleName); -} -EntryResult[] queryIn(Index index) throws IOException { - char[] key = this.superSimpleName; // can be null - int matchRule = getMatchRule(); - - // cannot include the superQualification since it may not exist in the index - switch(getMatchMode()) { - case R_EXACT_MATCH : - if (this.isCamelCase) break; - // do a prefix query with the superSimpleName - matchRule &= ~R_EXACT_MATCH; - matchRule |= R_PREFIX_MATCH; - if (this.superSimpleName != null) - key = CharOperation.append(this.superSimpleName, SEPARATOR); - break; - case R_PREFIX_MATCH : - // do a prefix query with the superSimpleName - break; - case R_PATTERN_MATCH : - // do a pattern query with the superSimpleName - break; - case R_REGEXP_MATCH : - // TODO (frederic) implement regular expression match - break; + // match rule is irrelevant when the key is null + return index.query(getIndexCategories(), key, matchRule); } - return index.query(getIndexCategories(), key, matchRule); // match rule is irrelevant when the key is null -} -protected StringBuffer print(StringBuffer output) { + /** + * @see org.eclipse.wst.jsdt.internal.core.search.matching.JavaSearchPattern#print(java.lang.StringBuffer) + */ + protected StringBuffer print(StringBuffer output) { output.append("SuperClassReferencePattern: <"); //$NON-NLS-1$ - if (superSimpleName != null) - output.append(superSimpleName); - else - output.append("*"); //$NON-NLS-1$ - output.append(">"); //$NON-NLS-1$ - return super.print(output); -} + if (superTypeName != null) { + output.append(superTypeName); + } else { + output.append("*"); //$NON-NLS-1$ + } + + output.append(">"); //$NON-NLS-1$ + return super.print(output); + } } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/TypeDeclarationLocator.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/TypeDeclarationLocator.java index c62b50fc..734e0d39 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/TypeDeclarationLocator.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/TypeDeclarationLocator.java @@ -36,7 +36,7 @@ public TypeDeclarationLocator(TypeDeclarationPattern pattern) { //public int match(MessageSend node, MatchingNodeSet nodeSet) - SKIP IT //public int match(Reference node, MatchingNodeSet nodeSet) - SKIP IT public int match(TypeDeclaration node, MatchingNodeSet nodeSet) { - if (this.pattern.simpleName == null || matchesName(this.pattern.simpleName, node.name)) + if (matchesName(this.pattern.simpleName, node.name)) return nodeSet.addMatch(node, ((InternalSearchPattern)this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH); return IMPOSSIBLE_MATCH; @@ -44,11 +44,16 @@ public int match(TypeDeclaration node, MatchingNodeSet nodeSet) { //public int match(TypeReference node, MatchingNodeSet nodeSet) - SKIP IT public int match(InferredType node, MatchingNodeSet nodeSet) { char[] typeName = node.getName(); - if (this.pattern.simpleName == null || matchesName(this.pattern.simpleName, typeName)) + char[] patternName; + if (this.pattern.getSearchPrefix() != null) { + patternName = this.pattern.getSearchPrefix(); + } else { + patternName = this.pattern.simpleName; + } + if (matchesName(patternName, typeName)) return nodeSet.addMatch(node, ((InternalSearchPattern)this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH); - char [] pkg=(this.pattern instanceof QualifiedTypeDeclarationPattern)? ((QualifiedTypeDeclarationPattern)this.pattern).qualification : this.pattern.pkg; - if (pkg!=null) - { + char [] pkg = this.pattern.qualification; + if (this.pattern.getSearchPrefix() == null && pkg != null) { if (pkg.length>0 && matchesName(CharOperation.concat(pkg, this.pattern.simpleName, '.'), typeName)) return nodeSet.addMatch(node, ((InternalSearchPattern)this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH); @@ -57,7 +62,7 @@ public int match(InferredType node, MatchingNodeSet nodeSet) { { int index=CharOperation.lastIndexOf('.', typeName); if (index>=0 && - matchesName(CharOperation.subarray(typeName, index+1,typeName.length),this.pattern.simpleName)) + matchesName(patternName, CharOperation.subarray(typeName, index+1,typeName.length))) return nodeSet.addMatch(node, ((InternalSearchPattern)this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH); } @@ -70,7 +75,7 @@ public int resolveLevel(ASTNode node) { else if (node instanceof InferredType) { InferredType type=(InferredType) node; - if (!type.isDefinition || (type.isAnonymous && !type.isNamed())) + if (!type.isDefinition() || !type.isIndexed()) return IMPOSSIBLE_MATCH; binding=type.binding; } @@ -85,21 +90,13 @@ public int resolveLevel(Binding binding) { TypeBinding type = (TypeBinding) binding; - switch (this.pattern.typeSuffix) { - case CLASS_SUFFIX: - if (!type.isClass()) return IMPOSSIBLE_MATCH; - break; - case TYPE_SUFFIX : // nothing - } - - // fully qualified name - if (this.pattern instanceof QualifiedTypeDeclarationPattern) { - QualifiedTypeDeclarationPattern qualifiedPattern = (QualifiedTypeDeclarationPattern) this.pattern; - return resolveLevelForType(qualifiedPattern.simpleName, qualifiedPattern.qualification, type); + int resolveLevel; + if (this.pattern.getSearchPrefix() != null) { + resolveLevel = resolveLevelUsingSearchPrefix(this.pattern.getSearchPrefix(), type); } else { - char[] enclosingTypeName = this.pattern.enclosingTypeNames == null ? null : CharOperation.concatWith(this.pattern.enclosingTypeNames, '.'); - return resolveLevelForType(this.pattern.simpleName, this.pattern.pkg, enclosingTypeName, type); + resolveLevel = resolveLevelForType(this.pattern.simpleName, this.pattern.qualification, type); } + return resolveLevel; } /** * Returns whether the given type binding matches the given simple name pattern @@ -116,7 +113,7 @@ protected int resolveLevelForType(char[] simpleNamePattern, char[] qualification // pattern was created from a Java element: qualification is the package name. char[] fullQualificationPattern = CharOperation.concat(qualificationPattern, enclosingNamePattern, '.'); - if (CharOperation.equals(this.pattern.pkg, CharOperation.concatWith(type.getPackage().compoundName, '.'))) + if (CharOperation.equals(this.pattern.qualification, CharOperation.concatWith(type.getPackage().compoundName, '.'))) return resolveLevelForType(simpleNamePattern, fullQualificationPattern, type); return IMPOSSIBLE_MATCH; } @@ -128,7 +125,7 @@ public String toString() { public int matchMetadataElement(IJavaScriptElement element) { String elementName = element.getElementName(); char[] typeName = elementName.toCharArray(); - char [] pkg=(this.pattern instanceof QualifiedTypeDeclarationPattern)? ((QualifiedTypeDeclarationPattern)this.pattern).qualification : this.pattern.pkg; + char [] pkg = this.pattern.qualification; if (this.pattern.simpleName == null || matchesName(this.pattern.simpleName, typeName)) return ACCURATE_MATCH; if (pkg!=null && pkg.length>0 && diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/TypeDeclarationPattern.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/TypeDeclarationPattern.java index bbb9fe35..5a357d59 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/TypeDeclarationPattern.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/TypeDeclarationPattern.java @@ -1,326 +1,516 @@ -/******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Michael Spector Bug 242987 - *******************************************************************************/ -package org.eclipse.wst.jsdt.internal.core.search.matching; - -import java.io.IOException; - -import org.eclipse.wst.jsdt.core.compiler.CharOperation; -import org.eclipse.wst.jsdt.core.search.SearchPattern; -import org.eclipse.wst.jsdt.internal.core.index.EntryResult; -import org.eclipse.wst.jsdt.internal.core.index.Index; - -public class TypeDeclarationPattern extends JavaSearchPattern { - -public char[] simpleName; -public char[] pkg; -public char[][] enclosingTypeNames; - -// set to CLASS_SUFFIX for only matching classes -// set to INTERFACE_SUFFIX for only matching interfaces -// set to ENUM_SUFFIX for only matching enums -// set to ANNOTATION_TYPE_SUFFIX for only matching annotation types -// set to TYPE_SUFFIX for matching both classes and interfaces -public char typeSuffix; -public int modifiers; -public boolean secondary = false; - -protected static char[][] CATEGORIES = { TYPE_DECL }; - -// want to save space by interning the package names for each match -static PackageNameSet internedPackageNames = new PackageNameSet(1001); -static class PackageNameSet { - -public char[][] names; -public int elementSize; // number of elements in the table -public int threshold; - -PackageNameSet(int size) { - this.elementSize = 0; - this.threshold = size; // size represents the expected number of elements - int extraRoom = (int) (size * 1.5f); - if (this.threshold == extraRoom) - extraRoom++; - this.names = new char[extraRoom][]; -} - -char[] add(char[] name) { - int length = names.length; - int index = CharOperation.hashCode(name) % length; - char[] current; - while ((current = names[index]) != null) { - if (CharOperation.equals(current, name)) return current; - if (++index == length) index = 0; - } - names[index] = name; - - // assumes the threshold is never equal to the size of the table - if (++elementSize > threshold) rehash(); - return name; -} - -void rehash() { - PackageNameSet newSet = new PackageNameSet(elementSize * 2); // double the number of expected elements - char[] current; - for (int i = names.length; --i >= 0;) - if ((current = names[i]) != null) - newSet.add(current); - - this.names = newSet.names; - this.elementSize = newSet.elementSize; - this.threshold = newSet.threshold; -} -} - -/* - * Create index key for type declaration pattern: - * key = typeName / packageName / enclosingTypeName / modifiers - * or for secondary types - * key = typeName / packageName / enclosingTypeName / modifiers / 'S' - */ -public static char[] createIndexKey(int modifiers, char[] typeName, char[] packageName, char[][] enclosingTypeNames, boolean secondary) { //, char typeSuffix) { - int typeNameLength = typeName == null ? 0 : typeName.length; - int packageLength = packageName == null ? 0 : packageName.length; - int enclosingNamesLength = 0; - if (enclosingTypeNames != null) { - for (int i = 0, length = enclosingTypeNames.length; i < length;) { - enclosingNamesLength += enclosingTypeNames[i].length; - if (++i < length) - enclosingNamesLength++; // for the '.' separator - } - } - - int resultLength = typeNameLength + packageLength + enclosingNamesLength + 5; - if (secondary) resultLength += 2; - char[] result = new char[resultLength]; - int pos = 0; - if (typeNameLength > 0) { - System.arraycopy(typeName, 0, result, pos, typeNameLength); - pos += typeNameLength; - } - result[pos++] = SEPARATOR; - if (packageLength > 0) { - System.arraycopy(packageName, 0, result, pos, packageLength); - pos += packageLength; - } - result[pos++] = SEPARATOR; - if (enclosingTypeNames != null && enclosingNamesLength > 0) { - for (int i = 0, length = enclosingTypeNames.length; i < length;) { - char[] enclosingName = enclosingTypeNames[i]; - int itsLength = enclosingName.length; - System.arraycopy(enclosingName, 0, result, pos, itsLength); - pos += itsLength; - if (++i < length) - result[pos++] = '.'; - } - } - result[pos++] = SEPARATOR; - result[pos++] = (char) modifiers; - result[pos] = (char) (modifiers>>16); - if (secondary) { - result[++pos] = SEPARATOR; - result[++pos] = 'S'; - } - return result; -} - -public TypeDeclarationPattern( - char[] pkg, - char[][] enclosingTypeNames, - char[] simpleName, - char typeSuffix, - int matchRule) { - - this(matchRule); - - int index; - if (simpleName!=null && (index=CharOperation.lastIndexOf('.',simpleName)) >0) - { - pkg=CharOperation.subarray(simpleName, 0, index); -// simpleName=CharOperation.subarray(simpleName, index+1, simpleName.length); - } - - this.pkg = isCaseSensitive() ? pkg : CharOperation.toLowerCase(pkg); - if (isCaseSensitive() || enclosingTypeNames == null) { - this.enclosingTypeNames = enclosingTypeNames; - } else { - int length = enclosingTypeNames.length; - this.enclosingTypeNames = new char[length][]; - for (int i = 0; i < length; i++) - this.enclosingTypeNames[i] = CharOperation.toLowerCase(enclosingTypeNames[i]); - } - this.simpleName = (isCaseSensitive() || isCamelCase()) ? simpleName : CharOperation.toLowerCase(simpleName); - this.typeSuffix = typeSuffix; - - ((InternalSearchPattern)this).mustResolve = (this.pkg != null && this.enclosingTypeNames != null) || typeSuffix != TYPE_SUFFIX; -} -TypeDeclarationPattern(int matchRule) { - super(TYPE_DECL_PATTERN, matchRule); -} -/* - * Type entries are encoded as: - * simpleTypeName / packageName / enclosingTypeName / modifiers - * e.g. Object/java.lang//0 - * e.g. Cloneable/java.lang//512 - * e.g. LazyValue/javax.swing/UIDefaults/0 - * or for secondary types as: - * simpleTypeName / packageName / enclosingTypeName / modifiers / S - */ -public void decodeIndexKey(char[] key) { - int slash = CharOperation.indexOf(SEPARATOR, key, 0); - this.simpleName = CharOperation.subarray(key, 0, slash); - - int start = ++slash; - if (key[start] == SEPARATOR) { - this.pkg = CharOperation.NO_CHAR; - } else { - slash = CharOperation.indexOf(SEPARATOR, key, start); - this.pkg = internedPackageNames.add(CharOperation.subarray(key, start, slash)); - } - - // Continue key read by the end to decode modifiers - int last = key.length-1; - this.secondary = key[last] == 'S'; - if (this.secondary) { - last -= 2; - } - this.modifiers = key[last-1] + (key[last]<<16); - decodeModifiers(); - - // Retrieve enclosing type names - start = slash + 1; - last -= 2; // position of ending slash - if (start == last) { - this.enclosingTypeNames = CharOperation.NO_CHAR_CHAR; - } else { - if (last == (start+1) && key[start] == ZERO_CHAR) { - this.enclosingTypeNames = ONE_ZERO_CHAR; - } else { - this.enclosingTypeNames = CharOperation.splitOn('.', key, start, last); - } - } -} -protected void decodeModifiers() { - this.typeSuffix = CLASS_SUFFIX; -} -public SearchPattern getBlankPattern() { - return new TypeDeclarationPattern(R_EXACT_MATCH | R_CASE_SENSITIVE); -} -public char[][] getIndexCategories() { - return CATEGORIES; -} -public boolean matchesDecodedKey(SearchPattern decodedPattern) { - TypeDeclarationPattern pattern = (TypeDeclarationPattern) decodedPattern; - - // check type suffix - if (this.typeSuffix != pattern.typeSuffix && typeSuffix != TYPE_SUFFIX) { - if (!matchDifferentTypeSuffixes(this.typeSuffix, pattern.typeSuffix)) { - return false; - } - } - - // check name - if (!matchesName(this.simpleName, pattern.simpleName)) - return false; - - // check package - exact match only - //if (this.pkg != null && !CharOperation.equals(this.pkg, pattern.pkg, isCaseSensitive())) - //return false; - - // check enclosingTypeNames - exact match only - if (this.enclosingTypeNames != null) { - if (this.enclosingTypeNames.length == 0) - return pattern.enclosingTypeNames.length == 0; - if (this.enclosingTypeNames.length == 1 && pattern.enclosingTypeNames.length == 1) - return CharOperation.equals(this.enclosingTypeNames[0], pattern.enclosingTypeNames[0], isCaseSensitive()); - if (pattern.enclosingTypeNames == ONE_ZERO_CHAR) - return true; // is a local or anonymous type - return CharOperation.equals(this.enclosingTypeNames, pattern.enclosingTypeNames, isCaseSensitive()); - } - return true; -} -EntryResult[] queryIn(Index index) throws IOException { - char[] key = this.simpleName; // can be null - int matchRule = getMatchRule(); - - switch(getMatchMode()) { - case R_PREFIX_MATCH : - // do a prefix query with the simpleName - break; - case R_EXACT_MATCH : - if (this.isCamelCase) break; - matchRule &= ~R_EXACT_MATCH; - if (this.simpleName != null) { - matchRule |= R_PREFIX_MATCH; - key = this.pkg == null - ? CharOperation.append(this.simpleName, SEPARATOR) - : CharOperation.concat(this.simpleName, SEPARATOR, this.pkg, SEPARATOR, CharOperation.NO_CHAR); - break; // do a prefix query with the simpleName and possibly the pkg - } - matchRule |= R_PATTERN_MATCH; - // fall thru to encode the key and do a pattern query - case R_PATTERN_MATCH : - if (this.pkg == null) { - if (this.simpleName == null) { - switch(this.typeSuffix) { - case CLASS_SUFFIX : - // null key already returns all types - // key = new char[] {ONE_STAR[0], SEPARATOR, ONE_STAR[0]}; - break; - } - } else if (this.simpleName[this.simpleName.length - 1] != '*') { - key = CharOperation.concat(this.simpleName, ONE_STAR, SEPARATOR); - } - break; // do a pattern query with the current encoded key - } - // must decode to check enclosingTypeNames due to the encoding of local types - key = CharOperation.concat( - this.simpleName == null ? ONE_STAR : this.simpleName, SEPARATOR, this.pkg, SEPARATOR, ONE_STAR); - break; - case R_REGEXP_MATCH : - // TODO (frederic) implement regular expression match - break; - } - - return index.query(getIndexCategories(), key, matchRule); // match rule is irrelevant when the key is null -} -protected StringBuffer print(StringBuffer output) { - switch (this.typeSuffix){ - case CLASS_SUFFIX : - output.append("ClassDeclarationPattern: pkg<"); //$NON-NLS-1$ - break; - default : - output.append("TypeDeclarationPattern: pkg<"); //$NON-NLS-1$ - break; - } - if (pkg != null) - output.append(pkg); - else - output.append("*"); //$NON-NLS-1$ - output.append(">, enclosing<"); //$NON-NLS-1$ - if (enclosingTypeNames != null) { - for (int i = 0; i < enclosingTypeNames.length; i++){ - output.append(enclosingTypeNames[i]); - if (i < enclosingTypeNames.length - 1) - output.append('.'); - } - } else { - output.append("*"); //$NON-NLS-1$ - } - output.append(">, type<"); //$NON-NLS-1$ - if (simpleName != null) - output.append(simpleName); - else - output.append("*"); //$NON-NLS-1$ - output.append(">"); //$NON-NLS-1$ - return super.print(output); -} -} +/******************************************************************************* + * Copyright (c) 2000, 2011 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + * Michael Spector Bug 242987 + *******************************************************************************/ +package org.eclipse.wst.jsdt.internal.core.search.matching; + +import java.io.IOException; + +import org.eclipse.wst.jsdt.core.compiler.CharOperation; +import org.eclipse.wst.jsdt.core.search.SearchPattern; +import org.eclipse.wst.jsdt.internal.compiler.classfmt.ClassFileConstants; +import org.eclipse.wst.jsdt.internal.core.Logger; +import org.eclipse.wst.jsdt.internal.core.index.EntryResult; +import org.eclipse.wst.jsdt.internal.core.index.Index; +import org.eclipse.wst.jsdt.internal.core.util.QualificationHelpers; + +/** + *

    Search pattern used to find and create type declaration index entries.

    + */ +public class TypeDeclarationPattern extends JavaSearchPattern { + /** + *

    Qualification of the type declaration.

    + */ + public char[] qualification; + + /** + *

    Simple type name of the type declaration .

    + */ + public char[] simpleName; + + /** + *

    Super types of the type declaration.

    + */ + public char[][] superTypes; + + /** + * @deprecated this will be removed at some point because it does not apply to JavaScript and is not longer used internally + */ + public char[][] enclosingTypeNames; + + /** + *

    Optional

    + * + *

    Any modifiers for this type declaration.

    + * + * @see ClassFileConstants + */ + public int modifiers; + + /** + *

    Used when searing for type declarations using a given prefix. + * This prefix will be used to match on either the {@link TypeDeclarationPattern#qualification} + * or the {@link TypeDeclarationPattern#simpleName}.

    + * + * @see #TypeDeclarationPattern(char[], int) + * + * @see TypeDeclarationPattern#qualification + * @see TypeDeclarationPattern#simpleName + */ + private char[] fSearchPrefix; + + /** + *

    Categories to search in for matches in the index.

    + */ + private static char[][] CATEGORIES = { TYPE_DECL }; + + + /** + *

    Internal constructor for creating plank patterns

    + * + * @param matchRule match rule used when comparing this pattern to search results + */ + TypeDeclarationPattern(int matchRule) { + super(TYPE_DECL_PATTERN, matchRule); + } + + /** + *

    Constructor to use when searching for a type with a specific simple name and qualification.

    + * + * @param qualification optional qualification of the type, if not specified then the type + * does not have a qualification. + * @param simpleName simple type name of the type + * @param matchRule match rule used when comparing this pattern to search results + */ + public TypeDeclarationPattern( + char[] qualification, + char[] simpleName, + int matchRule) { + + this(qualification, simpleName, null, matchRule); + } + + /** + *

    Constructor to create a pattern using qualification, simple name, and super types.

    + * + * @param qualification optional qualification of the type, if not specified then the type + * does not have a qualification. + * @param simpleName simple type name of the type + * @param superTypes + * @param matchRule match rule used when comparing this pattern to search results + */ + public TypeDeclarationPattern( + char[] qualification, + char[] simpleName, + char[][] superTypes, + int matchRule) { + + this(matchRule); + + /* if someone past a fully qualified name as the simple name break it up, should not have to do this + * else initialize normally + */ + if((qualification == null || qualification.length == 0) && CharOperation.contains(DOT, simpleName)) { + char[][] seperated = QualificationHelpers.seperateFullyQualifedName(simpleName); + this.qualification = seperated[QualificationHelpers.QULIFIERS_INDEX]; + this.simpleName = seperated[QualificationHelpers.SIMPLE_NAMES_INDEX]; + } else { + if(qualification != null && qualification.length > 0) { + this.qualification = qualification; + } else { + this.qualification = null; + } + this.simpleName = simpleName; + } + + //deal with case sensitive and camel case + this.qualification = (isCaseSensitive() || isCamelCase()) ? this.qualification : CharOperation.toLowerCase(this.qualification); + this.simpleName = (isCaseSensitive() || isCamelCase()) ? this.simpleName : CharOperation.toLowerCase(this.simpleName); + + + this.superTypes = superTypes; + } + + /** + *

    Constructor to use when searching for a type declaration based on a given prefix.

    + * + * @param searchPrefix to match against either the fully qualified name or simple name of + * type declarations + * @param matchRule match rule used when comparing this pattern to search results + */ + public TypeDeclarationPattern(char[] searchPrefix, int matchRule) { + this(matchRule); + + this.fSearchPrefix = (isCaseSensitive() || isCamelCase()) ? searchPrefix : CharOperation.toLowerCase(searchPrefix); + } + + /** + * @see org.eclipse.wst.jsdt.core.search.SearchPattern#decodeIndexKey(char[]) + * @see #createIndexKey(char[], char[][], int) + */ + public void decodeIndexKey(char[] key) { + char[][] seperated = CharOperation.splitOn(SEPARATOR, key); + + //decode type name + this.simpleName = seperated[0]; + this.qualification = seperated[1]; + + //get super types + this.superTypes = CharOperation.splitOn(PARAMETER_SEPARATOR, seperated[2]); + + //get the modifiers + this.modifiers = seperated[3][0] + seperated[3][1]; + } + + /** + * @see org.eclipse.wst.jsdt.internal.core.search.matching.JavaSearchPattern#getBlankPattern() + */ + public SearchPattern getBlankPattern() { + return new TypeDeclarationPattern(R_EXACT_MATCH | R_CASE_SENSITIVE); + } + + /** + * @see org.eclipse.wst.jsdt.core.search.SearchPattern#getIndexCategories() + */ + public char[][] getIndexCategories() { + return CATEGORIES; + } + + /** + *

    Matches this pattern against another pattern using the following logic:

      + *
    • OR
        + *
      • AND
          + *
        • this pattern has a defined search prefix
        • + *
        • OR
            + *
          • this pattern's prefix matches the other patterns qualified name
          • + *
          • this pattern's prefix matches the other patterns simple name
          • + *
          • AND if after separating this pattern's prefix into a qualifier and simple name
              + *
            • this pattern's prefix qualifier matches the other patterns qualified name
            • + *
            • this pattern's prefix simple name matches the other patterns simple name
      • + *
      • AND
          + *
        • this pattern does not have a defined search prefix
        • + *
        • this pattern's qualified name equals the other patterns qualified name
        • + *
        • this pattern's simple name equals the other patterns simple name

+ * + * @see org.eclipse.wst.jsdt.core.search.SearchPattern#matchesDecodedKey(org.eclipse.wst.jsdt.core.search.SearchPattern) + */ + public boolean matchesDecodedKey(SearchPattern decodedPattern) { + TypeDeclarationPattern pattern = (TypeDeclarationPattern) decodedPattern; + char[][] seperatedSearchPrefix = QualificationHelpers.seperateFullyQualifedName(this.fSearchPrefix); + + return + ( + this.fSearchPrefix != null && + ( + matchesName(this.fSearchPrefix, CharOperation.append(pattern.qualification, '.')) || + matchesName(this.fSearchPrefix, pattern.simpleName) || + ( + ( + CharOperation.equals(seperatedSearchPrefix[QualificationHelpers.QULIFIERS_INDEX], pattern.qualification, isCaseSensitive) || + matchesQualificationPattern(seperatedSearchPrefix[QualificationHelpers.QULIFIERS_INDEX], pattern.qualification, isCaseSensitive) + ) && + matchesName(seperatedSearchPrefix[QualificationHelpers.SIMPLE_NAMES_INDEX], pattern.simpleName) + ) + ) + ) + || + ( + this.fSearchPrefix == null && + matchesName(this.qualification, pattern.qualification) && + matchesName(this.simpleName, pattern.simpleName) + ) + || + ( + this.fSearchPrefix == null && this.superTypes != null && + matchesName(this.superTypes, pattern.superTypes) + ); + } + + /** + * @param superTypes + * @param patternSuperTypes + * @return + */ + private boolean matchesName(char[][] superTypes, char[][] patternSuperTypes) { + for (int i = 0; i < superTypes.length; i++) { + for (int j = 0; j < patternSuperTypes.length; j++) { + if (matchesName(this.superTypes[i], patternSuperTypes[j])) + return true; + } + } + return false; + } + + /** + * @see org.eclipse.wst.jsdt.internal.core.search.matching.InternalSearchPattern#queryIn(org.eclipse.wst.jsdt.internal.core.index.Index) + */ + EntryResult[] queryIn(Index index) throws IOException { + EntryResult[] results = null; + + //determine the qualification and simple name patterns to use + char[] qualificationPattern; + char[] simpleNamePattern; + if(this.fSearchPrefix != null) { + char[][] seperatedSearchPrefix = QualificationHelpers.seperateFullyQualifedName(this.fSearchPrefix); + qualificationPattern = seperatedSearchPrefix[QualificationHelpers.QULIFIERS_INDEX]; + simpleNamePattern = seperatedSearchPrefix[QualificationHelpers.SIMPLE_NAMES_INDEX]; + } else { + qualificationPattern = this.qualification; + simpleNamePattern = this.simpleName; + } + + //might have to do multiple searches + char[][] keys = null; + int[] matchRules = null; + + switch(getMatchMode()) { + case R_EXACT_MATCH : + keys = new char[1][]; + matchRules = new int[1]; + //can not do an exact match with camel case + if (this.isCamelCase) break; + + /* doing an exact match on the type, but really doing a prefix match in the index for + * simpleName// or simpleName/qualification/ + */ + + if(qualificationPattern == null || qualificationPattern.length == 0) { + keys[0] = CharOperation.append(simpleNamePattern, SEPARATOR); + } else { + keys[0] = CharOperation.concat(simpleNamePattern, qualificationPattern, SEPARATOR); + } + + keys[0] = CharOperation.append(keys[0], SEPARATOR); + if (superTypes != null) + keys[0] = CharOperation.concat(keys[0], CharOperation.concatWith(superTypes, PARAMETER_SEPARATOR)); + + matchRules[0] = this.getMatchRule(); + matchRules[0] &= ~R_EXACT_MATCH; + matchRules[0] |= R_PREFIX_MATCH; + break; + case R_PREFIX_MATCH : + if(qualificationPattern != null && qualificationPattern.length > 0) { + if(simpleNamePattern == null || simpleNamePattern.length == 0) { + keys = new char[1][]; + matchRules = new int[1]; + } else { + keys = new char[2][]; + matchRules = new int[2]; + + /* search just simple name because can not search camel case simple name with qualification: + * simpleNamePattern + */ + keys[1] = simpleNamePattern; + matchRules[1] = this.getMatchRule(); + } + + /* do a pattern search using the entire pattern as the qualification: + * * /fSearchPrefix* + */ + char[] trimmedPrefix = this.fSearchPrefix; + if(this.fSearchPrefix != null && this.fSearchPrefix[this.fSearchPrefix.length - 1] == DOT) { + trimmedPrefix = CharOperation.subarray(this.fSearchPrefix, 0, this.fSearchPrefix.length - 1); + } + + keys[0] = CharOperation.concat(ONE_STAR, trimmedPrefix, SEPARATOR); + keys[0] = CharOperation.concat(keys[0], ONE_STAR); + if (superTypes != null) + keys[0] = CharOperation.concat(keys[0], CharOperation.concatWith(superTypes, PARAMETER_SEPARATOR)); + matchRules[0] = this.getMatchRule(); + matchRules[0] &= ~R_PREFIX_MATCH; + matchRules[0] |= R_PATTERN_MATCH; + } else { + if(simpleNamePattern == null || simpleNamePattern.length == 0) { + keys = new char[1][]; + matchRules = new int[1]; + } else { + keys = new char[2][]; + matchRules = new int[2]; + + /* first key to search for is using the simple name as the simple name using prefix match: + * simpleNamePattern + */ + keys[1] = simpleNamePattern; + matchRules[1] = this.getMatchRule(); + } + + /* second key to search for is using the simple name as the qualifier using a pattern match + * * /simpleNamePattern* + */ + keys[0] = CharOperation.concat(ONE_STAR, simpleNamePattern, SEPARATOR); + keys[0] = CharOperation.concat(keys[0], ONE_STAR); + matchRules[0] = this.getMatchRule(); + matchRules[0] &= ~R_PREFIX_MATCH; + matchRules[0] |= R_PATTERN_MATCH; + } + + break; + case R_PATTERN_MATCH : + /* create the pattern: + * simpleNamePattern/qualificationPattern/* + */ + if (this.fSearchPrefix != null) { + keys = new char[2][]; + matchRules = new int[2]; + + /* Key to search for is using the entire pattern as the qualification: + * * /fSearchPrefix/* + */ + keys[1] = CharOperation.concat(ONE_STAR, this.fSearchPrefix, SEPARATOR); + keys[1] = CharOperation.concat(keys[1], ONE_STAR, SEPARATOR); + matchRules[1] = this.getMatchRule(); + } else { + keys = new char[1][]; + matchRules = new int[1]; + } + + //if no simple name use * + if (simpleNamePattern == null || simpleNamePattern.length == 0) { + simpleNamePattern = ONE_STAR; + } + + //if no qualification use * + if (qualificationPattern == null || qualificationPattern.length == 0) { + qualificationPattern = ONE_STAR; + } + + /* Key to search for is using the simple name of the pattern as the simple name + * simpleNamePattern/qualificationPattern/* + */ + keys[0] = CharOperation.concat(simpleNamePattern, qualificationPattern, SEPARATOR); + if (superTypes != null) { + // account for modifier values in #createIndexKey() by appending an extra SEPARATOR and ONE_STAR + keys[0] = CharOperation.concat(keys[0], SEPARATOR, CharOperation.concatWith(superTypes, PARAMETER_SEPARATOR), SEPARATOR, ONE_STAR); + } + else { + keys[0] = CharOperation.concat(keys[0], ONE_STAR, SEPARATOR); + } + matchRules[0] = this.getMatchRule(); + + break; + case R_REGEXP_MATCH : + Logger.log(Logger.WARNING, "Regular expression matching is not implimented by ConstructorDeclarationPattern"); + break; + } + + //run a search for each search key + for(int i = 0; i < keys.length; ++i) { + //run search + EntryResult[] additionalResults = index.query(getIndexCategories(), keys[i], matchRules[i]); + + //collect results + if(additionalResults != null && additionalResults.length > 0) { + if(results == null) { + results = additionalResults; + } else { + EntryResult[] existingResults = results; + + results = new EntryResult[existingResults.length + additionalResults.length]; + + System.arraycopy(existingResults, 0, results, 0, existingResults.length); + System.arraycopy(additionalResults, 0, results, existingResults.length, additionalResults.length); + } + } + } + + return results; + } + + /** + * @see org.eclipse.wst.jsdt.internal.core.search.matching.JavaSearchPattern#print(java.lang.StringBuffer) + */ + protected StringBuffer print(StringBuffer output) { + if (qualification != null) + output.append(qualification); + else + output.append("*"); //$NON-NLS-1$ + + if (simpleName != null) + output.append(simpleName); + else + output.append("*"); //$NON-NLS-1$ + output.append(">"); //$NON-NLS-1$ + return super.print(output); + } + + /** + *

Creates a type declaration index key, based on the given information, to be placed in the index.

+ * + *

Key Syntax: + * simpleName/qualification/fullyQualifiedSuperTypeNames/modifiers

+ * + * @param qualification optional qualification of the type, if not specified then the type + * does not have a qualification. + * @param simpleName simple type name of the type + * @param fullyQualifiedSuperTypeNames list of fully qualified super type names + * @param modifiers Modifiers to the type declaration + * + * @return Type declaration index key + */ + public static char[] createIndexKey(char[] qualification, char[] simpleName, char[][] fullyQualifiedSuperTypeNames, int modifiers) { + char[] indexKey = null; + + if(simpleName != null) { + //build list of super types + char[] fullyQualifiedSuperTypeNamesList = null; + if(fullyQualifiedSuperTypeNames != null) { + fullyQualifiedSuperTypeNamesList = CharOperation.concatWith(fullyQualifiedSuperTypeNames, PARAMETER_SEPARATOR); + } else { + fullyQualifiedSuperTypeNamesList = CharOperation.NO_CHAR; + } + + //get lengths + int simpleNameLength = simpleName.length; + int qualificationLength = qualification == null ? 0 : qualification.length; + + //get length + int keyLength = simpleNameLength + + 1 + qualificationLength + + 1 + fullyQualifiedSuperTypeNamesList.length + + 3; //modifiers + + //create result char array + indexKey = new char[keyLength]; + + //add simple type name to result + int pos = 0; + if (simpleNameLength > 0) { + System.arraycopy(simpleName, 0, indexKey, pos, simpleNameLength); + pos += simpleNameLength; + } + + //add qualification to result + indexKey[pos++] = SEPARATOR; + if (qualificationLength > 0) { + System.arraycopy(qualification, 0, indexKey, pos, qualificationLength); + pos += qualificationLength; + } + + //add super types + indexKey[pos++] = SEPARATOR; + if (fullyQualifiedSuperTypeNamesList.length > 0) { + System.arraycopy(fullyQualifiedSuperTypeNamesList, 0, indexKey, pos, fullyQualifiedSuperTypeNamesList.length); + pos += fullyQualifiedSuperTypeNamesList.length; + } + + //add modifiers + indexKey[pos++] = SEPARATOR; + indexKey[pos++] = (char) modifiers; + indexKey[pos++] = (char) (modifiers>>16); + } + + return indexKey; + } + + public char[] getSearchPrefix() { + return fSearchPrefix; + } + +} diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/TypeReferenceLocator.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/TypeReferenceLocator.java index 234c3a8d..784338e4 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/TypeReferenceLocator.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/TypeReferenceLocator.java @@ -491,7 +491,7 @@ void matchReportReference(Expression expr, int lastIndex, TypeBinding refBinding locator.reportAccurateTypeReference(match, expr, this.pattern.simpleName); return; } - if (refBinding.isLocalType()) { + if (refBinding instanceof LocalTypeBinding) { // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=82673 LocalTypeBinding local = (LocalTypeBinding) refBinding; IJavaScriptElement focus = ((InternalSearchPattern)pattern).focus; diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/TypeSynonymsPattern.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/TypeSynonymsPattern.java new file mode 100644 index 00000000..f8312b3e --- /dev/null +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/TypeSynonymsPattern.java @@ -0,0 +1,180 @@ +/******************************************************************************* + * Copyright (c) 2012 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.wst.jsdt.internal.core.search.matching; + +import java.io.IOException; + +import org.eclipse.wst.jsdt.core.compiler.CharOperation; +import org.eclipse.wst.jsdt.core.search.SearchPattern; +import org.eclipse.wst.jsdt.internal.core.index.EntryResult; +import org.eclipse.wst.jsdt.internal.core.index.Index; + +/** + *

+ * Pattern used to represent the synoyms of a type. + *

+ */ +public class TypeSynonymsPattern extends JavaSearchPattern { + + /** + *

+ * Pattern prefix used when searching for type synonyms. + *

+ */ + private static final char[] SEARCH_PATTERN_PREFIX = new char[]{'*', '/'}; + + /** + *

+ * Pattern suffix used when searching for type synonyms. + *

+ */ + private static final char[] SEARCH_PATTERN_SUFFIX = new char[]{'/', '*'}; + + /** + *

+ * Categories useing this pattern. + *

+ */ + private static char[][] CATEGORIES = {TYPE_SYNONYMS}; + + /** + *

+ * Type name to search for synonyms for. + *

+ */ + private final char[] fSearchTypeName; + + /** + *

+ * All of the type names in this array are synonyms. + *

+ */ + private char[][] fSynonyms; + + /** + *

+ * Constructor used to search for synonyms of a type with the given name. + *

+ * + * @param searchTypeName + * create a pattern used to search for synonyms of a type with + * this name + */ + public TypeSynonymsPattern(char[] searchTypeName) { + super(TYPE_SYNONYMS_PATTERN, R_PATTERN_MATCH); + + this.fSearchTypeName = searchTypeName; + } + + /** + *

+ * Private internal constructor for creating a blank pattern to decode a + * result key into. + *

+ */ + private TypeSynonymsPattern() { + this(null); + } + + /** + * @see org.eclipse.wst.jsdt.core.search.SearchPattern#decodeIndexKey(char[]) + */ + public void decodeIndexKey(char[] key) { + //min length for proper key is greater then 2 (//) + if(key != null && key.length > 2) { + this.fSynonyms = CharOperation.splitOn('/', key, 1, key.length-1); + } + } + + /** + * @see org.eclipse.wst.jsdt.internal.core.search.matching.JavaSearchPattern#getBlankPattern() + */ + public SearchPattern getBlankPattern() { + return new TypeSynonymsPattern(); + } + + /** + * @see org.eclipse.wst.jsdt.core.search.SearchPattern#getIndexCategories() + */ + public char[][] getIndexCategories() { + return CATEGORIES; + } + + /** + * @return synonyms of the type name being searched for, including the given type name + */ + public char[][] getSynonyms() { + return this.fSynonyms; + } + + /** + * @see org.eclipse.wst.jsdt.internal.core.search.matching.InternalSearchPattern#queryIn(org.eclipse.wst.jsdt.internal.core.index.Index) + */ + EntryResult[] queryIn(Index index) throws IOException { + char[] key = CharOperation.concat(SEARCH_PATTERN_PREFIX, this.fSearchTypeName, SEARCH_PATTERN_SUFFIX); + + if(!this.isCaseSensitive) { + key = CharOperation.toLowerCase(key); + } + + return index.query(getIndexCategories(), key, this.getMatchRule()); + } + + /** + *

+ * Creates an index key for the given type and its synonyms. + *

+ * + *

+ * Key Syntax: + * /type/synonymType0/synonymType1/synonymType2/ + *

+ * + * @param type + * name of the type to create synonym index key for + * @param synonymTypes + * synonyms of the given type name to create index key for + * + * @return synonyms index key generated from the given type and synonyms + * list + */ + public static char[] createIndexKey(char[] type, char[][] synonymTypes) { + char[] key = null; + + if(type != null && type.length > 0 && synonymTypes != null && synonymTypes.length > 0) { + key = CharOperation.concat(type, CharOperation.concatWith(synonymTypes, '/', true), '/'); + key = CharOperation.concat('/', key, '/'); + } + + return key; + } + + /** + * @see org.eclipse.wst.jsdt.internal.core.search.matching.JavaSearchPattern#print(java.lang.StringBuffer) + */ + protected StringBuffer print(StringBuffer output) { + if(this.fSearchTypeName != null) { + output.append("SearchTypeName: "); //$NON-NLS-1$ + output.append(this.fSearchTypeName); + output.append("\n"); //$NON-NLS-1$ + } + + if(this.fSynonyms != null) { + output.append("Synonyms: "); //$NON-NLS-1$ + for(int i = 0; i < this.fSynonyms.length; ++i) { + output.append(this.fSynonyms[i]); + output.append(", "); //$NON-NLS-1$ + } + } + + return super.print(output); + } +} diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/VariableLocator.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/VariableLocator.java index 1e43899f..e834e6aa 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/VariableLocator.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/search/matching/VariableLocator.java @@ -58,7 +58,7 @@ protected int matchReference(Reference node, MatchingNodeSet nodeSet, boolean wr return nodeSet.addMatch(node, ((InternalSearchPattern)this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH); } else if (node instanceof SingleNameReference) { if (matchesName(this.pattern.name, ((SingleNameReference) node).token)) - return nodeSet.addMatch(node, POSSIBLE_MATCH); + return nodeSet.addMatch(node, ((InternalSearchPattern)this.pattern).mustResolve ? POSSIBLE_MATCH : ACCURATE_MATCH); } else { QualifiedNameReference qNameRef = (QualifiedNameReference) node; char[][] tokens = qNameRef.tokens; diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/ASTNodeFinder.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/ASTNodeFinder.java index 8120c9b1..27d639dc 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/ASTNodeFinder.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/ASTNodeFinder.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -96,7 +96,7 @@ public class ASTNodeFinder { int parameterCount = parameterTypeSignatures.length; nextMethod: for (int i = 0, length = methods.length; i < length; i++) { AbstractMethodDeclaration method = methods[i]; - if (CharOperation.equals(selector, method.selector)) { + if (CharOperation.equals(selector, method.getName())) { Argument[] args = method.arguments; int argsLength = args == null ? 0 : args.length; if (argsLength == parameterCount) { @@ -197,10 +197,10 @@ public class ASTNodeFinder { int count = 0; for (int i = 0; i < this.unit.numberInferredTypes; i++) { InferredType inferredType = this.unit.inferredTypes[i]; - if (!inferredType.isDefinition || inferredType.isEmptyGlobal()) + if (!inferredType.isDefinition()) continue; - if (!inferredType.isNamed()) { + if (inferredType.isAnonymous) { if (findAnonymous && ++count == occurenceCount) { return inferredType; } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/BindingKeyParser.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/BindingKeyParser.java index 3d86d251..a2549500 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/BindingKeyParser.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/BindingKeyParser.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2011 IBM Corporation and others. + * Copyright (c) 2005, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -61,8 +61,7 @@ public class BindingKeyParser { boolean isAtMemberTypeStart() { return this.index < this.source.length - && (this.source[this.index] == '$' - || (this.source[this.index] == '.' && this.source[this.index-1] == '>')); + && (this.source[this.index] == '.' && this.source[this.index-1] == '>'); } boolean isAtParametersEnd() { diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/BindingKeyResolver.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/BindingKeyResolver.java index fb2c5694..c1c64174 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/BindingKeyResolver.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/BindingKeyResolver.java @@ -118,7 +118,7 @@ public class BindingKeyResolver extends BindingKeyParser { public void consumeLocalVar(char[] varName) { if (this.scope == null) { - this.scope = this.methodBinding.sourceMethod().scope; + this.scope = this.methodBinding.sourceMethod().getScope(); } for (int i = 0; i < this.scope.localIndex; i++) { LocalVariableBinding local = this.scope.locals[i]; @@ -161,7 +161,7 @@ public class BindingKeyResolver extends BindingKeyParser { public void consumeScope(int scopeNumber) { if (this.scope == null) { - this.scope = this.methodBinding.sourceMethod().scope; + this.scope = this.methodBinding.sourceMethod().getScope(); } if (scopeNumber >= this.scope.subscopeCount) return; // malformed key diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/ConvertUtility.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/ConvertUtility.java index 12a55812..7635503c 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/ConvertUtility.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/ConvertUtility.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2010 IBM Corporation and others. + * Copyright (c) 2007, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -12,9 +12,10 @@ package org.eclipse.wst.jsdt.internal.core.util; import java.util.ArrayList; import java.util.Arrays; -import java.util.HashSet; +import java.util.Comparator; +import java.util.HashMap; import java.util.List; -import java.util.Set; +import java.util.Map; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProjectDescription; @@ -35,28 +36,19 @@ import org.eclipse.wst.jsdt.core.IIncludePathEntry; import org.eclipse.wst.jsdt.core.JavaScriptCore; import org.eclipse.wst.jsdt.core.LibrarySuperType; import org.eclipse.wst.jsdt.internal.core.JavaProject; +import org.eclipse.wst.jsdt.internal.core.search.indexing.IIndexConstants; public class ConvertUtility { private static final String NATURE_IDS[] = {JavaScriptCore.NATURE_ID}; private static final String SYSTEM_LIBRARY = org.eclipse.wst.jsdt.launching.JavaRuntime.JRE_CONTAINER; //$NON-NLS-1$ - private static final String SYSTEM_SUPER_TYPE_NAME = "Global"; //$NON-NLS-1$ + private static final String SYSTEM_SUPER_TYPE_NAME = new String(IIndexConstants.GLOBAL); private static final String BROWSER_LIBRARY = org.eclipse.wst.jsdt.launching.JavaRuntime.BASE_BROWSER_LIB; //$NON-NLS-1$ public static final IPath BROWSER_LIBRARY_PATH = new Path(BROWSER_LIBRARY); - private static final String BROWSER_SUPER_TYPE_NAME = "Window"; //$NON-NLS-1$ + private static final String BROWSER_SUPER_TYPE_NAME = new String(IIndexConstants.WINDOW); - /** - * @deprecated - moved into - * org.eclipse.wst.jsdt.web.core.internal.project. - * ModuleSourcePathProvider - */ public static final String VIRTUAL_CONTAINER = "org.eclipse.wst.jsdt.launching.WebProject"; //$NON-NLS-1$ - /** - * @deprecated - moved into - * org.eclipse.wst.jsdt.web.core.internal.project. - * ModuleSourcePathProvider - */ public static final IIncludePathEntry VIRTUAL_SCOPE_ENTRY = JavaScriptCore.newContainerEntry(new Path(VIRTUAL_CONTAINER), new IAccessRule[0], new IIncludePathAttribute[]{IIncludePathAttribute.HIDE}, false); @@ -150,6 +142,7 @@ public class ConvertUtility { fJavaProject.setProject(fCurrProject); IIncludePathEntry[] includePath = getRawClassPath(); + includePath = addEntry(includePath, VIRTUAL_SCOPE_ENTRY, false); includePath = addEntry(includePath, JavaScriptCore.newContainerEntry(BROWSER_LIBRARY_PATH), false); try { @@ -291,15 +284,42 @@ public class ConvertUtility { IIncludePathEntry[] defaults = new IIncludePathEntry[]{JavaScriptCore.newSourceEntry(p.getFullPath())}; try { IConfigurationElement[] configurationElements = Platform.getExtensionRegistry().getConfigurationElementsFor("org.eclipse.wst.jsdt.core.sourcePathProvider"); - Set paths = new HashSet(); + Map paths = new HashMap(); for (int i = 0; i < configurationElements.length; i++) { DefaultSourcePathProvider provider = (DefaultSourcePathProvider) configurationElements[i].createExecutableExtension("class"); if (provider != null) { - paths.addAll(Arrays.asList(provider.getDefaultSourcePaths(p))); + IIncludePathEntry[] defaultSourcePaths = provider.getDefaultSourcePaths(p); + for (int j = 0; j < defaultSourcePaths.length; j++) { + paths.put(defaultSourcePaths[j].getPath(), defaultSourcePaths[j]); + } } } if (!paths.isEmpty()) { - defaults = (IIncludePathEntry[]) paths.toArray(new IIncludePathEntry[paths.size()]); + IPath[] pathsArray = (IPath[]) paths.keySet().toArray(new IPath[paths.size()]); + // keep only the most specific paths + for (int i = 0; i < pathsArray.length; i++) { + for (int j = 0; j < pathsArray.length; j++) { + if (i != j && pathsArray[i] != null && pathsArray[j] != null && pathsArray[j].isPrefixOf(pathsArray[i])) { + // only remove if same kind of entry + if ((((IIncludePathEntry) paths.get(pathsArray[i]))).getEntryKind() == (((IIncludePathEntry) paths.get(pathsArray[j]))).getEntryKind()) { + paths.remove(pathsArray[j]); + pathsArray[j] = null; + } + } + } + } + defaults = (IIncludePathEntry[]) paths.values().toArray(new IIncludePathEntry[paths.size()]); + Arrays.sort(defaults, new Comparator() { + public int compare(Object o1, Object o2) { + IIncludePathEntry entry1 = (IIncludePathEntry) o1; + IIncludePathEntry entry2 = (IIncludePathEntry) o2; + if (entry1.getEntryKind() == IIncludePathEntry.CPE_SOURCE && entry2.getEntryKind() != IIncludePathEntry.CPE_SOURCE) + return -1; + if (entry1.getEntryKind() != IIncludePathEntry.CPE_SOURCE && entry2.getEntryKind() == IIncludePathEntry.CPE_SOURCE) + return 1; + return entry1.getPath().toString().compareTo(entry2.getPath().toString()); + } + }); } } catch (Exception e) { @@ -316,24 +336,24 @@ public class ConvertUtility { return proj.readRawIncludepath(); } -// private boolean hasAValidSourcePath() { -// if (hasProjectClassPathFile()) { -// try { -// IIncludePathEntry[] entries = getRawClassPath(); -// for (int i = 0; i < entries.length; i++) { -// if (entries[i].getEntryKind() == IIncludePathEntry.CPE_SOURCE) { -// return true; -// } -// } -// } -// catch (Exception e) { -// if (DEBUG) { -// System.out.println("Error checking sourcepath:" + e); //$NON-NLS-1$ -// } -// } -// } -// return false; -// } + private boolean hasAValidSourcePath() { + if (hasProjectClassPathFile()) { + try { + IIncludePathEntry[] entries = getRawClassPath(); + for (int i = 0; i < entries.length; i++) { + if (entries[i].getEntryKind() == IIncludePathEntry.CPE_SOURCE) { + return true; + } + } + } + catch (Exception e) { + if (DEBUG) { + System.out.println("Error checking sourcepath:" + e); //$NON-NLS-1$ + } + } + } + return false; + } private boolean hasProjectClassPathFile() { if (fCurrProject == null) { diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/DefaultSourcePathProvider.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/DefaultSourcePathProvider.java index 8386d2e0..a148ea62 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/DefaultSourcePathProvider.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/DefaultSourcePathProvider.java @@ -14,12 +14,6 @@ import org.eclipse.core.resources.IProject; import org.eclipse.wst.jsdt.core.IIncludePathEntry; import org.eclipse.wst.jsdt.core.JavaScriptCore; -/** - * A provider of defaul include path entries to be added when converting a - * project. Any extension returning any entrieswill supercede the values - * returned in this class. - * - */ public abstract class DefaultSourcePathProvider { public DefaultSourcePathProvider() { } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/HandleFactory.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/HandleFactory.java index ebf84356..cc1bb617 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/HandleFactory.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/HandleFactory.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -83,40 +83,40 @@ public class HandleFactory { */ public Openable createOpenable(String resourcePath, IJavaScriptSearchScope scope) { int separatorIndex; -// if ((separatorIndex= resourcePath.indexOf(IJavaScriptSearchScope.JAR_FILE_ENTRY_SEPARATOR)) > -1) { -// // path to a class file inside a jar -// // Optimization: cache package fragment root handle and package handles -// int rootPathLength; -// if (this.lastPkgFragmentRootPath == null -// || (rootPathLength = this.lastPkgFragmentRootPath.length()) != resourcePath.length() -// || !resourcePath.regionMatches(0, this.lastPkgFragmentRootPath, 0, rootPathLength)) { -// String jarPath= resourcePath.substring(0, separatorIndex); -// PackageFragmentRoot root= this.getJarPkgFragmentRoot(jarPath, scope); -// if (root == null) -// return null; // match is outside classpath -// this.lastPkgFragmentRootPath= jarPath; -// this.lastPkgFragmentRoot= root; -// this.packageHandles= new HashtableOfArrayToObject(5); -// } -// // create handle -// String classFilePath= resourcePath.substring(separatorIndex + 1); -// String[] simpleNames = new Path(classFilePath).segments(); -// String[] pkgName; -// int length = simpleNames.length-1; -// if (length > 0) { -// pkgName = new String[length]; -// System.arraycopy(simpleNames, 0, pkgName, 0, length); -// } else { -// pkgName = CharOperation.NO_STRINGS; -// } -// IPackageFragment pkgFragment= (IPackageFragment) this.packageHandles.get(pkgName); -// if (pkgFragment == null) { -// pkgFragment= ((PackageFragmentRoot) this.lastPkgFragmentRoot).getPackageFragment(pkgName); -// this.packageHandles.put(pkgName, pkgFragment); -// } -// IClassFile classFile= pkgFragment.getClassFile(simpleNames[length]); -// return (Openable) classFile; -// } else { + if ((separatorIndex= resourcePath.indexOf(IJavaScriptSearchScope.JAR_FILE_ENTRY_SEPARATOR)) > -1) { + // path to a class file inside a jar + // Optimization: cache package fragment root handle and package handles + int rootPathLength; + if (this.lastPkgFragmentRootPath == null + || (rootPathLength = this.lastPkgFragmentRootPath.length()) != resourcePath.length() + || !resourcePath.regionMatches(0, this.lastPkgFragmentRootPath, 0, rootPathLength)) { + String jarPath= resourcePath.substring(0, separatorIndex); + PackageFragmentRoot root= (PackageFragmentRoot) this.getJarPkgFragmentRoot(jarPath, scope); + if (root == null) + return null; // match is outside classpath + this.lastPkgFragmentRootPath= jarPath; + this.lastPkgFragmentRoot= root; + this.packageHandles= new HashtableOfArrayToObject(5); + } + // create handle + String classFilePath= resourcePath.substring(separatorIndex + 1); + String[] simpleNames = new Path(classFilePath).segments(); + String[] pkgName; + int length = simpleNames.length-1; + if (length > 0) { + pkgName = new String[length]; + System.arraycopy(simpleNames, 0, pkgName, 0, length); + } else { + pkgName = CharOperation.NO_STRINGS; + } + IPackageFragment pkgFragment= (IPackageFragment) this.packageHandles.get(pkgName); + if (pkgFragment == null) { + pkgFragment= ((PackageFragmentRoot) this.lastPkgFragmentRoot).getPackageFragment(pkgName); + this.packageHandles.put(pkgName, pkgFragment); + } + IClassFile classFile= pkgFragment.getClassFile(simpleNames[length]); + return (Openable) classFile; + } else { // path to a file in a directory // Optimization: cache package fragment root handle and package handles int rootPathLength = -1; @@ -167,7 +167,7 @@ public class HandleFactory { IClassFile classFile= pkgFragment.getClassFile(simpleName); return (Openable) classFile; } -// } + } } /** @@ -241,7 +241,7 @@ public class HandleFactory { } else { // method element AbstractMethodDeclaration method = methodScope.referenceMethod(); - newElement = parentType.getFunction(new String(method.getSafeName()), Util.typeParameterSignatures(method)); + newElement = parentType.getFunction(new String(method.getName()), Util.typeParameterSignatures(method)); if (newElement != null) { knownScopes.put(scope, newElement); } @@ -319,8 +319,8 @@ public class HandleFactory { for (int i= 0, projectCount= projects.length; i < projectCount; i++) { try { JavaProject javaProject= (JavaProject)projects[i]; - IIncludePathEntry classpathEnty = javaProject.getClasspathEntryFor(jarPath); - if (classpathEnty != null) { + IIncludePathEntry classpathEntry = javaProject.getClasspathEntryFor(jarPath); + if (classpathEntry != null) { if (target instanceof IFile) { // internal jar return javaProject.getPackageFragmentRoot((IFile)target); @@ -357,7 +357,7 @@ public class HandleFactory { { return root; } - if ( root.getLocation().isPrefixOf(path) + if (!root.isExternal() && root.getLocation().isPrefixOf(path) && !Util.isExcluded(path, root.fullInclusionPatternChars(), root.fullExclusionPatternChars(), false)) { this.lastIsFullPath=true; return root; diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/KeyToSignature.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/KeyToSignature.java index 488472f7..48d41512 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/KeyToSignature.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/KeyToSignature.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2009 IBM Corporation and others. + * Copyright (c) 2005, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -79,7 +79,7 @@ public class KeyToSignature extends BindingKeyParser { } public void consumeMemberType(char[] simpleTypeName) { - this.signature.append('$'); + this.signature.append('.'); this.signature.append(simpleTypeName); } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/Messages.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/Messages.java index a4f1888c..5039ca3c 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/Messages.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/Messages.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -217,6 +217,8 @@ public final class Messages extends NLS { public static String manager_indexingInProgress; public static String converter_ConfiguringForJavaScript; public static String converter_ConfiguringForBrowser; + + public static String PostponedRunnablesManager_job_title; static { NLS.initializeMessages(BUNDLE_NAME, Messages.class); diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/PublicScanner.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/PublicScanner.java index ce3e8acf..66fd6eb0 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/PublicScanner.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/PublicScanner.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/QualificationHelpers.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/QualificationHelpers.java new file mode 100644 index 00000000..1f14e4ed --- /dev/null +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/QualificationHelpers.java @@ -0,0 +1,236 @@ +/******************************************************************************* + * Copyright (c) 2011 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.wst.jsdt.internal.core.util; + +import org.eclipse.wst.jsdt.core.Signature; +import org.eclipse.wst.jsdt.core.compiler.CharOperation; +import org.eclipse.wst.jsdt.internal.core.search.indexing.IIndexConstants; + +/** + *

Methods for helping with qualified type names, both to separate them into + * qualifier and simple name, as well as recombining qualifier with simple name.

+ */ +public class QualificationHelpers { + + /** + *

The index in the array containing the qualifier of a fully qualified name + * separated by a method in this class.

+ * + * @see #seperateFullyQualifedName(char[]) + * @see #seperateFullyQualifedTypeNames(char[]) + */ + public static final int QULIFIERS_INDEX = 0; + + /** + *

The index in the array containing the simple name of a fully qualified name + * separated by a method in this class.

+ * + * @see #seperateFullyQualifedName(char[]) + * @see #seperateFullyQualifedTypeNames(char[]) + */ + public static final int SIMPLE_NAMES_INDEX = 1; + + /** + *

Given a qualification and a simple name creates a fully qualified name.

+ * + * @param qualification the qualification, or null if no qualification + * @param simpleName the simple name, can not be null + * + * @return fully qualified name created from the given simpleName and + * the optional qualification + */ + public static char[] createFullyQualifiedName(char[] qualification, char[] simpleName) { + char[] fullTypeName = null; + if(simpleName != null && simpleName.length > 0) { + if(qualification != null && qualification.length > 0) { + fullTypeName = CharOperation.concat(qualification, simpleName, IIndexConstants.DOT); + } else { + fullTypeName = simpleName; + } + } + + return fullTypeName; + } + + /** + *

Given a list of qualifications and a list of simple names creates a single list of + * fully qualified names created by matching one qualification and one simple name from + * their respective lists in order.

+ * + * @param qualifications to match with the given simpleNames, this can be + * null if there are not qualifications, or an array of the same size as + * simpleNames where any one of the indices maybe null to signify + * there is no qualifier for that specific simple name. + * @param simpleNames to match with the given qualifications, this array + * can not be null and no indices in the array can be null either + * + * @return an array of fully qualified names created from the given simpleNames + * and the optional qualifications + */ + public static char[][] createFullyQualifiedNames(char[][] qualifications, char[][] simpleNames) { + char[][] fullTypeNames = null; + + if(simpleNames != null) { + fullTypeNames = new char[simpleNames.length][]; + for(int i = 0; i < fullTypeNames.length; ++i) { + if(qualifications != null && qualifications.length > i) { + fullTypeNames[i] = createFullyQualifiedName(qualifications[i], simpleNames[i]); + } else { + fullTypeNames[i] = simpleNames[i]; + } + } + } + + return fullTypeNames; + } + + /** + *

Separates a fully qualified name into its qualifier and its simple name

+ * + * @param fullyQualifiedName fully qualified type name to separate into its qualifier and simple name + * + * @return a multidimensional array with one dimension for the qualifier and one for the simple name + * + * @see #QULIFIERS_INDEX + * @see #SIMPLE_NAMES_INDEX + */ + public static char[][] seperateFullyQualifedName(char[] fullyQualifiedName) { + char[][] seperatedTypeName = new char[2][]; + + if(fullyQualifiedName != null && fullyQualifiedName.length > 0) { + int lastIndexOfDot = CharOperation.lastIndexOf(IIndexConstants.DOT, fullyQualifiedName); + if(lastIndexOfDot != -1) { + seperatedTypeName[QULIFIERS_INDEX] = CharOperation.subarray(fullyQualifiedName, 0, lastIndexOfDot); + seperatedTypeName[SIMPLE_NAMES_INDEX] = CharOperation.subarray(fullyQualifiedName, lastIndexOfDot+1, -1); + } else { + seperatedTypeName[QULIFIERS_INDEX] = null; + seperatedTypeName[SIMPLE_NAMES_INDEX] = fullyQualifiedName; + } + } + + return seperatedTypeName; + } + + /** + *

Separates an array of fully qualified names into their qualifiers and their simple names

+ * + * @param fullyQualifiedNames fully qualified type names to separate into their qualifiers and their simple names + * @param minLength the minimum length of the result, padding will be with null + * + * @return resulting array consists of three indices. The first is either {@link #QULIFIERS_INDEX} or + * {@link #SIMPLE_NAMES_INDEX}, the second is then a list of either the qualifiers or the simple names, + * depending on the first index, the last index is the char[] "string" qualifier or simple name. + * + * @see #QULIFIERS_INDEX + * @see #SIMPLE_NAMES_INDEX + */ + public static char[][][] seperateFullyQualifiednames(String[] fullyQualifiedNames, int minLength) { + return seperateFullyQualifiedNames(stringArrayToCharArray(fullyQualifiedNames), minLength); + } + + /** + *

Separates a list of fully qualified names separated by {@link IIndexConstants#PARAMETER_SEPARATOR} + * into their qualifiers and their simple names

+ * + * @param fullyQualifiedNames a list of fully qualified type names separated by {@link IIndexConstants#PARAMETER_SEPARATOR} + * to separate into their qualifiers and their simple names + * @param minLength the minimum length of the result, padding will be with null + * + * @return resulting array consists of three indices. The first is either {@link #QULIFIERS_INDEX} or + * {@link #SIMPLE_NAMES_INDEX}, the second is then a list of either the qualifiers or the simple names, + * depending on the first index, the last index is the char[] "string" qualifier or simple name. + * + * @see #QULIFIERS_INDEX + * @see #SIMPLE_NAMES_INDEX + */ + public static char[][][] seperateFullyQualifiedNames(char[] fullyQualifiedNames, int minLength) { + char[][] names = CharOperation.splitOn(IIndexConstants.PARAMETER_SEPARATOR, fullyQualifiedNames); + return seperateFullyQualifiedNames(names, minLength); + } + + /** + *

Separates an array of fully qualified names into their qualifiers and their simple names

+ * + * @param fullyQualifiedNames fully qualified type names to separate into their qualifiers and their simple names + * @param minLength the minimum length of the result, padding will be with null + * + * @return resulting array consists of three indices. The first is either {@link #QULIFIERS_INDEX} or + * {@link #SIMPLE_NAMES_INDEX}, the second is then a list of either the qualifiers or the simple names, + * depending on the first index, the last index is the char[] "string" qualifier or simple name. + * + * @see #QULIFIERS_INDEX + * @see #SIMPLE_NAMES_INDEX + */ + public static char[][][] seperateFullyQualifiedNames(char[][] fullyQualifiedNames, int minLength) { + /* + * First index is 0 or 1 for the list of qualifiers qualifier and then the list of simple names respectively + * Second index is a list of the qualifiers and simple names + * Third index is the actual 'string' qualifier or simple name + */ + char[][][] seperatedTypeNames = new char[2][][]; + + if(fullyQualifiedNames.length > 0) { + int length = minLength > fullyQualifiedNames.length ? minLength : fullyQualifiedNames.length; + seperatedTypeNames[QULIFIERS_INDEX] = new char[length][]; + seperatedTypeNames[SIMPLE_NAMES_INDEX] = new char[length][]; + + for(int i = 0; i < fullyQualifiedNames.length; ++i) { + char[][] seperatedTypeName = seperateFullyQualifedName(fullyQualifiedNames[i]); + seperatedTypeNames[QULIFIERS_INDEX][i] = seperatedTypeName[QULIFIERS_INDEX]; + seperatedTypeNames[SIMPLE_NAMES_INDEX][i] = seperatedTypeName[SIMPLE_NAMES_INDEX]; + + //in case the qualifier is a signature, nothing happens if it is not + if(seperatedTypeNames[QULIFIERS_INDEX][i] != null && seperatedTypeNames[QULIFIERS_INDEX][i].length > 0) { + seperatedTypeNames[QULIFIERS_INDEX][i] = Signature.toCharArray(seperatedTypeNames[QULIFIERS_INDEX][i]); + } + + //in case the simple name is a signature, nothing happens if it is not + if(seperatedTypeNames[SIMPLE_NAMES_INDEX][i] != null && seperatedTypeNames[SIMPLE_NAMES_INDEX][i].length > 0) { + try { + seperatedTypeNames[SIMPLE_NAMES_INDEX][i] = Signature.toCharArray(seperatedTypeNames[SIMPLE_NAMES_INDEX][i]); + } catch(IllegalArgumentException e) { + /* ignore, this will happen if a name looking like it maybe a signature gets passed in, but isn't, such as "QName" + * the real future fix for this should be to completely stop using signatures + */ + } + } + } + + } else if (minLength > 0) { + seperatedTypeNames[QULIFIERS_INDEX] = new char[minLength][]; + seperatedTypeNames[SIMPLE_NAMES_INDEX] = new char[minLength][]; + } else { + seperatedTypeNames[QULIFIERS_INDEX] = null; + seperatedTypeNames[SIMPLE_NAMES_INDEX] = null; + } + + return seperatedTypeNames; + } + + /** + *

Transform a {@link String} array into a char array.

+ * + * @param array of {@link String}s to transform into an array of chars + * + * @return array of {@link String}s built from the given array of chars + */ + public static char[][] stringArrayToCharArray(String[] array) { + char[][] results = null; + if(array != null) { + results = new char[array.length][]; + for(int i = 0; i < array.length; ++i) { + results[i] = array[i].toCharArray(); + } + } + + return results; + } +} diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/ReferenceInfoAdapter.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/ReferenceInfoAdapter.java index e30e2c26..9bce4b7d 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/ReferenceInfoAdapter.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/ReferenceInfoAdapter.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -30,7 +30,7 @@ public void acceptFieldReference(char[] fieldName, int sourcePosition) { /** * Does nothing. */ -public void acceptMethodReference(char[] methodName, int argCount, int sourcePosition) { +public void acceptMethodReference(char[] methodName, int sourcePosition) { // Does nothing } /** diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/ResourceCompilationUnit.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/ResourceCompilationUnit.java index b3901af7..e5e7db1f 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/ResourceCompilationUnit.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/ResourceCompilationUnit.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/Util.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/Util.java index 4def4c9f..b087aa4c 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/Util.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/Util.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -2642,21 +2642,12 @@ public class Util { // all done return p; case Signature.C_DOT : + case Signature.C_DOLLAR : buffer.append('.'); break; case '/' : buffer.append('/'); break; - case Signature.C_DOLLAR : - // once we hit "$" there are no more package prefixes - /** - * Convert '$' in resolved type signatures into '.'. - * NOTE: This assumes that the type signature is an inner type - * signature. This is true in most cases, but someone can define a - * non-inner type name containing a '$'. - */ - buffer.append('.'); - break; default : buffer.append(c); } @@ -2669,7 +2660,7 @@ public class Util { * * marker and label */ - public static final String ANONYMOUS_MARKER = new String( CharOperation.concat(IInferEngine.ANONYMOUS_PREFIX, IInferEngine.ANONYMOUS_CLASS_ID) ); + public static final String ANONYMOUS_MARKER = new String(IInferEngine.ANONYMOUS_PREFIX); public static final String ANONYMOUS_LABEL = "{}"; //$NON-NLS-1$ /* diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/messages.properties b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/messages.properties index 2ae5c4ac..6925377a 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/messages.properties +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/util/messages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2010 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR ### JavaModel messages. @@ -91,9 +93,9 @@ build_serializationError = Validator serialization error #build_duplicateResource = The resource is a duplicate of {0} and was not copied to the output folder #build_inconsistentClassFile = A class file was not written. The project may be inconsistent, if so try refreshing this project and validating it build_inconsistentProject = The project was not validated due to "{0}". Fix the problem, then try refreshing this project and validating it since it may be inconsistent -build_incompleteClassPath = The project was not validated since its include path is incomplete. Cannot find the class definition for {0}. Fix the include path then try validating this project +build_incompleteClassPath = The project was not validated since its include path is incomplete. Cannot find the type definition for {0}. Fix the include path then try validating this project build_missingSourceFile = The project was not validated since the source file {0} could not be read -build_prereqProjectHasClasspathProblems = The project was not validated since it depends on {0}, which has inlude path errors +build_prereqProjectHasClasspathProblems = The project was not validated since it depends on {0}, which has include path errors build_prereqProjectMustBeRebuilt = The project cannot be validated until its prerequisite {0} is built. Cleaning and validating all projects is recommended build_abortDueToClasspathProblems = The project cannot be validated until include path errors are resolved @@ -128,13 +130,13 @@ classpath_buildPath = Include path classpath_cannotNestEntryInEntry = Cannot nest ''{0}'' inside ''{1}''. To enable the nesting exclude ''{2}'' from ''{1}'' classpath_cannotNestEntryInEntryNoExclusion= Cannot nest ''{0}'' inside ''{1}''. To allow the nesting enable use of exclusion patterns in the preferences of project ''{1}'' and exclude ''{2}'' from ''{1}'' classpath_cannotNestEntryInLibrary = Cannot nest ''{0}'' inside library ''{1}'' -classpath_cannotReadClasspathFile = Unable to read ''.jsdtscope'' file of project {0} +classpath_cannotReadClasspathFile = Unable to read ''.settings/.jsdtscope'' file of project {0} classpath_cannotReferToItself = Project cannot reference itself: {0} classpath_closedProject = Required project: {0} needs to be open classpath_cycle = A cycle was detected in the include path of project: {0} classpath_duplicateEntryPath = Include path contains duplicate entry: ''{0}'' for project {1} classpath_illegalContainerPath = Illegal include path container path: ''{0}'' in project {1}, must have at least one segment (containerID+hints) -classpath_illegalEntryInClasspathFile = Illegal entry in ''.jsdtscope'' of project {0} file: {1} +classpath_illegalEntryInClasspathFile = Illegal entry in ''.settings/.jsdtscope'' of project {0} file: {1} classpath_illegalLibraryPath = Illegal path for required library: ''{0}'' in project {1} classpath_illegalLibraryArchive = Illegal type of archive for required library: ''{0}'' in project {1} classpath_illegalExternalFolder = Required library cannot denote external folder: ''{0}'' for project {1} @@ -150,7 +152,7 @@ classpath_unboundSourceAttachment = Invalid source attachment: ''{0}'' for requi classpath_unboundSourceFolder = Project ''{1}'' is missing required source folder: ''{0}'' classpath_unboundVariablePath = Unbound include path variable: ''{0}'' in project ''{1}'' classpath_unknownKind = Unknown kind: ''{0}'' -classpath_xmlFormatError = XML format error in ''.jsdtscope'' file of project {0}: {1} +classpath_xmlFormatError = XML format error in ''.settings/.jsdtscope'' file of project {0}: {1} classpath_disabledInclusionExclusionPatterns = Inclusion or exclusion patterns are disabled in project {1}, cannot selectively include or exclude from entry: ''{0}'' classpath_duplicateEntryExtraAttribute = Duplicate extra attribute: ''{0}'' in include path entry ''{1}'' for project ''{2}'' classpath_deprecated_variable = Include path variable ''{0}'' in project ''{1}'' is deprecated: {2} @@ -165,12 +167,12 @@ savedState_jobName = Processing JavaScript changes since last activation ## java model initialization javamodel_initialization = Initializing JavaScript tooling -javamodel_configuring_searchengine=Configuring search engine -javamodel_configuring_classpath_containers=Configuring includepath containers +javamodel_configuring_searchengine=Configuring JavaScript search engine +javamodel_configuring_classpath_containers=Configuring include path containers javamodel_getting_build_state_number=Getting validation state version number javamodel_configuring=Configuring {0} javamodel_building_after_upgrade=Triggering validation after upgrade -javamodel_refreshing_external_jars=Refreshing external libraries +javamodel_refreshing_external_jars=Refreshing external JavaScript libraries ### access restrictions restrictedAccess_project = The type {0} is not accessible due to restriction on required project {1} @@ -244,4 +246,7 @@ manager_indexingInProgress = JavaScript indexing in progress ### Project conversion converter_ConfiguringForJavaScript=Configuring for JavaScript -converter_ConfiguringForBrowser=Configuring for Browser \ No newline at end of file +converter_ConfiguringForBrowser=Configuring for Browser + +### Postponed runnables manager +PostponedRunnablesManager_job_title=JavaScript Postponed Runnables Processing Job \ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/CodeFormatterVisitor.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/CodeFormatterVisitor.java index 0c431e20..ff1d8d20 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/CodeFormatterVisitor.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/CodeFormatterVisitor.java @@ -1487,7 +1487,7 @@ public class CodeFormatterVisitor extends ASTVisitor { if (i > 0 && spaceAfterComma) { this.scribe.space(); } - arguments[i].traverse(this, methodDeclaration.scope); + arguments[i].traverse(this, methodDeclaration.getScope()); } ok = true; } catch (AlignmentException e) { @@ -2988,7 +2988,7 @@ public class CodeFormatterVisitor extends ASTVisitor { if (this.preferences.indent_statements_compare_to_body) { this.scribe.indent(); } - constructorDeclaration.constructorCall.traverse(this, constructorDeclaration.scope); + constructorDeclaration.constructorCall.traverse(this, constructorDeclaration.getScope()); if (this.preferences.indent_statements_compare_to_body) { this.scribe.unIndent(); } @@ -2999,7 +2999,7 @@ public class CodeFormatterVisitor extends ASTVisitor { if (this.preferences.indent_statements_compare_to_body) { this.scribe.indent(); } - formatStatements(constructorDeclaration.scope, statements, true); + formatStatements(constructorDeclaration.getScope(), statements, true); this.scribe.printComment(); if (this.preferences.indent_statements_compare_to_body) { this.scribe.unIndent(); @@ -3825,7 +3825,7 @@ public class CodeFormatterVisitor extends ASTVisitor { */ this.scribe.printNextToken(TerminalTokens.TokenNamefunction); - if (methodDeclaration.selector!=null) + if (methodDeclaration.getName()!=null) this.scribe.printNextToken(TerminalTokens.TokenNameIdentifier, true); formatMethodArguments( @@ -3849,7 +3849,7 @@ public class CodeFormatterVisitor extends ASTVisitor { } } - final MethodScope methodDeclarationScope = methodDeclaration.scope; + final MethodScope methodDeclarationScope = methodDeclaration.getScope(); if (!methodDeclaration.isAbstract() && ((methodDeclaration.modifiers & ExtraCompilerModifiers.AccSemicolonBody) == 0)) { /* diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/DefaultCodeFormatter.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/DefaultCodeFormatter.java index 4183b493..f8993ec1 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/DefaultCodeFormatter.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/DefaultCodeFormatter.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -145,7 +145,7 @@ public class DefaultCodeFormatter extends CodeFormatter { String lineSeparator) { if (offset < 0 || length < 0 || length > source.length()) { - throw new IllegalArgumentException(); + throw new IllegalArgumentException(""+offset+":"+length); //$NON-NLS-1$//$NON-NLS-2$ } this.codeSnippetParsingUtil = new CodeSnippetParsingUtil(); switch(kind) { diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/options.properties b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/options.properties index 476842b1..d4e47a4f 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/options.properties +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/formatter/options.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2007 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,9 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_NONE + newline.openingBrace.number=1 newline.openingBrace.category=Newline newline.openingBrace.name=I&nsert new line before opening brace diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Alias.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Alias.java index e7d0dbb1..cb790da9 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Alias.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Alias.java @@ -1,3 +1,13 @@ +/******************************************************************************* + * Copyright (c) 2011 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ package org.eclipse.wst.jsdt.internal.oaametadata; public class Alias { diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Author.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Author.java index c1e13cba..a0f006e6 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Author.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Author.java @@ -1,3 +1,13 @@ +/******************************************************************************* + * Copyright (c) 2011 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ package org.eclipse.wst.jsdt.internal.oaametadata; public class Author { diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/DepreciatedOrAvailable.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/DepreciatedOrAvailable.java index 3d1d04d0..9bc1cc37 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/DepreciatedOrAvailable.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/DepreciatedOrAvailable.java @@ -1,3 +1,13 @@ +/******************************************************************************* + * Copyright (c) 2011 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ package org.eclipse.wst.jsdt.internal.oaametadata; public class DepreciatedOrAvailable { diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Enum.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Enum.java index b5567900..f3098bb1 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Enum.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/Enum.java @@ -1,3 +1,13 @@ +/******************************************************************************* + * Copyright (c) 2011 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ package org.eclipse.wst.jsdt.internal.oaametadata; public class Enum { diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/MetadataReader.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/MetadataReader.java index 4deda6d5..57533540 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/MetadataReader.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/oaametadata/MetadataReader.java @@ -723,7 +723,7 @@ public class MetadataReader extends DefaultHandler implements IOAAMetaDataConsta private ArrayList getCollection(String tagClass) { ArrayList list = null; - if(this.collections != null) { + if (this.collections != null) { list = (ArrayList)this.collections.get(tagClass); } if (list==null) diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/AbstractVMInstallType.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/AbstractVMInstallType.java index 85ced738..23e3344b 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/AbstractVMInstallType.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/AbstractVMInstallType.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/ExecutionArguments.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/ExecutionArguments.java index 7f357605..d839bc59 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/ExecutionArguments.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/ExecutionArguments.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IRuntimeClasspathEntry2.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IRuntimeClasspathEntry2.java index 98ea0191..9d6e6943 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IRuntimeClasspathEntry2.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IRuntimeClasspathEntry2.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IRuntimeClasspathProvider.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IRuntimeClasspathProvider.java index 635486cb..c47938ce 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IRuntimeClasspathProvider.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IRuntimeClasspathProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IVMInstall.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IVMInstall.java index f4841be5..360fdd44 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IVMInstall.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IVMInstall.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IVMInstall2.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IVMInstall2.java index 9c3cbe2a..144787ae 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IVMInstall2.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IVMInstall2.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IVMInstall3.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IVMInstall3.java index a2666403..66328a0d 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IVMInstall3.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IVMInstall3.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2007 IBM Corporation and others. + * Copyright (c) 2006, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IVMInstallType.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IVMInstallType.java index fa35c390..e6345dd9 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IVMInstallType.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IVMInstallType.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IVMRunner.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IVMRunner.java index a085cf84..e1911d18 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IVMRunner.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/IVMRunner.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/JREContainer.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/JREContainer.java index 473208ed..d52a8aeb 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/JREContainer.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/JREContainer.java @@ -138,14 +138,6 @@ public class JREContainer implements IJsGlobalScopeContainer { fVMInstall = vm; fPath = path; } - - /** - * @see IJsGlobalScopeContainer#getClasspathEntries() - * @deprecated Use {@link #getIncludepathEntries()} instead - */ - public IIncludePathEntry[] getClasspathEntries() { - return getIncludepathEntries(); - } /** * @see IJsGlobalScopeContainer#getIncludepathEntries() diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/JREContainerInitializer.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/JREContainerInitializer.java index ea96dd07..2b5c7045 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/JREContainerInitializer.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/JREContainerInitializer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -31,6 +31,8 @@ import org.eclipse.wst.jsdt.core.infer.DefaultInferrenceProvider; */ public class JREContainerInitializer extends JsGlobalScopeContainerInitializer { + public static final String JsECMA_NAME = LaunchingMessages.JREContainerInitializer_JsECMA_NAME; + /** * @see JsGlobalScopeContainerInitializer#initialize(IPath, IJavaScriptProject) */ diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/JavaRuntime.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/JavaRuntime.java index 1ccab7b9..5b4348aa 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/JavaRuntime.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/JavaRuntime.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -27,10 +27,10 @@ import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Preferences; import org.eclipse.core.runtime.Status; import org.eclipse.debug.core.ILaunchConfiguration; -import org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer; import org.eclipse.wst.jsdt.core.IIncludePathEntry; import org.eclipse.wst.jsdt.core.IJavaScriptModel; import org.eclipse.wst.jsdt.core.IJavaScriptProject; +import org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer; import org.eclipse.wst.jsdt.core.JavaScriptCore; import org.eclipse.wst.jsdt.core.compiler.libraries.SystemLibraryLocation; @@ -138,7 +138,7 @@ public final class JavaRuntime { /* * Default supertype for javascript unit s */ - public static final String DEFAULT_SUPER_TYPE ="Global"; //$NON-NLS-1$ + public static final String DEFAULT_SUPER_TYPE = "Global"; //$NON-NLS-1$ public static final String DEFAULT_SUPER_TYPE_LIBRARY = JRE_CONTAINER; //$NON-NLS-1$ /** diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/LaunchingMessages.properties b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/LaunchingMessages.properties index 58f3186f..816c3d93 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/LaunchingMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/LaunchingMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2009 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR JavaRuntime_Specified_VM_install_type_does_not_exist___0__2=Specified VM install type does not exist: {0} JavaRuntime_VM_not_fully_specified_in_launch_configuration__0____missing_VM_name__Reverting_to_default_VM__1=VM not fully specified in launch configuration {0} - missing VM name. Reverting to default VM. diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/LibraryLocation.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/LibraryLocation.java index c201be2d..7da6bc6d 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/LibraryLocation.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/LibraryLocation.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/StandardVMType.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/StandardVMType.java index 805f6d3b..4eb12f6c 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/StandardVMType.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/StandardVMType.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/VMRunnerConfiguration.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/VMRunnerConfiguration.java index c3330e07..413d5c76 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/VMRunnerConfiguration.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/VMRunnerConfiguration.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/VMStandin.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/VMStandin.java index e3ca7084..efacf839 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/VMStandin.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/launching/VMStandin.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/libraries/BasicBrowserLibraryJsGlobalScopeContainerInitializer.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/libraries/BasicBrowserLibraryJsGlobalScopeContainerInitializer.java index c6278706..68f1f2fa 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/libraries/BasicBrowserLibraryJsGlobalScopeContainerInitializer.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/libraries/BasicBrowserLibraryJsGlobalScopeContainerInitializer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2010 IBM Corporation and others. + * Copyright (c) 2005, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -12,6 +12,10 @@ package org.eclipse.wst.jsdt.libraries; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.Path; +import org.eclipse.wst.jsdt.core.IAccessRule; +import org.eclipse.wst.jsdt.core.IIncludePathAttribute; +import org.eclipse.wst.jsdt.core.IIncludePathEntry; import org.eclipse.wst.jsdt.core.IJavaScriptProject; import org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer; import org.eclipse.wst.jsdt.core.JavaScriptCore; @@ -30,16 +34,18 @@ import org.eclipse.wst.jsdt.core.infer.DefaultInferrenceProvider; public class BasicBrowserLibraryJsGlobalScopeContainerInitializer extends JsGlobalScopeContainerInitializer implements IJsGlobalScopeContainer { private static final String CONTAINER_ID = org.eclipse.wst.jsdt.launching.JavaRuntime.BASE_BROWSER_LIB; //$NON-NLS-1$ private static final String BROWSER_SUPER_TYPE_NAME = "Window"; //$NON-NLS-1$ - - /** - * Union of all filenames composing web browser libraries - */ + + private static final String ContainerDescription = Messages.BasicBrowserLibraryJsGlobalScopeContainerInitializer_ECMA3Browser; + private static final String FILE_DESCRIPTION0 = Messages.BasicBrowserLibraryJsGlobalScopeContainerInitializer_ECMA3DOM; + private static final String FILE_DESCRIPTION1 = Messages.BasicBrowserLibraryJsGlobalScopeContainerInitializer_CommonWebBrowser; + private static final String LibraryDescription = Messages.BasicBrowserLibraryJsGlobalScopeContainerInitializer_ECMA3BrowserLibrary; + private static final char[][] LIBRARY_FILE_NAME = { - { 'b', 'a', 's', 'e', 'B', 'r', 'o', 'w', 's', 'e', 'r', 'L', 'i', 'b', 'r', 'a', 'r', 'y', '.', 'j', 's' }, - {'b','r','o','w','s','e','r','W','i','n','d','o','w','.','j','s'}, - {'x','h','r','.','j','s'}, - "dom5.js".toCharArray() - }; + { 'b', 'a', 's', 'e', 'B', 'r', 'o', 'w', 's', 'e', 'r', 'L', 'i', 'b', 'r', 'a', 'r', 'y', '.', 'j', 's' }, + {'b','r','o','w','s','e','r','W','i','n','d','o','w','.','j','s'}, + {'x','h','r','.','j','s'}, + {'d','o','m','5','.','j','s'} + }; /** * Filenames composing our HTML4.01 web browser library @@ -83,6 +89,17 @@ public class BasicBrowserLibraryJsGlobalScopeContainerInitializer extends JsGlob public LibraryLocation getLibraryLocation() { return BasicLibLocation.getInstance(); } + + public IIncludePathEntry[] getIncludepathEntries() { + LibraryLocation libLocation = getLibraryLocation(); + char[][] filesInLibs = libLocation.getLibraryFileNames(); + IIncludePathEntry[] entries = new IIncludePathEntry[filesInLibs.length]; + for (int i = 0; i < entries.length; i++) { + IPath workingLibPath = new Path(libLocation.getLibraryPath(filesInLibs[i])); + entries[i] = JavaScriptCore.newLibraryEntry(workingLibPath.makeAbsolute(), null, null, new IAccessRule[0], new IIncludePathAttribute[0], true); + } + return entries; + } /* (non-Javadoc) * @see org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer#canUpdateJsGlobalScopeContainer(org.eclipse.core.runtime.IPath, org.eclipse.wst.jsdt.core.IJavaScriptProject) @@ -92,7 +109,11 @@ public class BasicBrowserLibraryJsGlobalScopeContainerInitializer extends JsGlob } protected IJsGlobalScopeContainer getContainer(IPath containerPath, IJavaScriptProject project) { - return new BasicBrowserLibraryContainer(containerPath); + return this; + } + + public String getDescription() { + return BasicBrowserLibraryJsGlobalScopeContainerInitializer.LibraryDescription; } public String getDescription(IPath containerPath, IJavaScriptProject project) { @@ -102,6 +123,14 @@ public class BasicBrowserLibraryJsGlobalScopeContainerInitializer extends JsGlob return containerPath.lastSegment(); } + public int getKind() { + return IJsGlobalScopeContainer.K_SYSTEM; + } + + public IPath getPath() { + return new Path(BasicBrowserLibraryJsGlobalScopeContainerInitializer.CONTAINER_ID); + } + public void initialize(IPath containerPath, IJavaScriptProject project) throws CoreException { JavaScriptCore.setJsGlobalScopeContainer(containerPath, new IJavaScriptProject[] { project }, new IJsGlobalScopeContainer[] { getContainer(containerPath, project) }, null); } diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/libraries/BasicLibraryContainer.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/libraries/BasicLibraryContainer.java new file mode 100644 index 00000000..f3120fcf --- /dev/null +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/libraries/BasicLibraryContainer.java @@ -0,0 +1,22 @@ +/******************************************************************************* + * Copyright (c) 2005, 2010 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.wst.jsdt.libraries; + +/** + * + * Provisional API: This class/interface is part of an interim API that is still under development and expected to + * change significantly before reaching stability. It is being made available at this early stage to solicit feedback + * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken + * (repeatedly) as the API evolves. + * + * @deprecated + */ +public class BasicLibraryContainer {} diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/libraries/Messages.java b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/libraries/Messages.java index 22efe73d..2d79da47 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/libraries/Messages.java +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/libraries/Messages.java @@ -20,6 +20,10 @@ public class Messages extends NLS { public static String BasicBrowserLibraryJsGlobalScopeContainerInitializer_ECMA3Browser; public static String BasicBrowserLibraryJsGlobalScopeContainerInitializer_HTML5Browser; + public static String BasicBrowserLibraryJsGlobalScopeContainerInitializer_ECMA3BrowserLibrary; + + public static String BasicBrowserLibraryJsGlobalScopeContainerInitializer_ECMA3DOM; + static { // initialize resource bundle NLS.initializeMessages(BUNDLE_NAME, Messages.class); diff --git a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/libraries/messages.properties b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/libraries/messages.properties index 553a92ad..65653df4 100644 --- a/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/libraries/messages.properties +++ b/bundles/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/libraries/messages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2005, 2010 IBM Corporation and others. +# Copyright (c) 2005, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,11 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_NONE + BasicBrowserLibraryJsGlobalScopeContainerInitializer_ECMA3Browser=ECMA 3 Browser Support BasicBrowserLibraryJsGlobalScopeContainerInitializer_HTML5Browser=Browser Support +BasicBrowserLibraryJsGlobalScopeContainerInitializer_ECMA3DOM=ECMA 3 DOM BasicBrowserLibraryJsGlobalScopeContainerInitializer_CommonWebBrowser=Common Web Browser +BasicBrowserLibraryJsGlobalScopeContainerInitializer_ECMA3BrowserLibrary=ECMA 3 Browser Support Library diff --git a/bundles/org.eclipse.wst.jsdt.manipulation/.project b/bundles/org.eclipse.wst.jsdt.manipulation/.project index d280b679..12f6cab0 100644 --- a/bundles/org.eclipse.wst.jsdt.manipulation/.project +++ b/bundles/org.eclipse.wst.jsdt.manipulation/.project @@ -1,28 +1,34 @@ - - - org.eclipse.wst.jsdt.manipulation - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder - - - - - - org.eclipse.pde.PluginNature - org.eclipse.jdt.core.javanature - - + + + org.eclipse.wst.jsdt.manipulation + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + org.eclipse.pde.api.tools.apiAnalysisBuilder + + + + + + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + org.eclipse.pde.api.tools.apiAnalysisNature + + diff --git a/bundles/org.eclipse.wst.jsdt.manipulation/plugin.properties b/bundles/org.eclipse.wst.jsdt.manipulation/plugin.properties index 171e2394..daaa3e45 100644 --- a/bundles/org.eclipse.wst.jsdt.manipulation/plugin.properties +++ b/bundles/org.eclipse.wst.jsdt.manipulation/plugin.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2010 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_NONE pluginName= JavaScript Code Manipulation Functionality providerName= Eclipse Web Tools Platform diff --git a/bundles/org.eclipse.wst.jsdt.manipulation/src/org/eclipse/wst/jsdt/internal/core/manipulation/JavaManipulationMessages.properties b/bundles/org.eclipse.wst.jsdt.manipulation/src/org/eclipse/wst/jsdt/internal/core/manipulation/JavaManipulationMessages.properties index 04d8614e..72d537a9 100644 --- a/bundles/org.eclipse.wst.jsdt.manipulation/src/org/eclipse/wst/jsdt/internal/core/manipulation/JavaManipulationMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.manipulation/src/org/eclipse/wst/jsdt/internal/core/manipulation/JavaManipulationMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2007 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,4 +8,7 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_NONE + JavaManipulationMessages_internalError=Internal Error diff --git a/bundles/org.eclipse.wst.jsdt.manipulation/src/org/eclipse/wst/jsdt/internal/core/refactoring/descriptors/DescriptorMessages.properties b/bundles/org.eclipse.wst.jsdt.manipulation/src/org/eclipse/wst/jsdt/internal/core/refactoring/descriptors/DescriptorMessages.properties index 7fa60a91..47701cf3 100644 --- a/bundles/org.eclipse.wst.jsdt.manipulation/src/org/eclipse/wst/jsdt/internal/core/refactoring/descriptors/DescriptorMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.manipulation/src/org/eclipse/wst/jsdt/internal/core/refactoring/descriptors/DescriptorMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2007 IBM Corporation and others. +# Copyright (c) 2007, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,9 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR + JavaRefactoringDescriptor_not_available=N/A JavaRefactoringDescriptor_no_description=Description has not been set. JavaRefactoringDescriptor_no_resulting_descriptor=Refactoring contribution registered for id ''{0}'' returned null as result of createDescriptor(String, String, String, String, Map, int) diff --git a/bundles/org.eclipse.wst.jsdt.support.firefox/.project b/bundles/org.eclipse.wst.jsdt.support.firefox/.project index 5be883c1..7c24828e 100644 --- a/bundles/org.eclipse.wst.jsdt.support.firefox/.project +++ b/bundles/org.eclipse.wst.jsdt.support.firefox/.project @@ -1,34 +1,40 @@ - - - org.eclipse.wst.jsdt.support.firefox - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder - - - - - org.eclipse.wst.jsdt.core.javascriptValidator - - - - - - org.eclipse.pde.PluginNature - org.eclipse.jdt.core.javanature - org.eclipse.wst.jsdt.core.jsNature - - + + + org.eclipse.wst.jsdt.support.firefox + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + org.eclipse.wst.jsdt.core.javascriptValidator + + + + + org.eclipse.pde.api.tools.apiAnalysisBuilder + + + + + + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + org.eclipse.wst.jsdt.core.jsNature + org.eclipse.pde.api.tools.apiAnalysisNature + + diff --git a/bundles/org.eclipse.wst.jsdt.support.firefox/META-INF/MANIFEST.MF b/bundles/org.eclipse.wst.jsdt.support.firefox/META-INF/MANIFEST.MF index 49fd0421..12ef00e2 100644 --- a/bundles/org.eclipse.wst.jsdt.support.firefox/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.wst.jsdt.support.firefox/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: %Bundle-Name Bundle-SymbolicName: org.eclipse.wst.jsdt.support.firefox;singleton:=true -Bundle-Version: 1.0.402.qualifier +Bundle-Version: 1.0.500.qualifier Require-Bundle: org.eclipse.wst.jsdt.core;bundle-version="[1.1.0,2.0.0)", org.eclipse.wst.jsdt.ui;bundle-version="[1.1.0,2.0.0)", org.eclipse.core.runtime;bundle-version="[3.5.0,4.0.0)", @@ -10,6 +10,6 @@ Require-Bundle: org.eclipse.wst.jsdt.core;bundle-version="[1.1.0,2.0.0)", org.eclipse.ui;bundle-version="[3.5.0,4.0.0)", org.eclipse.core.resources;bundle-version="[3.5.0,4.0.0)" Bundle-RequiredExecutionEnvironment: J2SE-1.4 -Bundle-Vendor: %providerName +Bundle-Vendor: %Bundle-Vendor Bundle-Localization: plugin Bundle-ActivationPolicy: lazy diff --git a/bundles/org.eclipse.wst.jsdt.support.firefox/plugin.properties b/bundles/org.eclipse.wst.jsdt.support.firefox/plugin.properties index ed33ffe9..099acc4f 100644 --- a/bundles/org.eclipse.wst.jsdt.support.firefox/plugin.properties +++ b/bundles/org.eclipse.wst.jsdt.support.firefox/plugin.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2005, 2010 IBM Corporation and others. +# Copyright (c) 2005, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,7 +8,10 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_NONE + #Properties file for org.eclipse.wst.jsdt.support.firefox -providerName = Eclipse Web Tools Platform +Bundle-Vendor = Eclipse Web Tools Platform Bundle-Name = JSDT support for Mozilla FireFox -JsGlobalScopeContainerPage.name.0 = Mozilla FireFox Library \ No newline at end of file +JsGlobalScopeContainerPage.name.0 = Mozilla FireFox Library diff --git a/bundles/org.eclipse.wst.jsdt.support.firefox/src/org/eclipse/wst/jsdt/internal/ui/wizards/FirefoxMessages.java b/bundles/org.eclipse.wst.jsdt.support.firefox/src/org/eclipse/wst/jsdt/internal/ui/wizards/FirefoxMessages.java index 36d07889..d63fa04f 100644 --- a/bundles/org.eclipse.wst.jsdt.support.firefox/src/org/eclipse/wst/jsdt/internal/ui/wizards/FirefoxMessages.java +++ b/bundles/org.eclipse.wst.jsdt.support.firefox/src/org/eclipse/wst/jsdt/internal/ui/wizards/FirefoxMessages.java @@ -1,3 +1,13 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ package org.eclipse.wst.jsdt.internal.ui.wizards; import org.eclipse.osgi.util.NLS; diff --git a/bundles/org.eclipse.wst.jsdt.support.firefox/src/org/eclipse/wst/jsdt/internal/ui/wizards/FirefoxMessages.properties b/bundles/org.eclipse.wst.jsdt.support.firefox/src/org/eclipse/wst/jsdt/internal/ui/wizards/FirefoxMessages.properties index 27dc5b5c..0b83053a 100644 --- a/bundles/org.eclipse.wst.jsdt.support.firefox/src/org/eclipse/wst/jsdt/internal/ui/wizards/FirefoxMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.support.firefox/src/org/eclipse/wst/jsdt/internal/ui/wizards/FirefoxMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2009 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_NONE FirefoxLibraryWizardPage_title=Mozilla FireFox Library FirefoxLibraryWizardPage_FirefoxLibraryAdded=FireFox Browser (2.0.0.3) Library added to Project.\n\n - This library supports JavaScript elements provided by the FireFox web browser. diff --git a/bundles/org.eclipse.wst.jsdt.support.ie/.project b/bundles/org.eclipse.wst.jsdt.support.ie/.project index e4a8dd63..717a5b49 100644 --- a/bundles/org.eclipse.wst.jsdt.support.ie/.project +++ b/bundles/org.eclipse.wst.jsdt.support.ie/.project @@ -1,34 +1,40 @@ - - - org.eclipse.wst.jsdt.support.ie - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder - - - - - org.eclipse.wst.jsdt.core.javascriptValidator - - - - - - org.eclipse.pde.PluginNature - org.eclipse.jdt.core.javanature - org.eclipse.wst.jsdt.core.jsNature - - + + + org.eclipse.wst.jsdt.support.ie + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + org.eclipse.wst.jsdt.core.javascriptValidator + + + + + org.eclipse.pde.api.tools.apiAnalysisBuilder + + + + + + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + org.eclipse.wst.jsdt.core.jsNature + org.eclipse.pde.api.tools.apiAnalysisNature + + diff --git a/bundles/org.eclipse.wst.jsdt.support.ie/META-INF/MANIFEST.MF b/bundles/org.eclipse.wst.jsdt.support.ie/META-INF/MANIFEST.MF index fcf242f7..76cd235b 100644 --- a/bundles/org.eclipse.wst.jsdt.support.ie/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.wst.jsdt.support.ie/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: %Bundle-Name.0 Bundle-SymbolicName: org.eclipse.wst.jsdt.support.ie;singleton:=true -Bundle-Version: 1.0.402.qualifier +Bundle-Version: 1.0.500.qualifier Require-Bundle: org.eclipse.wst.jsdt.core;bundle-version="[1.1.0,2.0.0)", org.eclipse.wst.jsdt.ui;bundle-version="[1.1.0,2.0.0)", org.eclipse.core.runtime;bundle-version="[3.5.0,4.0.0)", @@ -10,4 +10,4 @@ Require-Bundle: org.eclipse.wst.jsdt.core;bundle-version="[1.1.0,2.0.0)", org.eclipse.core.resources;bundle-version="[3.5.0,4.0.0)" Bundle-RequiredExecutionEnvironment: J2SE-1.4 Bundle-Localization: plugin -Bundle-Vendor: %providerName +Bundle-Vendor: %Bundle-Vendor.0 diff --git a/bundles/org.eclipse.wst.jsdt.support.ie/plugin.properties b/bundles/org.eclipse.wst.jsdt.support.ie/plugin.properties index c7416ddb..bc041e74 100644 --- a/bundles/org.eclipse.wst.jsdt.support.ie/plugin.properties +++ b/bundles/org.eclipse.wst.jsdt.support.ie/plugin.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2005, 2010 IBM Corporation and others. +# Copyright (c) 2005, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,7 +8,10 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_NONE + #Properties file for org.eclipse.wst.jsdt.support.ie Bundle-Name.0 = JSDT support for Microsoft Internet Explorer JsGlobalScopeContainerPage.name.0 = Microsoft Internet Explorer Library -providerName = Eclipse Web Tools Platform \ No newline at end of file +Bundle-Vendor.0 = Eclipse Web Tools Platform diff --git a/bundles/org.eclipse.wst.jsdt.support.ie/src/org/eclipse/wst/jsdt/internal/ui/wizards/IEMessages.java b/bundles/org.eclipse.wst.jsdt.support.ie/src/org/eclipse/wst/jsdt/internal/ui/wizards/IEMessages.java index 05f2b6b7..6e38a32c 100644 --- a/bundles/org.eclipse.wst.jsdt.support.ie/src/org/eclipse/wst/jsdt/internal/ui/wizards/IEMessages.java +++ b/bundles/org.eclipse.wst.jsdt.support.ie/src/org/eclipse/wst/jsdt/internal/ui/wizards/IEMessages.java @@ -1,3 +1,13 @@ +/******************************************************************************* + * Copyright (c) 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ package org.eclipse.wst.jsdt.internal.ui.wizards; import org.eclipse.osgi.util.NLS; diff --git a/bundles/org.eclipse.wst.jsdt.support.ie/src/org/eclipse/wst/jsdt/internal/ui/wizards/IEMessages.properties b/bundles/org.eclipse.wst.jsdt.support.ie/src/org/eclipse/wst/jsdt/internal/ui/wizards/IEMessages.properties index 30cd9b9c..84c04c70 100644 --- a/bundles/org.eclipse.wst.jsdt.support.ie/src/org/eclipse/wst/jsdt/internal/ui/wizards/IEMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.support.ie/src/org/eclipse/wst/jsdt/internal/ui/wizards/IEMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2009 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_NONE IELibraryWizardPage_title=Internet Explorer Library IELibraryWizardPage_IELibraryAdded=Internet Explorer Browser (5.0) Library added to Project.\n\n - This library supports JavaScript elements provided by Microsoft's Internet Explorer web browser. diff --git a/bundles/org.eclipse.wst.jsdt.ui/.options b/bundles/org.eclipse.wst.jsdt.ui/.options index 119937d4..0ef6876c 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/.options +++ b/bundles/org.eclipse.wst.jsdt.ui/.options @@ -1 +1,2 @@ org.eclipse.wst.jsdt.ui/statusbar/offset=false +org.eclipse.wst.jsdt.ui/debug/ResultCollector=false \ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.ui/.project b/bundles/org.eclipse.wst.jsdt.ui/.project index 64a8c46c..1ba52ce8 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/.project +++ b/bundles/org.eclipse.wst.jsdt.ui/.project @@ -1,33 +1,34 @@ - - - org.eclipse.wst.jsdt.ui - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder - - - - - org.eclipse.pde.api.tools.apiAnalysisBuilder - - - - - org.eclipse.pde.PluginNature - org.eclipse.jdt.core.javanature - org.eclipse.pde.api.tools.apiAnalysisNature - - + + + org.eclipse.wst.jsdt.ui + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + org.eclipse.pde.api.tools.apiAnalysisBuilder + + + + + + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + org.eclipse.pde.api.tools.apiAnalysisNature + + diff --git a/bundles/org.eclipse.wst.jsdt.ui/.settings/org.eclipse.jdt.core.prefs b/bundles/org.eclipse.wst.jsdt.ui/.settings/org.eclipse.jdt.core.prefs index bb359bc5..53cf527d 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/.settings/org.eclipse.jdt.core.prefs +++ b/bundles/org.eclipse.wst.jsdt.ui/.settings/org.eclipse.jdt.core.prefs @@ -1,110 +1,394 @@ -#Mon Mar 28 15:33:12 EDT 2011 -eclipse.preferences.version=1 -org.eclipse.jdt.core.builder.cleanOutputFolder=clean -org.eclipse.jdt.core.builder.duplicateResourceTask=warning -org.eclipse.jdt.core.builder.invalidClasspath=ignore -org.eclipse.jdt.core.builder.resourceCopyExclusionFilter=*.launch -org.eclipse.jdt.core.circularClasspath=error -org.eclipse.jdt.core.classpath.exclusionPatterns=enabled -org.eclipse.jdt.core.classpath.multipleOutputLocations=enabled -org.eclipse.jdt.core.codeComplete.argumentPrefixes= -org.eclipse.jdt.core.codeComplete.argumentSuffixes= -org.eclipse.jdt.core.codeComplete.fieldPrefixes= -org.eclipse.jdt.core.codeComplete.fieldSuffixes= -org.eclipse.jdt.core.codeComplete.localPrefixes= -org.eclipse.jdt.core.codeComplete.localSuffixes= -org.eclipse.jdt.core.codeComplete.staticFieldPrefixes= -org.eclipse.jdt.core.codeComplete.staticFieldSuffixes= -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=disabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2 -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.4 -org.eclipse.jdt.core.compiler.debug.lineNumber=generate -org.eclipse.jdt.core.compiler.debug.localVariable=generate -org.eclipse.jdt.core.compiler.debug.sourceFile=generate -org.eclipse.jdt.core.compiler.doc.comment.support=enabled -org.eclipse.jdt.core.compiler.maxProblemPerUnit=100 -org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning -org.eclipse.jdt.core.compiler.problem.autoboxing=ignore -org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning -org.eclipse.jdt.core.compiler.problem.deadCode=warning -org.eclipse.jdt.core.compiler.problem.deprecation=ignore -org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled -org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=enabled -org.eclipse.jdt.core.compiler.problem.discouragedReference=warning -org.eclipse.jdt.core.compiler.problem.emptyStatement=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning -org.eclipse.jdt.core.compiler.problem.fallthroughCase=warning -org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled -org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore -org.eclipse.jdt.core.compiler.problem.finalParameterBound=ignore -org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=error -org.eclipse.jdt.core.compiler.problem.forbiddenReference=error -org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning -org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled -org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning -org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore -org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=error -org.eclipse.jdt.core.compiler.problem.invalidJavadoc=ignore -org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsDeprecatedRef=enabled -org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsNotVisibleRef=enabled -org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsVisibility=private -org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore -org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=error -org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=ignore -org.eclipse.jdt.core.compiler.problem.missingJavadocComments=ignore -org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsOverriding=enabled -org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsVisibility=public -org.eclipse.jdt.core.compiler.problem.missingJavadocTags=ignore -org.eclipse.jdt.core.compiler.problem.missingJavadocTagsOverriding=enabled -org.eclipse.jdt.core.compiler.problem.missingJavadocTagsVisibility=private -org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled -org.eclipse.jdt.core.compiler.problem.missingSerialVersion=error -org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=warning -org.eclipse.jdt.core.compiler.problem.noEffectAssignment=error -org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning -org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=warning -org.eclipse.jdt.core.compiler.problem.nullReference=warning -org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning -org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore -org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=error -org.eclipse.jdt.core.compiler.problem.potentialNullReference=warning -org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning -org.eclipse.jdt.core.compiler.problem.redundantNullCheck=warning -org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore -org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore -org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore -org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=enabled -org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=error -org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled -org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled -org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore -org.eclipse.jdt.core.compiler.problem.typeParameterHiding=ignore -org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled -org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning -org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore -org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning -org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore -org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning -org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled -org.eclipse.jdt.core.compiler.problem.unusedImport=error -org.eclipse.jdt.core.compiler.problem.unusedLabel=error -org.eclipse.jdt.core.compiler.problem.unusedLocal=warning -org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=ignore -org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore -org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled -org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning -org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning -org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.source=1.3 -org.eclipse.jdt.core.incompatibleJDKLevel=ignore -org.eclipse.jdt.core.incompleteClasspath=error +#Tue Jul 17 18:19:32 EDT 2012 +org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert +org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line +org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_try_resources=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert +org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert +org.eclipse.jdt.core.compiler.problem.localVariableHiding=warning +org.eclipse.jdt.core.formatter.alignment_for_assignment=0 +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert +org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=error +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert +org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_try_resources=insert +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2 +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=false +org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false +org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert +org.eclipse.jdt.core.compiler.problem.emptyStatement=error +org.eclipse.jdt.core.compiler.problem.missingJavadocTagsVisibility=private +org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore +org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=insert +org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=error +org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert +org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore +org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert +org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=warning +org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert +org.eclipse.jdt.core.formatter.blank_lines_after_imports=1 +org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsVisibility=public +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation=0 +org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=error +org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning +org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore +org.eclipse.jdt.core.formatter.comment.format_source_code=true +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true +org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1 +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_try=insert +org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert +org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false +org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert +org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column=true +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert +org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1 +org.eclipse.jdt.core.classpath.exclusionPatterns=enabled +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16 +org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=3 +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert +org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.formatter.comment.format_header=false +org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert +org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=64 +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert +org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning +org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16 +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.comment.line_length=78 +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert +org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsNotVisibleRef=enabled +org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled +org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert +org.eclipse.jdt.core.classpath.multipleOutputLocations=enabled +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=insert +org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert +org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert +org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning +org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.builder.cleanOutputFolder=clean +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled +org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert +org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert +org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=true +org.eclipse.jdt.core.formatter.continuation_indentation=3 +org.eclipse.jdt.core.codeComplete.fieldSuffixes= +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field=insert +org.eclipse.jdt.core.compiler.problem.invalidJavadoc=ignore +org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert +org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=16 +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert +org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=enabled +org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert +org.eclipse.jdt.core.formatter.blank_lines_before_method=1 +org.eclipse.jdt.core.compiler.problem.missingJavadocTagsOverriding=enabled +org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=false +org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16 +org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1 +org.eclipse.jdt.core.builder.resourceCopyExclusionFilter=*.launch +org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert +org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line +org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.incompleteClasspath=error +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert +org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 +org.eclipse.jdt.core.formatter.join_lines_in_comments=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true +org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsOverriding=enabled +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=warning +org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0 +org.eclipse.jdt.core.formatter.comment.format_block_comments=true +org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert +org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16 +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=insert +org.eclipse.jdt.core.formatter.alignment_for_union_type_in_multicatch=16 +org.eclipse.jdt.core.formatter.comment.format_html=true +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16 +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert +org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore +org.eclipse.jdt.core.compiler.problem.autoboxing=ignore +org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning +org.eclipse.jdt.core.compiler.problem.fallthroughCase=warning +org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled +org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled +org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsDeprecatedRef=enabled +org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert +org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=error +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert +org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore +org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 +org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=insert +org.eclipse.jdt.core.compiler.problem.redundantNullCheck=warning +org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=error +org.eclipse.jdt.core.compiler.problem.forbiddenReference=error +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert +org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries=true +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_member=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert +org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true +org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=insert +org.eclipse.jdt.core.codeComplete.staticFinalFieldSuffixes= +org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16 +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert +org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=insert +org.eclipse.jdt.core.circularClasspath=error +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_try=do not insert +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 +org.eclipse.jdt.core.codeComplete.fieldPrefixes= +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert +org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line +org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch=true +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert +org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=warning +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert +org.eclipse.jdt.core.codeComplete.staticFieldSuffixes= +org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0 +org.eclipse.jdt.core.formatter.alignment_for_method_declaration=0 +org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning +org.eclipse.jdt.core.formatter.tabulation.char=tab +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert +org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled +org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true +org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled +org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert +org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false +org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false +org.eclipse.jdt.core.formatter.compact_else_if=true +org.eclipse.jdt.core.codeComplete.localPrefixes= +org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert +org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert +org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false +org.eclipse.jdt.core.compiler.problem.missingSerialVersion=error +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled +org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning +org.eclipse.jdt.core.formatter.disabling_tag=@formatter\:off +org.eclipse.jdt.core.formatter.align_type_members_on_columns=false +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=insert +org.eclipse.jdt.core.compiler.problem.finalParameterBound=ignore +org.eclipse.jdt.core.codeComplete.localSuffixes= +org.eclipse.jdt.core.formatter.join_wrapped_lines=true +org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true +org.eclipse.jdt.core.formatter.use_on_off_tags=false +org.eclipse.jdt.core.compiler.problem.discouragedReference=warning +org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16 +org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert +org.eclipse.jdt.core.formatter.comment.format_line_comments=true +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert +org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert +org.eclipse.jdt.core.formatter.comment.indent_parameter_description=true +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.indentation.size=4 +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert +org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16 +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.comment.indent_root_tags=true +org.eclipse.jdt.core.compiler.problem.deprecation=ignore +org.eclipse.jdt.core.compiler.problem.potentialNullReference=warning +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert +org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsVisibility=private +org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore +org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16 +org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled +org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert +org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false +org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true +org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert +org.eclipse.jdt.core.formatter.blank_lines_before_package=0 +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert +org.eclipse.jdt.core.formatter.indent_empty_lines=false +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16 +org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested=true +org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=warning +org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore +org.eclipse.jdt.core.compiler.problem.deadCode=warning +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter=do not insert +org.eclipse.jdt.core.codeComplete.staticFinalFieldPrefixes= +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert +org.eclipse.jdt.core.compiler.problem.noEffectAssignment=error +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert +org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore +org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line +org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 +org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=48 +org.eclipse.jdt.core.codeComplete.argumentPrefixes= +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert +org.eclipse.jdt.core.compiler.problem.unusedImport=error +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert +org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=true +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert +org.eclipse.jdt.core.compiler.problem.unusedLabel=error +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=insert +org.eclipse.jdt.core.builder.invalidClasspath=ignore +org.eclipse.jdt.core.codeComplete.argumentSuffixes= +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert +org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore +org.eclipse.jdt.core.incompatibleJDKLevel=ignore +org.eclipse.jdt.core.formatter.alignment_for_resources_in_try=80 +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.compiler.problem.nullReference=error +org.eclipse.jdt.core.codeComplete.staticFieldPrefixes= +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.problem.missingJavadocComments=ignore +org.eclipse.jdt.core.formatter.blank_lines_before_imports=1 +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.alignment_for_compact_if=32 +org.eclipse.jdt.core.compiler.problem.typeParameterHiding=ignore +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=disabled +org.eclipse.jdt.core.formatter.insert_new_line_after_label=do not insert +org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=insert +org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments=false +org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_try=do not insert +org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled +org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=3 +org.eclipse.jdt.core.formatter.lineSplit=999 +org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=enabled +org.eclipse.jdt.core.compiler.maxProblemPerUnit=100 +org.eclipse.jdt.core.compiler.source=1.3 +org.eclipse.jdt.core.formatter.tabulation.size=4 +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert +org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning +org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line +org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert +org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1 +org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries=true +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert +org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning +org.eclipse.jdt.core.builder.duplicateResourceTask=warning +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert +org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=warning +org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=insert +org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert +org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning +org.eclipse.jdt.core.compiler.problem.unusedLocal=warning +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.compiler.doc.comment.support=enabled +org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert +org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.problem.missingJavadocTags=ignore +org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.enabling_tag=@formatter\:on +org.eclipse.jdt.core.compiler.compliance=1.4 +org.eclipse.jdt.core.formatter.blank_lines_after_package=1 +org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=64 +org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert +org.eclipse.jdt.core.formatter.blank_lines_before_field=0 diff --git a/bundles/org.eclipse.wst.jsdt.ui/.settings/org.eclipse.jdt.ui.prefs b/bundles/org.eclipse.wst.jsdt.ui/.settings/org.eclipse.jdt.ui.prefs index c91d09d8..fb6bc732 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/.settings/org.eclipse.jdt.ui.prefs +++ b/bundles/org.eclipse.wst.jsdt.ui/.settings/org.eclipse.jdt.ui.prefs @@ -1,51 +1,54 @@ -#Wed Oct 24 19:41:31 EDT 2007 -cleanup.add_default_serial_version_id=true -cleanup.add_generated_serial_version_id=false -cleanup.add_missing_annotations=false -cleanup.add_missing_deprecated_annotations=true -cleanup.add_missing_nls_tags=false -cleanup.add_missing_override_annotations=true -cleanup.add_serial_version_id=true -cleanup.always_use_blocks=true -cleanup.always_use_parentheses_in_expressions=true -cleanup.always_use_this_for_non_static_field_access=false -cleanup.always_use_this_for_non_static_method_access=false -cleanup.convert_to_enhanced_for_loop=false -cleanup.format_source_code=false -cleanup.make_local_variable_final=true -cleanup.make_parameters_final=false -cleanup.make_private_fields_final=true -cleanup.make_variable_declarations_final=false -cleanup.never_use_blocks=false -cleanup.never_use_parentheses_in_expressions=false -cleanup.organize_imports=true -cleanup.qualify_static_field_accesses_with_declaring_class=false -cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true -cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true -cleanup.qualify_static_member_accesses_with_declaring_class=true -cleanup.qualify_static_method_accesses_with_declaring_class=false -cleanup.remove_private_constructors=true -cleanup.remove_unnecessary_casts=true -cleanup.remove_unnecessary_nls_tags=true -cleanup.remove_unused_imports=true -cleanup.remove_unused_local_variables=false -cleanup.remove_unused_private_fields=true -cleanup.remove_unused_private_members=true -cleanup.remove_unused_private_methods=true -cleanup.remove_unused_private_types=true -cleanup.use_blocks=true -cleanup.use_blocks_only_for_return_and_throw=false -cleanup.use_parentheses_in_expressions=true -cleanup.use_this_for_non_static_field_access=false -cleanup.use_this_for_non_static_field_access_only_if_necessary=true -cleanup.use_this_for_non_static_method_access=false -cleanup.use_this_for_non_static_method_access_only_if_necessary=true -cleanup_profile=_SSE Team Styles -cleanup_settings_version=2 -eclipse.preferences.version=1 -internal.default.compliance=default -org.eclipse.jdt.ui.exception.name=e -org.eclipse.jdt.ui.gettersetter.use.is=true -org.eclipse.jdt.ui.keywordthis=false -org.eclipse.jdt.ui.overrideannotation=false -org.eclipse.jdt.ui.text.custom_code_templates= +#Mon Mar 05 17:39:49 EST 2012 +cleanup.format_source_code=false +cleanup_profile=_SSE Team Styles +org.eclipse.jdt.ui.text.custom_code_templates= +cleanup.add_missing_annotations=false +cleanup.use_this_for_non_static_method_access_only_if_necessary=true +cleanup.remove_unused_private_types=true +cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true +cleanup.qualify_static_method_accesses_with_declaring_class=false +cleanup.add_generated_serial_version_id=false +cleanup.make_variable_declarations_final=false +cleanup.always_use_this_for_non_static_field_access=false +org.eclipse.jdt.ui.overrideannotation=false +internal.default.compliance=default +org.eclipse.jdt.ui.keywordthis=false +cleanup.never_use_parentheses_in_expressions=false +cleanup.add_serial_version_id=true +cleanup_settings_version=2 +cleanup.remove_unused_private_methods=true +cleanup.use_this_for_non_static_field_access=false +cleanup.use_blocks_only_for_return_and_throw=false +cleanup.remove_unused_private_members=true +org.eclipse.jdt.ui.exception.name=e +cleanup.always_use_this_for_non_static_method_access=false +cleanup.remove_unnecessary_nls_tags=true +cleanup.qualify_static_field_accesses_with_declaring_class=false +formatter_profile=_SSE Formatting +cleanup.add_missing_nls_tags=false +cleanup.use_this_for_non_static_field_access_only_if_necessary=true +cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true +org.eclipse.jdt.ui.gettersetter.use.is=true +cleanup.remove_unnecessary_casts=true +cleanup.qualify_static_member_accesses_with_declaring_class=true +cleanup.use_parentheses_in_expressions=true +cleanup.remove_unused_private_fields=true +cleanup.make_parameters_final=false +eclipse.preferences.version=1 +cleanup.remove_unused_imports=true +cleanup.organize_imports=true +cleanup.convert_to_enhanced_for_loop=false +cleanup.remove_private_constructors=true +cleanup.always_use_blocks=true +cleanup.never_use_blocks=false +cleanup.always_use_parentheses_in_expressions=true +formatter_settings_version=12 +cleanup.use_this_for_non_static_method_access=false +cleanup.remove_unused_local_variables=false +cleanup.make_private_fields_final=true +org.eclipse.jdt.ui.javadoc=true +cleanup.add_missing_deprecated_annotations=true +cleanup.add_default_serial_version_id=true +cleanup.use_blocks=true +cleanup.add_missing_override_annotations=true +cleanup.make_local_variable_final=true diff --git a/bundles/org.eclipse.wst.jsdt.ui/META-INF/MANIFEST.MF b/bundles/org.eclipse.wst.jsdt.ui/META-INF/MANIFEST.MF index 7cddb864..2683e9f7 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/META-INF/MANIFEST.MF +++ b/bundles/org.eclipse.wst.jsdt.ui/META-INF/MANIFEST.MF @@ -1,6 +1,6 @@ Manifest-Version: 1.0 Bundle-SymbolicName: org.eclipse.wst.jsdt.ui; singleton:=true -Bundle-Version: 1.1.202.qualifier +Bundle-Version: 1.1.400.qualifier Bundle-Activator: org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin Import-Package: com.ibm.icu.text, com.ibm.icu.util @@ -109,7 +109,7 @@ Require-Bundle: org.eclipse.ui;bundle-version="[3.5.0,4.0.0)", org.eclipse.core.expressions;bundle-version="[3.4.100,4.0.0)", org.eclipse.core.filesystem;bundle-version="[1.2.0,2.0.0)", org.eclipse.core.resources;bundle-version="[3.5.0,4.0.0)", - org.eclipse.wst.jsdt.core;bundle-version="[1.1.101,2.0.0)", + org.eclipse.wst.jsdt.core;bundle-version="[1.2.100,2.0.0)", org.eclipse.search;bundle-version="[3.5.0,4.0.0)", org.eclipse.debug.core;bundle-version="[3.5.0,4.0.0)", org.eclipse.debug.ui;bundle-version="[3.5.0,4.0.0)", diff --git a/bundles/org.eclipse.wst.jsdt.ui/about.html b/bundles/org.eclipse.wst.jsdt.ui/about.html index b3906a9f..3fc12c1e 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/about.html +++ b/bundles/org.eclipse.wst.jsdt.ui/about.html @@ -28,7 +28,7 @@ and such source code may be obtained at http://

The Content includes items that have been sourced from third parties as set out below. If you did not receive this Content directly from the Eclipse Foundation, the following is provided -for informational purposes only, and you should look to the Redistributor’s license for +for informational purposes only, and you should look to the Redistributor's license for terms and conditions of use.

Ispell 3.1.20

diff --git a/bundles/org.eclipse.wst.jsdt.ui/about.properties b/bundles/org.eclipse.wst.jsdt.ui/about.properties index c59607ec..3f49197b 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/about.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/about.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2005, 2009 IBM Corporation and others. +# Copyright (c) 2005, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR # about.properties # contains externalized strings for about.ini diff --git a/bundles/org.eclipse.wst.jsdt.ui/build.properties b/bundles/org.eclipse.wst.jsdt.ui/build.properties index e6ba0d63..3a3e09d2 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/build.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/build.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2007 IBM Corporation and others. +# Copyright (c) 2007, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -12,7 +12,6 @@ source.. = src/ output.. = bin/ bin.includes = META-INF/,\ .,\ - build.properties,\ icons/,\ plugin.properties,\ plugin.xml,\ @@ -25,3 +24,4 @@ bin.includes = META-INF/,\ about.mappings,\ .options src.includes = schema/ +nls_exclude=templates/* \ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.ui/icons/full/etool16/loading1.gif b/bundles/org.eclipse.wst.jsdt.ui/icons/full/etool16/loading1.gif new file mode 100644 index 00000000..eae118ad Binary files /dev/null and b/bundles/org.eclipse.wst.jsdt.ui/icons/full/etool16/loading1.gif differ diff --git a/bundles/org.eclipse.wst.jsdt.ui/icons/full/etool16/loading2.gif b/bundles/org.eclipse.wst.jsdt.ui/icons/full/etool16/loading2.gif new file mode 100644 index 00000000..c37f13d7 Binary files /dev/null and b/bundles/org.eclipse.wst.jsdt.ui/icons/full/etool16/loading2.gif differ diff --git a/bundles/org.eclipse.wst.jsdt.ui/icons/full/etool16/loading3.gif b/bundles/org.eclipse.wst.jsdt.ui/icons/full/etool16/loading3.gif new file mode 100644 index 00000000..10a87c20 Binary files /dev/null and b/bundles/org.eclipse.wst.jsdt.ui/icons/full/etool16/loading3.gif differ diff --git a/bundles/org.eclipse.wst.jsdt.ui/icons/full/etool16/loading4.gif b/bundles/org.eclipse.wst.jsdt.ui/icons/full/etool16/loading4.gif new file mode 100644 index 00000000..7c6cfa8a Binary files /dev/null and b/bundles/org.eclipse.wst.jsdt.ui/icons/full/etool16/loading4.gif differ diff --git a/bundles/org.eclipse.wst.jsdt.ui/plugin.properties b/bundles/org.eclipse.wst.jsdt.ui/plugin.properties index b3373eb8..c84773b9 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/plugin.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/plugin.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2010 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_NONE pluginName= Eclipse JavaScript Development Tools providerName= Eclipse Web Tools Platform diff --git a/bundles/org.eclipse.wst.jsdt.ui/plugin.xml b/bundles/org.eclipse.wst.jsdt.ui/plugin.xml index e9eac347..4e2414e0 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/plugin.xml +++ b/bundles/org.eclipse.wst.jsdt.ui/plugin.xml @@ -457,13 +457,6 @@ name="%viewCategoryName" id="org.eclipse.wst.jsdt.ui.java"> - - + +
@@ -1511,7 +1511,7 @@ icon="$nl$/icons/full/etool16/newjscript_wiz.gif" tooltip="%Javascript_UI_Wizard_New_Title" class="org.eclipse.wst.jsdt.internal.ui.wizards.OpenJavaScriptFileWizardToolbarAction" - toolbarPath="Normal/JSWizards" + toolbarPath="Normal/JavaWizards" id="org.eclipse.wst.jsdt.ui.actions.OpenFileWizard"> @@ -1762,14 +1762,6 @@ - - @@ -5063,15 +5055,14 @@ - + + id="org.eclipse.wst.jsdt.USER_LIBRARY"> @@ -5124,7 +5115,7 @@ label="%action.label.projectConvert" menubarPath="org.eclipse.ui.projectConfigure/additions" enablesFor="+" - id="org.eclipse.wst.jsdt.ui.internal.convertProjects"> + id="org.eclipse.wst.jsdt.internal.web.ui.convertProjects"> @@ -5284,18 +5275,19 @@ - + + - + @@ -5303,11 +5295,12 @@ - + + - - + + @@ -5345,139 +5338,58 @@ - - + + - + - - - - + id="org.eclipse.wst.jsdt.ui.navigator.actions.OpenActions" + overrides="org.eclipse.ui.navigator.resources.OpenActions"> + + + + + + + - - + - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + - @@ -6002,7 +5914,7 @@ + id="org.eclipse.wst.jsdt.BASE"> diff --git a/bundles/org.eclipse.wst.jsdt.ui/schema/JsGlobalScopeContainerPage.exsd b/bundles/org.eclipse.wst.jsdt.ui/schema/JsGlobalScopeContainerPage.exsd index 947681a4..4435809e 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/schema/JsGlobalScopeContainerPage.exsd +++ b/bundles/org.eclipse.wst.jsdt.ui/schema/JsGlobalScopeContainerPage.exsd @@ -1,6 +1,6 @@ - + @@ -12,11 +12,6 @@ edit a includepath container entry. - - - - - @@ -80,13 +75,6 @@ with a public 0-argument constructor. - - - - Allow multiple Include Path container entries with the associated ID to be added to a project, 'false' if not otherwise specified. - - - @@ -111,8 +99,23 @@ with a public 0-argument constructor. + + + + + + + + - + + + + + + + + diff --git a/bundles/org.eclipse.wst.jsdt.ui/schema/javadocCompletionProcessor.exsd b/bundles/org.eclipse.wst.jsdt.ui/schema/javadocCompletionProcessor.exsd index 5686eef2..6914de38 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/schema/javadocCompletionProcessor.exsd +++ b/bundles/org.eclipse.wst.jsdt.ui/schema/javadocCompletionProcessor.exsd @@ -6,7 +6,7 @@ - This extension point adds completion processors to the list used for generating JSDoc proposals, e.g. to propose new JSDoc tags. + This extension point allows to add a JSdoc completion processor to e.g. offer new JSdoc tags. <p> Deprecated as of 3.2. Extenders should rather contribute to the <tt>org.eclipse.wst.jsdt.ui.javaCompletionProposalComputer</tt> extension point, which allows to provide additional proposals not only for jsdoc, but any part of a JavaScript editor. </p> diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/CorextMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/CorextMessages.properties index c6b037b8..0398ae28 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/CorextMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/CorextMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2007 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,9 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR + Resources_outOfSyncResources= Some resources are out of sync Resources_outOfSync= Resource ''{0}'' is out of sync with file system. Resources_modifiedResources= There are modified resources diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/buildpath/BuildpathDelta.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/buildpath/BuildpathDelta.java index 2ec2c96a..6868565c 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/buildpath/BuildpathDelta.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/buildpath/BuildpathDelta.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/buildpath/CPJavaProject.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/buildpath/CPJavaProject.java index 2a1af9a3..fe1bc353 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/buildpath/CPJavaProject.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/buildpath/CPJavaProject.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CallHierarchyMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CallHierarchyMessages.properties index 23407fa3..eba733d8 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CallHierarchyMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/CallHierarchyMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2007 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -9,5 +9,8 @@ # Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation # (report 36180: Callers/Callees view) ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_NONE + CallerMethodWrapper_taskname=Finding callers... CalleeMethodWrapper_taskname=Finding callees... diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/IImplementorFinder.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/IImplementorFinder.java index c50322f5..0f26bfd8 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/IImplementorFinder.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/IImplementorFinder.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/JavaImplementorFinder.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/JavaImplementorFinder.java index eb326c1f..92ac8803 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/JavaImplementorFinder.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/callhierarchy/JavaImplementorFinder.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/CodeGenerationMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/CodeGenerationMessages.java index 913459db..ce3f150b 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/CodeGenerationMessages.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/CodeGenerationMessages.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/CodeGenerationMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/CodeGenerationMessages.properties index a4a54e2a..a35dc0d0 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/CodeGenerationMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/codemanipulation/CodeGenerationMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2007 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,9 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR + AddGetterSetterOperation_description=Generate Getters and Setters... AddGetterSetterOperation_error_input_type_not_found=Could not find the selected type element diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/CleanUpConstants.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/CleanUpConstants.java index 83215c70..15ca7399 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/CleanUpConstants.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/CleanUpConstants.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/FixMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/FixMessages.java index 5d3239be..f087ad9d 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/FixMessages.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/FixMessages.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/FixMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/FixMessages.properties index e3546bd9..b5dbc12b 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/FixMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/fix/FixMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2005, 2008 IBM Corporation and others. +# Copyright (c) 2005, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,9 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR + CleanUpRefactoring_Refactoring_name=Clean Up CleanUpRefactoring_Initialize_message=Checking preconditions for project ''{0}'' CleanUpRefactoring_Parser_Startup_message=Processing project {0} diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/javadoc/JavaDocCommentReader.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/javadoc/JavaDocCommentReader.java index 645928f0..e0fe8a26 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/javadoc/JavaDocCommentReader.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/javadoc/JavaDocCommentReader.java @@ -10,9 +10,9 @@ *******************************************************************************/ package org.eclipse.wst.jsdt.internal.corext.javadoc; -import org.eclipse.wst.jsdt.internal.ui.text.html.SingleCharReader; import org.eclipse.wst.jsdt.core.IBuffer; import org.eclipse.wst.jsdt.core.formatter.IndentManipulation; +import org.eclipse.wst.jsdt.internal.ui.text.html.SingleCharReader; /** @@ -37,6 +37,17 @@ public class JavaDocCommentReader extends SingleCharReader { reset(); } + public JavaDocCommentReader(IBuffer buf, int end) { + fBuffer= buf; + fStartPos = fEndPos = end; + + fStartPos = rewind(); + if (fStartPos >= 0) + reset(); + else + fCurrPos = fEndPos; + } + /** * @see java.io.Reader#read() */ @@ -81,7 +92,49 @@ public class JavaDocCommentReader extends SingleCharReader { fWasNewLine= true; } - + private int rewind() { + if (fEndPos > 4) { + char ch; + // skip whitespace before the name + do { + ch = fBuffer.getChar(fStartPos--); + } + while (fStartPos > 4 && Character.isWhitespace(ch)); + + // skip keyword if present + if (ch != 'r' && ch != '/') + return -1; + ch = fBuffer.getChar(fStartPos--); + if (ch != 'a' && ch != '*') + return -1; + if (ch == '*') + fStartPos += 2; + else { + ch = fBuffer.getChar(fStartPos--); + if (ch != 'v') + return -1; + } + // skip before any trailing whitespace + do { + ch = fBuffer.getChar(fStartPos--); + } + while (fStartPos > 4 && Character.isWhitespace(ch)); + // found a possible block comment end + if (fStartPos > 4) { + if (ch == '/' && fBuffer.getChar(fStartPos) == '*') { + fEndPos = fStartPos - 1; + while (fStartPos > 2 && (fBuffer.getChar(fStartPos - 1) != '/' || fBuffer.getChar(fStartPos) != '*')) { + fStartPos--; + } + if (fBuffer.getChar(fStartPos - 1) == '/' || fBuffer.getChar(fStartPos) == '*') { + return fStartPos; + } + } + } + } + return -1; + } + /** * Returns the offset of the last read character in the passed buffer. */ diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/IRefactoringSearchRequestor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/IRefactoringSearchRequestor.java index 0d82efac..37ea4f2f 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/IRefactoringSearchRequestor.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/IRefactoringSearchRequestor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/JavaRefactoringArguments.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/JavaRefactoringArguments.java index cccc09b5..7cfe321b 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/JavaRefactoringArguments.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/JavaRefactoringArguments.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/binary/SourceCreationOperation.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/binary/SourceCreationOperation.java index 270d2f9e..b3c056fa 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/binary/SourceCreationOperation.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/binary/SourceCreationOperation.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2007 IBM Corporation and others. + * Copyright (c) 2006, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/binary/StubCreationOperation.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/binary/StubCreationOperation.java index 8a885e20..e07401ea 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/binary/StubCreationOperation.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/binary/StubCreationOperation.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/RefactoringDescriptorChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/RefactoringDescriptorChange.java index ef838e5d..dc00d92c 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/RefactoringDescriptorChange.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/RefactoringDescriptorChange.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2007 IBM Corporation and others. + * Copyright (c) 2006, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/UndoCompilationUnitChange.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/UndoCompilationUnitChange.java index abaeb28b..24cd1318 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/UndoCompilationUnitChange.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/changes/UndoCompilationUnitChange.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ExtractTempRefactoring.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ExtractTempRefactoring.java index 6e636d23..2515c6d7 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ExtractTempRefactoring.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/ExtractTempRefactoring.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/LocalTypeAnalyzer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/LocalTypeAnalyzer.java index b2e09b85..ce9816ae 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/LocalTypeAnalyzer.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/LocalTypeAnalyzer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/ReturnFlowInfo.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/ReturnFlowInfo.java index a90453cf..d9e62aa8 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/ReturnFlowInfo.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/code/flow/ReturnFlowInfo.java @@ -28,7 +28,7 @@ class ReturnFlowInfo extends FlowInfo { private static int getReturnFlag(ReturnStatement node) { Expression expression= node.getExpression(); - if (expression == null /* we can't resolve "void" anyway || expression.resolveTypeBinding() == node.getAST().resolveWellKnownType("void")*/) //$NON-NLS-1$ + if (expression == null /* The only binding resolver implementation can't resolve "void" anyway || expression.resolveTypeBinding() == node.getAST().resolveWellKnownType("void")*/) //$NON-NLS-1$ return VOID_RETURN; return VALUE_RETURN; } diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSElement.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSElement.java index 7f982d8b..96079651 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSElement.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSElement.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSMessages.properties index d24228e6..b813beca 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2007 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,7 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### - +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR NLSSourceModifier_replace_value=Rename value ''{0}'' to ''{1}'' NLSSourceModifier_replace_key=Replace key ''{0}'' to ''{1}'' diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSSubstitution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSSubstitution.java index b8b630b9..563efd39 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSSubstitution.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/NLSSubstitution.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/changes/NLSChangesMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/changes/NLSChangesMessages.properties index 3848d089..b7886cd2 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/changes/NLSChangesMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/nls/changes/NLSChangesMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2007 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,9 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR + createFile_creating_resource=Creating file... createFile_Create_file=Create file {0} deleteFile_deleting_resource=Deleting file... diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/participants/ResourceModifications.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/participants/ResourceModifications.java index edcfae60..4d02a7d4 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/participants/ResourceModifications.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/participants/ResourceModifications.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/refactoring.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/refactoring.properties index dc4c2800..26259aea 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/refactoring.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/refactoring.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2008 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,9 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR + # NLS properties for the Refactoring Core ####################################### diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/JavaRenameRefactoring.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/JavaRenameRefactoring.java index 03a511be..e401b54e 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/JavaRenameRefactoring.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/JavaRenameRefactoring.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameAnalyzeUtil.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameAnalyzeUtil.java index 8cbaa225..f2b8790f 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameAnalyzeUtil.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameAnalyzeUtil.java @@ -32,8 +32,8 @@ import org.eclipse.ltk.core.refactoring.RefactoringStatusEntry; import org.eclipse.ltk.core.refactoring.TextChange; import org.eclipse.ltk.core.refactoring.TextEditChangeGroup; import org.eclipse.text.edits.TextEdit; -import org.eclipse.wst.jsdt.core.IJavaScriptElement; import org.eclipse.wst.jsdt.core.IJavaScriptUnit; +import org.eclipse.wst.jsdt.core.IJavaScriptElement; import org.eclipse.wst.jsdt.core.ISourceRange; import org.eclipse.wst.jsdt.core.ISourceReference; import org.eclipse.wst.jsdt.core.JavaScriptModelException; @@ -42,9 +42,9 @@ import org.eclipse.wst.jsdt.core.compiler.IProblem; import org.eclipse.wst.jsdt.core.dom.AST; import org.eclipse.wst.jsdt.core.dom.ASTNode; import org.eclipse.wst.jsdt.core.dom.ASTVisitor; +import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit; import org.eclipse.wst.jsdt.core.dom.IBinding; import org.eclipse.wst.jsdt.core.dom.IVariableBinding; -import org.eclipse.wst.jsdt.core.dom.JavaScriptUnit; import org.eclipse.wst.jsdt.core.dom.Name; import org.eclipse.wst.jsdt.core.dom.SimpleName; import org.eclipse.wst.jsdt.core.dom.VariableDeclaration; diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameMethodProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameMethodProcessor.java index d446745f..06914f47 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameMethodProcessor.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/rename/RenameMethodProcessor.java @@ -58,6 +58,7 @@ import org.eclipse.wst.jsdt.core.search.SearchMatch; import org.eclipse.wst.jsdt.core.search.SearchParticipant; import org.eclipse.wst.jsdt.core.search.SearchPattern; import org.eclipse.wst.jsdt.core.search.SearchRequestor; +import org.eclipse.wst.jsdt.internal.core.JavaElement; import org.eclipse.wst.jsdt.internal.corext.refactoring.Checks; import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptor; import org.eclipse.wst.jsdt.internal.corext.refactoring.JDTRefactoringDescriptorComment; @@ -430,9 +431,34 @@ public abstract class RenameMethodProcessor extends JavaRenameProcessor implemen } //TODO: shouldn't scope take all ripple methods into account? protected static final IJavaScriptSearchScope createRefactoringScope(IFunction method) throws CoreException { - return RefactoringScopeFactory.create(method); + JavaElement javaElement = (JavaElement) method; + if (javaElement instanceof IMember) { + IMember member= (IMember) javaElement; + if (member.getParent().getElementType() == IJavaScriptElement.METHOD) { + IJavaScriptElement toplevelFunction = getTopLevelFunction(member.getParent()); + return SearchEngine.createJavaSearchScope(new IJavaScriptElement[] {toplevelFunction}); + } + else if (JdtFlags.isPrivate(member)) { + if (member.getJavaScriptUnit() != null) + return SearchEngine.createJavaSearchScope(new IJavaScriptElement[] { member.getJavaScriptUnit()}); + else + return SearchEngine.createJavaSearchScope(new IJavaScriptElement[] { member}); + } + } + return RefactoringScopeFactory.create(javaElement.getJavaScriptProject()); } + /** + * @param parent + * @return + */ + private static IJavaScriptElement getTopLevelFunction(IJavaScriptElement method) { + if (method.getParent().getElementType() == IJavaScriptElement.METHOD) + return getTopLevelFunction(method.getParent()); + + return method; + } + SearchPattern createOccurrenceSearchPattern() { HashSet methods= new HashSet(fMethodsToRename); methods.add(fMethod); diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/CreateTargetExecutionLog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/CreateTargetExecutionLog.java index 22c3e5a4..86f99fca 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/CreateTargetExecutionLog.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/CreateTargetExecutionLog.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2007 IBM Corporation and others. + * Copyright (c) 2006, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JDTCopyRefactoringDescriptor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JDTCopyRefactoringDescriptor.java index 151dd1d6..2ba744b1 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JDTCopyRefactoringDescriptor.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JDTCopyRefactoringDescriptor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2007 IBM Corporation and others. + * Copyright (c) 2006, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JDTMoveRefactoringDescriptor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JDTMoveRefactoringDescriptor.java index 996196ce..65428798 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JDTMoveRefactoringDescriptor.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JDTMoveRefactoringDescriptor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2007 IBM Corporation and others. + * Copyright (c) 2006, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JavaCopyRefactoring.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JavaCopyRefactoring.java index 5244dbb8..aeb8542c 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JavaCopyRefactoring.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JavaCopyRefactoring.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2007 IBM Corporation and others. + * Copyright (c) 2006, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JavaDeleteRefactoring.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JavaDeleteRefactoring.java index 9449a613..f9b4c92e 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JavaDeleteRefactoring.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/JavaDeleteRefactoring.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2007 IBM Corporation and others. + * Copyright (c) 2006, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/MonitoringCreateTargetQueries.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/MonitoringCreateTargetQueries.java index 1fecf0b3..f55f3be1 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/MonitoringCreateTargetQueries.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/MonitoringCreateTargetQueries.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2007 IBM Corporation and others. + * Copyright (c) 2006, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/NullReorgQueries.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/NullReorgQueries.java index 0690618a..cc525ed3 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/NullReorgQueries.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/reorg/NullReorgQueries.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2007 IBM Corporation and others. + * Copyright (c) 2006, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ChangeMethodSignatureRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ChangeMethodSignatureRefactoringContribution.java index a3143457..eaa0f2c4 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ChangeMethodSignatureRefactoringContribution.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ChangeMethodSignatureRefactoringContribution.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ChangeTypeRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ChangeTypeRefactoringContribution.java index 80cf08b8..cfab193b 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ChangeTypeRefactoringContribution.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ChangeTypeRefactoringContribution.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2007 IBM Corporation and others. + * Copyright (c) 2006, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ConvertAnonymousRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ConvertAnonymousRefactoringContribution.java index 8120fe4e..34c8c956 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ConvertAnonymousRefactoringContribution.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ConvertAnonymousRefactoringContribution.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/CopyRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/CopyRefactoringContribution.java index bdbb16c1..69ce5d3d 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/CopyRefactoringContribution.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/CopyRefactoringContribution.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2007 IBM Corporation and others. + * Copyright (c) 2006, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/DeleteRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/DeleteRefactoringContribution.java index 50e7e373..e3bb7d13 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/DeleteRefactoringContribution.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/DeleteRefactoringContribution.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2007 IBM Corporation and others. + * Copyright (c) 2006, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ExtractMethodRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ExtractMethodRefactoringContribution.java index d43c39a2..c912bafa 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ExtractMethodRefactoringContribution.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ExtractMethodRefactoringContribution.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ExtractSupertypeRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ExtractSupertypeRefactoringContribution.java index 5da79514..73fb4dc7 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ExtractSupertypeRefactoringContribution.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/ExtractSupertypeRefactoringContribution.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/InlineConstantRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/InlineConstantRefactoringContribution.java index 564b7416..c6749cf4 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/InlineConstantRefactoringContribution.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/InlineConstantRefactoringContribution.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/InlineTempRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/InlineTempRefactoringContribution.java index 9a9f9eb4..3cc269e7 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/InlineTempRefactoringContribution.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/InlineTempRefactoringContribution.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/IntroduceFactoryRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/IntroduceFactoryRefactoringContribution.java index f40b286c..0d957d77 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/IntroduceFactoryRefactoringContribution.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/IntroduceFactoryRefactoringContribution.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/IntroduceIndirectionRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/IntroduceIndirectionRefactoringContribution.java index 89add449..1624c049 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/IntroduceIndirectionRefactoringContribution.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/IntroduceIndirectionRefactoringContribution.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/IntroduceParameterRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/IntroduceParameterRefactoringContribution.java index 23f56336..ab1edac1 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/IntroduceParameterRefactoringContribution.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/IntroduceParameterRefactoringContribution.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/MoveMemberTypeRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/MoveMemberTypeRefactoringContribution.java index d7988b17..f652eb8a 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/MoveMemberTypeRefactoringContribution.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/MoveMemberTypeRefactoringContribution.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/MoveMethodRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/MoveMethodRefactoringContribution.java index f73c14af..b3c0e89f 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/MoveMethodRefactoringContribution.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/MoveMethodRefactoringContribution.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/MoveRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/MoveRefactoringContribution.java index 197c24d4..1ff5eefe 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/MoveRefactoringContribution.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/MoveRefactoringContribution.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2007 IBM Corporation and others. + * Copyright (c) 2006, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/MoveStaticMembersRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/MoveStaticMembersRefactoringContribution.java index c14e00d3..ac4cc3b8 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/MoveStaticMembersRefactoringContribution.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/MoveStaticMembersRefactoringContribution.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/PromoteTempToFieldRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/PromoteTempToFieldRefactoringContribution.java index f8a14cc1..e75d1d20 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/PromoteTempToFieldRefactoringContribution.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/PromoteTempToFieldRefactoringContribution.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/PullUpRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/PullUpRefactoringContribution.java index 855c1472..a131b59b 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/PullUpRefactoringContribution.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/PullUpRefactoringContribution.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/PushDownRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/PushDownRefactoringContribution.java index 1e16dded..a8dc6c6b 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/PushDownRefactoringContribution.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/PushDownRefactoringContribution.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/SelfEncapsulateRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/SelfEncapsulateRefactoringContribution.java index c658eea8..305f3b5a 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/SelfEncapsulateRefactoringContribution.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/SelfEncapsulateRefactoringContribution.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/UseSupertypeRefactoringContribution.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/UseSupertypeRefactoringContribution.java index d0df51c8..68cf7448 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/UseSupertypeRefactoringContribution.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/scripting/UseSupertypeRefactoringContribution.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ExtractSupertypeRefactoring.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ExtractSupertypeRefactoring.java index 7f9de1dd..2d925fe9 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ExtractSupertypeRefactoring.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/ExtractSupertypeRefactoring.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2007 IBM Corporation and others. + * Copyright (c) 2006, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/JavaMoveRefactoring.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/JavaMoveRefactoring.java index 1e1063d6..c04df4ff 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/JavaMoveRefactoring.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/structure/JavaMoveRefactoring.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/ICommentProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/ICommentProvider.java index 5ed7a6ce..da77a103 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/ICommentProvider.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/ICommentProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/IDelegateUpdating.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/IDelegateUpdating.java index e900fae8..11a06e4e 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/IDelegateUpdating.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/IDelegateUpdating.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/IScriptableRefactoring.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/IScriptableRefactoring.java index 29f12012..227f7396 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/IScriptableRefactoring.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/IScriptableRefactoring.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/ISimilarDeclarationUpdating.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/ISimilarDeclarationUpdating.java index 3bb2db0c..906c1b51 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/ISimilarDeclarationUpdating.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/refactoring/tagging/ISimilarDeclarationUpdating.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/CodeTemplateContextType.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/CodeTemplateContextType.java index 58225f15..37ac380d 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/CodeTemplateContextType.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/CodeTemplateContextType.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/CompilationUnitCompletion.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/CompilationUnitCompletion.java index c6bc5781..3aae1533 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/CompilationUnitCompletion.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/CompilationUnitCompletion.java @@ -85,8 +85,12 @@ final class CompilationUnitCompletion extends CompletionRequestor { * false if not */ public boolean isArray() { - if (fType == UNKNOWN && (fChecked & ARRAY) == 0 && Signature.getTypeSignatureKind(signature) == Signature.ARRAY_TYPE_SIGNATURE) - fType= ARRAY; + + try + { + if (fType == UNKNOWN && (fChecked & ARRAY) == 0 && Signature.getTypeSignatureKind(signature) == Signature.ARRAY_TYPE_SIGNATURE) + fType= ARRAY; + } catch(IllegalArgumentException iae) {/* Ignore bad signature: assume not array */} fChecked |= ARRAY; return fType == ARRAY; } @@ -551,7 +555,7 @@ final class CompilationUnitCompletion extends CompletionRequestor { public void accept(CompletionProposal proposal) { String name= String.valueOf(proposal.getCompletion()); - String signature= String.valueOf(proposal.getSignature()); + String signature = ( proposal.getSignature() != null ? String.valueOf( proposal.getSignature() ) : "" ); switch (proposal.getKind()) { diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/ElementTypeResolver.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/ElementTypeResolver.java index 41fef4e5..52e6575e 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/ElementTypeResolver.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/ElementTypeResolver.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/ExclusivePositionUpdater.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/ExclusivePositionUpdater.java index 8c5ffbd3..b8a3333f 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/ExclusivePositionUpdater.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/ExclusivePositionUpdater.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2007 IBM Corporation and others. + * Copyright (c) 2006, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/FieldResolver.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/FieldResolver.java index a997cb93..f8f36b3c 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/FieldResolver.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/FieldResolver.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2007 IBM Corporation and others. + * Copyright (c) 2006, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaContext.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaContext.java index 06c9a22f..fd504625 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaContext.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaContext.java @@ -222,7 +222,7 @@ public class JavaContext extends CompilationUnitContext { * */ private boolean isTempalteNamePart(char ch) { - return !Character.isWhitespace(ch) && ch != '(' && ch != ')' && ch != '{' && ch != '}' && ch != ';'; + return !Character.isWhitespace(ch) && ch != '(' && ch != ')' && ch != '{' && ch != '}' && ch != ';' && ch != '>'; } /* diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaTemplateMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaTemplateMessages.java index 8c0b1c80..9933df7d 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaTemplateMessages.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaTemplateMessages.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaTemplateMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaTemplateMessages.properties index b394c3a9..85d30a79 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaTemplateMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaTemplateMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2008 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,7 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### - +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR ContextType_error_multiple_cursor_variables=Template has multiple cursor variables. diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaVariable.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaVariable.java index 9d97c150..52ea93ea 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaVariable.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/JavaVariable.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2007 IBM Corporation and others. + * Copyright (c) 2006, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/LocalVarResolver.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/LocalVarResolver.java index de908eac..bc70e336 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/LocalVarResolver.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/LocalVarResolver.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2007 IBM Corporation and others. + * Copyright (c) 2006, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/NameResolver.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/NameResolver.java index f49faea6..340a48ce 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/NameResolver.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/NameResolver.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2007 IBM Corporation and others. + * Copyright (c) 2006, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/TemplateSet.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/TemplateSet.java index bbd1d1b8..73604e6a 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/TemplateSet.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/TemplateSet.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/TypeVariableResolver.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/TypeVariableResolver.java index 081f96fc..33467442 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/TypeVariableResolver.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/TypeVariableResolver.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/VarResolver.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/VarResolver.java index 41ff456f..25b136be 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/VarResolver.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/template/java/VarResolver.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2007 IBM Corporation and others. + * Copyright (c) 2006, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/Messages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/Messages.java index 951eea68..35e5e5e2 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/Messages.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/Messages.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/SearchUtils.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/SearchUtils.java index 916d4cc9..a9a6da33 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/SearchUtils.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/corext/util/SearchUtils.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/IJavaStatusConstants.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/IJavaStatusConstants.java index e9db530d..083e29bf 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/IJavaStatusConstants.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/IJavaStatusConstants.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaPerspectiveFactory.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaPerspectiveFactory.java index 052b5b5e..14c8b413 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaPerspectiveFactory.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaPerspectiveFactory.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -34,23 +34,22 @@ public class JavaPerspectiveFactory implements IPerspectiveFactory { IFolderLayout folder= layout.createFolder("left", IPageLayout.LEFT, (float)0.25, editorArea); //$NON-NLS-1$ - folder.addView(JavaScriptUI.ID_PACKAGES); - folder.addPlaceholder(IPageLayout.ID_PROJECT_EXPLORER); - String explorerViewID = ProductProperties.getProperty(IProductConstants.PERSPECTIVE_EXPLORER_VIEW); // make sure the specified view ID is known - if (PlatformUI.getWorkbench().getViewRegistry().find(explorerViewID) != null) { - folder.addPlaceholder(explorerViewID); - layout.addShowViewShortcut(explorerViewID); - } + if (PlatformUI.getWorkbench().getViewRegistry().find(explorerViewID) != null) + folder.addView(explorerViewID); + else + folder.addView(ProductProperties.ID_PERSPECTIVE_EXPLORER_VIEW); folder.addPlaceholder(JavaScriptUI.ID_TYPE_HIERARCHY); folder.addPlaceholder(IPageLayout.ID_RES_NAV); + folder.addPlaceholder(JavaScriptUI.ID_PACKAGES); IFolderLayout outputfolder= layout.createFolder("bottom", IPageLayout.BOTTOM, (float)0.75, editorArea); //$NON-NLS-1$ outputfolder.addView(IPageLayout.ID_PROBLEM_VIEW); + outputfolder.addView(JavaScriptUI.ID_JAVADOC_VIEW); - outputfolder.addPlaceholder(JavaScriptUI.ID_SOURCE_VIEW); + outputfolder.addView(JavaScriptUI.ID_SOURCE_VIEW); outputfolder.addPlaceholder(TemplatesView.ID); outputfolder.addPlaceholder(NewSearchUI.SEARCH_VIEW_ID); outputfolder.addPlaceholder(IConsoleConstants.ID_CONSOLE_VIEW); @@ -84,18 +83,17 @@ public class JavaPerspectiveFactory implements IPerspectiveFactory { layout.addShowViewShortcut(IPageLayout.ID_RES_NAV); layout.addShowViewShortcut(IPageLayout.ID_TASK_LIST); layout.addShowViewShortcut(IProgressConstants.PROGRESS_VIEW_ID); - layout.addShowViewShortcut(IPageLayout.ID_PROJECT_EXPLORER); - - // new actions - JavaScript project creation wizard + + // new actions - Java project creation wizard layout.addNewWizardShortcut("org.eclipse.wst.jsdt.ui.wizards.JavaProjectWizard"); //$NON-NLS-1$ -// layout.addNewWizardShortcut("org.eclipse.wst.jsdt.ui.wizards.NewPackageCreationWizard"); //$NON-NLS-1$ + layout.addNewWizardShortcut("org.eclipse.wst.jsdt.ui.wizards.NewPackageCreationWizard"); //$NON-NLS-1$ layout.addNewWizardShortcut("org.eclipse.wst.jsdt.ui.wizards.NewClassCreationWizard"); //$NON-NLS-1$ layout.addNewWizardShortcut("org.eclipse.wst.jsdt.ui.NewJSWizard"); //$NON-NLS-1$ -// layout.addNewWizardShortcut("org.eclipse.wst.jsdt.ui.wizards.NewInterfaceCreationWizard"); //$NON-NLS-1$ -// layout.addNewWizardShortcut("org.eclipse.wst.jsdt.ui.wizards.NewEnumCreationWizard"); //$NON-NLS-1$ -// layout.addNewWizardShortcut("org.eclipse.wst.jsdt.ui.wizards.NewAnnotationCreationWizard"); //$NON-NLS-1$ + layout.addNewWizardShortcut("org.eclipse.wst.jsdt.ui.wizards.NewInterfaceCreationWizard"); //$NON-NLS-1$ + layout.addNewWizardShortcut("org.eclipse.wst.jsdt.ui.wizards.NewEnumCreationWizard"); //$NON-NLS-1$ + layout.addNewWizardShortcut("org.eclipse.wst.jsdt.ui.wizards.NewAnnotationCreationWizard"); //$NON-NLS-1$ layout.addNewWizardShortcut("org.eclipse.wst.jsdt.ui.wizards.NewSourceFolderCreationWizard"); //$NON-NLS-1$ -// layout.addNewWizardShortcut("org.eclipse.wst.jsdt.ui.wizards.NewSnippetFileCreationWizard"); //$NON-NLS-1$ + layout.addNewWizardShortcut("org.eclipse.wst.jsdt.ui.wizards.NewSnippetFileCreationWizard"); //$NON-NLS-1$ layout.addNewWizardShortcut("org.eclipse.ui.wizards.new.folder");//$NON-NLS-1$ layout.addNewWizardShortcut("org.eclipse.ui.wizards.new.file");//$NON-NLS-1$ layout.addNewWizardShortcut("org.eclipse.ui.editors.wizards.UntitledTextFileWizard");//$NON-NLS-1$ diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaPluginImages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaPluginImages.java index 35bf3746..3ecfac21 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaPluginImages.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaPluginImages.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -153,6 +153,11 @@ public class JavaPluginImages { public static final String IMG_OBJS_SEARCH_OCCURRENCE= NAME_PREFIX + "occ_match.gif"; //$NON-NLS-1$ public static final String IMG_OBJS_HELP= NAME_PREFIX + "help.gif"; //$NON-NLS-1$ + + public static final String IMG_LOADING_1 = NAME_PREFIX + "loading1.gif"; //$NON-NLS-1$ + public static final String IMG_LOADING_2 = NAME_PREFIX + "loading2.gif"; //$NON-NLS-1$ + public static final String IMG_LOADING_3 = NAME_PREFIX + "loading3.gif"; //$NON-NLS-1$ + public static final String IMG_LOADING_4 = NAME_PREFIX + "loading4.gif"; //$NON-NLS-1$ /* * Set of predefined Image Descriptors. @@ -406,6 +411,11 @@ public class JavaPluginImages { public static final ImageDescriptor DESC_TOOL_NEWSNIPPET= createUnManaged(T_ETOOL, "newsbook_wiz.gif"); //$NON-NLS-1$ public static final ImageDescriptor DESC_TOOL_NEWPACKROOT= createUnManaged(T_ETOOL, "newpackfolder_wiz.gif"); //$NON-NLS-1$ public static final ImageDescriptor DESC_DLCL_NEWPACKROOT= createUnManaged(T_DLCL, "newpackfolder_wiz.gif"); //$NON-NLS-1$ + + public static final ImageDescriptor DESC_TOOL_LOADING_1 = createUnManaged(T_ETOOL, "loading1.gif"); //$NON-NLS-1$ + public static final ImageDescriptor DESC_TOOL_LOADING_2 = createUnManaged(T_ETOOL, "loading2.gif"); //$NON-NLS-1$ + public static final ImageDescriptor DESC_TOOL_LOADING_3 = createUnManaged(T_ETOOL, "loading3.gif"); //$NON-NLS-1$ + public static final ImageDescriptor DESC_TOOL_LOADING_4 = createUnManaged(T_ETOOL, "loading4.gif"); //$NON-NLS-1$ public static final ImageDescriptor DESC_TOOL_CLASSPATH_ORDER= createUnManaged(T_OBJ, "cp_order_obj.gif"); //$NON-NLS-1$ public static final ImageDescriptor DESC_ELCL_COLLAPSEALL= createUnManaged(T_ELCL, "collapseall.gif"); //$NON-NLS-1$ diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaScriptPlugin.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaScriptPlugin.java index 724808bc..475b8a31 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaScriptPlugin.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaScriptPlugin.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaTaskListAdapter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaTaskListAdapter.java index 601c06b9..34b6eea8 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaTaskListAdapter.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaTaskListAdapter.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -22,8 +22,12 @@ public class JavaTaskListAdapter implements ITaskListResourceAdapter { * @see ITaskListResourceAdapter#getAffectedResource(IAdaptable) */ public IResource getAffectedResource(IAdaptable element) { + IResource resource= (IResource) element.getAdapter(IResource.class); + if (resource != null) + return resource; + IJavaScriptElement java = (IJavaScriptElement) element; - IResource resource= java.getResource(); + resource= java.getResource(); if (resource != null) return resource; diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaUIMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaUIMessages.java index 0864494e..0e2c428b 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaUIMessages.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaUIMessages.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaUIMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaUIMessages.properties index f920aab0..fd41121d 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaUIMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/JavaUIMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2008 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR JavaPlugin_internal_error=Internal Error JavaElementProperties_name=Name diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/Logger.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/Logger.java index 133352f7..fa7f8362 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/Logger.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/Logger.java @@ -138,6 +138,10 @@ public class Logger { _log(ERROR, message, exception); } + public static void logException(int level, Throwable exception) { + _log(level, exception.getMessage(), exception); + } + public static void logException(Throwable exception) { _log(ERROR, exception.getMessage(), exception); } diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/ProductProperties.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/ProductProperties.java index c217cf0b..d8a80016 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/ProductProperties.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/ProductProperties.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2010 IBM Corporation and others. + * Copyright (c) 2005, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/AbstractToggleLinkingAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/AbstractToggleLinkingAction.java index 72dfdc57..3bf82ad8 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/AbstractToggleLinkingAction.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/AbstractToggleLinkingAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/ActionMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/ActionMessages.properties index 787a9d7c..cb598e3b 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/ActionMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/ActionMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2008 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -9,6 +9,8 @@ # IBM Corporation - initial API and implementation # Sebastian Davids - Bug 114276 ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR OpenWithMenu_label=Open Wit&h RefactorMenu_label=Refac&tor diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/BlockCommentAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/BlockCommentAction.java index 76b0bf74..94c6c33c 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/BlockCommentAction.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/BlockCommentAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/ConfigureContainerAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/ConfigureContainerAction.java index cc778104..6321cb9a 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/ConfigureContainerAction.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/ConfigureContainerAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -17,16 +17,12 @@ import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.action.IAction; import org.eclipse.jface.operation.IRunnableContext; import org.eclipse.jface.operation.IRunnableWithProgress; -import org.eclipse.jface.viewers.AbstractTreeViewer; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.StructuredViewer; -import org.eclipse.jface.viewers.TreePath; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IObjectActionDelegate; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.navigator.CommonViewer; import org.eclipse.wst.jsdt.core.IIncludePathEntry; import org.eclipse.wst.jsdt.core.IJavaScriptProject; import org.eclipse.wst.jsdt.core.JavaScriptModelException; @@ -55,22 +51,8 @@ public class ConfigureContainerAction implements IObjectActionDelegate { */ public void run(IAction action) { if (fCurrentSelection instanceof IStructuredSelection) { - JsGlobalScopeContainer container = (JsGlobalScopeContainer) ((IStructuredSelection) fCurrentSelection).getFirstElement(); + JsGlobalScopeContainer container= (JsGlobalScopeContainer) ((IStructuredSelection) fCurrentSelection).getFirstElement(); openWizard(container.getClasspathEntry(), container.getLabel(), container.getJavaProject()); - StructuredViewer viewer = (CommonViewer) fPart.getAdapter(StructuredViewer.class); - if (viewer == null) { - viewer = (CommonViewer) fPart.getAdapter(CommonViewer.class); - } - if (viewer != null) { - TreePath[] expanded = null; - if (viewer instanceof AbstractTreeViewer) { - expanded = ((AbstractTreeViewer) viewer).getExpandedTreePaths(); - } - viewer.refresh(container.getJavaProject().getProject(), true); - if (expanded != null && viewer instanceof AbstractTreeViewer) { - ((AbstractTreeViewer) viewer).setExpandedTreePaths(expanded); - } - } } } diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/FoldingMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/FoldingMessages.java index c4ad9d9d..e8ea35b3 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/FoldingMessages.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/FoldingMessages.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/FoldingMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/FoldingMessages.properties index b801ed91..5a7adbe1 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/FoldingMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/FoldingMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2005, 2007 IBM Corporation and others. +# Copyright (c) 2005, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,9 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_NONE + Projection.Toggle.label= &Enable Folding Projection.Toggle.tooltip= Toggles Folding Projection.Toggle.description= Toggles folding for the current editor diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/QuickMenuAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/QuickMenuAction.java index c21fe3bc..3206fa0e 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/QuickMenuAction.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/QuickMenuAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/SelectionConverter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/SelectionConverter.java index 96342955..bfa9fd0d 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/SelectionConverter.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/actions/SelectionConverter.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -295,7 +295,7 @@ public class SelectionConverter { if (nResults == 1) return elements[0]; - int flags= JavaScriptElementLabelProvider.SHOW_DEFAULT | JavaScriptElementLabelProvider.SHOW_QUALIFIED | JavaScriptElementLabelProvider.SHOW_ROOT; + int flags= JavaScriptElementLabelProvider.SHOW_DEFAULT | JavaScriptElementLabelProvider.SHOW_POST_QUALIFIED | JavaScriptElementLabelProvider.SHOW_ROOT; ElementListSelectionDialog dialog= new ElementListSelectionDialog(shell, new JavaScriptElementLabelProvider(flags)); dialog.setTitle(title); diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/IPackagesViewViewer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/IPackagesViewViewer.java index 656da368..4f2f0b2c 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/IPackagesViewViewer.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/IPackagesViewViewer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/JavaBrowsingMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/JavaBrowsingMessages.properties index dfbd8d91..67ffb16e 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/JavaBrowsingMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/JavaBrowsingMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2007 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR JavaBrowsingPart_toolTip= Working Set: {0} JavaBrowsingPart_toolTip2= {0} - Working Set: {1} diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/ToggleLinkingAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/ToggleLinkingAction.java index 61f385b5..28bfa5c8 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/ToggleLinkingAction.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/browsing/ToggleLinkingAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyMessages.properties index 27a9c25b..c861b48b 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/callhierarchy/CallHierarchyMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2007 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -11,6 +11,8 @@ # Michael Fraenkel (fraenkel@us.ibm.com) - patch # (report 60714: Call Hierarchy: display search scope in view title) ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR ToggleCallModeAction_callers_label=&Caller Hierarchy ToggleCallModeAction_callers_tooltip=Show Caller Hierarchy diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/AddFromHistoryAction.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/AddFromHistoryAction.properties index c555bb96..92b0abe9 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/AddFromHistoryAction.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/AddFromHistoryAction.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2007 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR title= Restore JavaScript Element from Local History width= 800 diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/CompareAction.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/CompareAction.properties index 24ca1da8..11ebdd32 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/CompareAction.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/CompareAction.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2007 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR title= Compare JavaScript Elements width= 800 diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/CompareMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/CompareMessages.java index 2991f498..ca1f9b9d 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/CompareMessages.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/CompareMessages.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/CompareMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/CompareMessages.properties index 71cd7b80..5fcd2e03 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/CompareMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/CompareMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2008 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,7 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### - +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_NONE # # Title of Java source compare viewer diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/CompareWithEditionAction.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/CompareWithEditionAction.properties index 884cdaeb..165a871a 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/CompareWithEditionAction.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/CompareWithEditionAction.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2007 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR title= Compare JavaScript Element with Local History width= 800 diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/EclipsePreferencesAdapter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/EclipsePreferencesAdapter.java index a74b060c..50b0d074 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/EclipsePreferencesAdapter.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/EclipsePreferencesAdapter.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaTokenComparator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaTokenComparator.java index 340fb536..ef9457aa 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaTokenComparator.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/JavaTokenComparator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/ReplaceWithEditionAction.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/ReplaceWithEditionAction.properties index 911b6d20..45aca948 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/ReplaceWithEditionAction.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/compare/ReplaceWithEditionAction.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2007 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR title= Replace JavaScript Element from Local History width= 800 diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/DialogsMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/DialogsMessages.properties index 8684258e..118a82e4 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/DialogsMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/DialogsMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2007 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -9,6 +9,8 @@ # IBM Corporation - initial API and implementation # Sebastian Davids - Bug 114276 ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_NONE SortMembersMessageDialog_dialog_title=Sort Members SortMembersMessageDialog_description=The order of the sort may be configured on the Members Sort Order preference page. diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/FilteredTypesSelectionDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/FilteredTypesSelectionDialog.java index b2738a3c..234d649b 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/FilteredTypesSelectionDialog.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/FilteredTypesSelectionDialog.java @@ -1,1649 +1,1682 @@ -/******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.jsdt.internal.ui.dialogs; - -import java.io.IOException; -import java.io.StringReader; -import java.io.StringWriter; -import java.lang.reflect.InvocationTargetException; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.SubProgressMonitor; -import org.eclipse.core.runtime.jobs.IJobManager; -import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.action.IMenuManager; -import org.eclipse.jface.dialogs.IDialogSettings; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.jface.operation.IRunnableContext; -import org.eclipse.jface.operation.IRunnableWithProgress; -import org.eclipse.jface.resource.ImageDescriptor; -import org.eclipse.jface.text.ITextSelection; -import org.eclipse.jface.util.IPropertyChangeListener; -import org.eclipse.jface.util.PropertyChangeEvent; -import org.eclipse.jface.viewers.ILabelDecorator; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.LabelProvider; -import org.eclipse.jface.viewers.LabelProviderChangedEvent; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Item; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.swt.widgets.Table; -import org.eclipse.swt.widgets.Text; -import org.eclipse.ui.IMemento; -import org.eclipse.ui.IWorkbenchWindow; -import org.eclipse.ui.IWorkingSet; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.WorkbenchException; -import org.eclipse.ui.XMLMemento; -import org.eclipse.ui.dialogs.FilteredItemsSelectionDialog; -import org.eclipse.ui.dialogs.ISelectionStatusValidator; -import org.eclipse.ui.dialogs.PreferencesUtil; -import org.eclipse.ui.dialogs.SearchPattern; -import org.eclipse.wst.jsdt.core.IPackageFragmentRoot; -import org.eclipse.wst.jsdt.core.IType; -import org.eclipse.wst.jsdt.core.JavaScriptConventions; -import org.eclipse.wst.jsdt.core.JavaScriptCore; -import org.eclipse.wst.jsdt.core.JavaScriptModelException; -import org.eclipse.wst.jsdt.core.WorkingCopyOwner; -import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants; -import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope; -import org.eclipse.wst.jsdt.core.search.SearchEngine; -import org.eclipse.wst.jsdt.core.search.TypeNameMatch; -import org.eclipse.wst.jsdt.core.search.TypeNameMatchRequestor; -import org.eclipse.wst.jsdt.core.search.TypeNameRequestor; -import org.eclipse.wst.jsdt.internal.corext.util.Messages; -import org.eclipse.wst.jsdt.internal.corext.util.OpenTypeHistory; -import org.eclipse.wst.jsdt.internal.corext.util.Strings; -import org.eclipse.wst.jsdt.internal.corext.util.TypeFilter; -import org.eclipse.wst.jsdt.internal.corext.util.TypeInfoRequestorAdapter; -import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds; -import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin; -import org.eclipse.wst.jsdt.internal.ui.JavaUIMessages; -import org.eclipse.wst.jsdt.internal.ui.preferences.TypeFilterPreferencePage; -import org.eclipse.wst.jsdt.internal.ui.search.JavaSearchScopeFactory; -import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler; -import org.eclipse.wst.jsdt.internal.ui.util.TypeNameMatchLabelProvider; -import org.eclipse.wst.jsdt.internal.ui.viewsupport.ColoredJavaElementLabels; -import org.eclipse.wst.jsdt.internal.ui.viewsupport.ColoredString; -import org.eclipse.wst.jsdt.internal.ui.viewsupport.ColoredViewersManager; -import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider; -import org.eclipse.wst.jsdt.internal.ui.viewsupport.OwnerDrawSupport; -import org.eclipse.wst.jsdt.internal.ui.workingsets.WorkingSetFilterActionGroup; -import org.eclipse.wst.jsdt.launching.IVMInstall; -import org.eclipse.wst.jsdt.launching.IVMInstallType; -import org.eclipse.wst.jsdt.launching.JavaRuntime; -import org.eclipse.wst.jsdt.launching.LibraryLocation; -import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels; -import org.eclipse.wst.jsdt.ui.JavaScriptUI; -import org.eclipse.wst.jsdt.ui.dialogs.ITypeInfoFilterExtension; -import org.eclipse.wst.jsdt.ui.dialogs.ITypeInfoImageProvider; -import org.eclipse.wst.jsdt.ui.dialogs.ITypeSelectionComponent; -import org.eclipse.wst.jsdt.ui.dialogs.TypeSelectionExtension; - -/** - * Shows a list of Java types to the user with a text entry field for a string - * pattern used to filter the list of types. - * - * - */ -public class FilteredTypesSelectionDialog extends FilteredItemsSelectionDialog implements ITypeSelectionComponent { - - /** - * Disabled "Show Container for Duplicates because of - * https://bugs.eclipse.org/bugs/show_bug.cgi?id=184693 . - */ - private static final boolean BUG_184693= true; - - private static final String DIALOG_SETTINGS= "org.eclipse.wst.jsdt.internal.ui.dialogs.FilteredTypesSelectionDialog"; //$NON-NLS-1$ - - private static final String SHOW_CONTAINER_FOR_DUPLICATES= "ShowContainerForDuplicates"; //$NON-NLS-1$ - - private static final String WORKINGS_SET_SETTINGS= "WorkingSet"; //$NON-NLS-1$ - - private WorkingSetFilterActionGroup fFilterActionGroup; - - private final TypeItemLabelProvider fTypeInfoLabelProvider; - - private String fTitle; - - private ShowContainerForDuplicatesAction fShowContainerForDuplicatesAction; - - private IJavaScriptSearchScope fSearchScope; - - private boolean fAllowScopeSwitching; - - private final int fElementKinds; - - private final ITypeInfoFilterExtension fFilterExtension; - - private final TypeSelectionExtension fExtension; - - private ISelectionStatusValidator fValidator; - - private final TypeInfoUtil fTypeInfoUtil; - - private static boolean fgFirstTime= true; - - private final TypeItemsComparator fTypeItemsComparator; - - private int fTypeFilterVersion= 0; - - /** - * Creates new FilteredTypesSelectionDialog instance - * - * @param parent - * shell to parent the dialog on - * @param multi - * true if multiple selection is allowed - * @param context - * context used to execute long-running operations associated - * with this dialog - * @param scope - * scope used when searching for types - * @param elementKinds - * flags defining nature of searched elements; the only valid - * values are: IJavaScriptSearchConstants.TYPE - * IJavaScriptSearchConstants.ANNOTATION_TYPE - * IJavaScriptSearchConstants.INTERFACE - * IJavaScriptSearchConstants.ENUM - * IJavaScriptSearchConstants.CLASS_AND_INTERFACE - * IJavaScriptSearchConstants.CLASS_AND_ENUM. - * Please note that the bitwise OR combination of the elementary - * constants is not supported. - */ - public FilteredTypesSelectionDialog(Shell parent, boolean multi, IRunnableContext context, IJavaScriptSearchScope scope, int elementKinds) { - this(parent, multi, context, scope, elementKinds, null); - } - - /** - * Creates new FilteredTypesSelectionDialog instance. - * - * @param shell - * shell to parent the dialog on - * @param multi - * true if multiple selection is allowed - * @param context - * context used to execute long-running operations associated - * with this dialog - * @param scope - * scope used when searching for types. If the scope is null, - * then workspace is scope is used as default, and the user can - * choose a working set as scope. - * @param elementKinds - * flags defining nature of searched elements; the only valid - * values are: IJavaScriptSearchConstants.TYPE - * IJavaScriptSearchConstants.ANNOTATION_TYPE - * IJavaScriptSearchConstants.INTERFACE - * IJavaScriptSearchConstants.ENUM - * IJavaScriptSearchConstants.CLASS_AND_INTERFACE - * IJavaScriptSearchConstants.CLASS_AND_ENUM. - * Please note that the bitwise OR combination of the elementary - * constants is not supported. - * @param extension - * an extension of the standard type selection dialog; See - * {@link TypeSelectionExtension} - */ - public FilteredTypesSelectionDialog(Shell shell, boolean multi, IRunnableContext context, IJavaScriptSearchScope scope, int elementKinds, TypeSelectionExtension extension) { - super(shell, multi); - - setSelectionHistory(new TypeSelectionHistory()); - - if (scope == null) { - fAllowScopeSwitching= true; - scope= SearchEngine.createWorkspaceScope(); - } - PlatformUI.getWorkbench().getHelpSystem().setHelp(shell, IJavaHelpContextIds.TYPE_SELECTION_DIALOG2); - - fElementKinds= elementKinds; - fExtension= extension; - fFilterExtension= (extension == null) ? null : extension.getFilterExtension(); - fSearchScope= scope; - - if (extension != null) { - fValidator= extension.getSelectionValidator(); - } - - fTypeInfoUtil= new TypeInfoUtil(extension != null ? extension.getImageProvider() : null); - - fTypeInfoLabelProvider= new TypeItemLabelProvider(); - - setListLabelProvider(fTypeInfoLabelProvider); - setListSelectionLabelDecorator(fTypeInfoLabelProvider); - setDetailsLabelProvider(new TypeItemDetailsLabelProvider(fTypeInfoUtil)); - - fTypeItemsComparator= new TypeItemsComparator(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.dialogs.SelectionDialog#setTitle(java.lang.String) - */ - public void setTitle(String title) { - super.setTitle(title); - fTitle= title; - } - - /** - * Adds or replaces subtitle of the dialog - * - * @param text - * the new subtitle for this dialog - */ - private void setSubtitle(String text) { - if (text == null || text.length() == 0) { - getShell().setText(fTitle); - } else { - getShell().setText(Messages.format(JavaUIMessages.FilteredTypeSelectionDialog_titleFormat, new String[] { fTitle, text })); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.dialogs.AbstractSearchDialog#getDialogSettings() - */ - protected IDialogSettings getDialogSettings() { - IDialogSettings settings= JavaScriptPlugin.getDefault().getDialogSettings().getSection(DIALOG_SETTINGS); - - if (settings == null) { - settings= JavaScriptPlugin.getDefault().getDialogSettings().addNewSection(DIALOG_SETTINGS); - } - - return settings; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.dialogs.AbstractSearchDialog#storeDialog(org.eclipse.jface.dialogs.IDialogSettings) - */ - protected void storeDialog(IDialogSettings settings) { - super.storeDialog(settings); - - if (! BUG_184693) { - settings.put(SHOW_CONTAINER_FOR_DUPLICATES, fShowContainerForDuplicatesAction.isChecked()); - } - - if (fFilterActionGroup != null) { - XMLMemento memento= XMLMemento.createWriteRoot("workingSet"); //$NON-NLS-1$ - fFilterActionGroup.saveState(memento); - fFilterActionGroup.dispose(); - StringWriter writer= new StringWriter(); - try { - memento.save(writer); - settings.put(WORKINGS_SET_SETTINGS, writer.getBuffer().toString()); - } catch (IOException e) { - // don't do anything. Simply don't store the settings - JavaScriptPlugin.log(e); - } - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.dialogs.AbstractSearchDialog#restoreDialog(org.eclipse.jface.dialogs.IDialogSettings) - */ - protected void restoreDialog(IDialogSettings settings) { - super.restoreDialog(settings); - - if (! BUG_184693) { - boolean showContainer= settings.getBoolean(SHOW_CONTAINER_FOR_DUPLICATES); - fShowContainerForDuplicatesAction.setChecked(showContainer); - fTypeInfoLabelProvider.setContainerInfo(showContainer); - } else { - fTypeInfoLabelProvider.setContainerInfo(true); - } - - if (fAllowScopeSwitching) { - String setting= settings.get(WORKINGS_SET_SETTINGS); - if (setting != null) { - try { - IMemento memento= XMLMemento.createReadRoot(new StringReader(setting)); - fFilterActionGroup.restoreState(memento); - } catch (WorkbenchException e) { - // don't do anything. Simply don't restore the settings - JavaScriptPlugin.log(e); - } - } - IWorkingSet ws= fFilterActionGroup.getWorkingSet(); - if (ws == null || (ws.isAggregateWorkingSet() && ws.isEmpty())) { - setSearchScope(SearchEngine.createWorkspaceScope()); - setSubtitle(null); - } else { - setSearchScope(JavaSearchScopeFactory.getInstance().createJavaSearchScope(ws, true)); - setSubtitle(ws.getLabel()); - } - } - - // TypeNameMatch[] types = OpenTypeHistory.getInstance().getTypeInfos(); - // - // for (int i = 0; i < types.length; i++) { - // TypeNameMatch type = types[i]; - // accessedHistoryItem(type); - // } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.dialogs.AbstractSearchDialog#fillViewMenu(org.eclipse.jface.action.IMenuManager) - */ - protected void fillViewMenu(IMenuManager menuManager) { - super.fillViewMenu(menuManager); - - if (! BUG_184693) { - fShowContainerForDuplicatesAction= new ShowContainerForDuplicatesAction(); - menuManager.add(fShowContainerForDuplicatesAction); - } - if (fAllowScopeSwitching) { - fFilterActionGroup= new WorkingSetFilterActionGroup(getShell(), JavaScriptPlugin.getActivePage(), new IPropertyChangeListener() { - public void propertyChange(PropertyChangeEvent event) { - IWorkingSet ws= (IWorkingSet) event.getNewValue(); - if (ws == null || (ws.isAggregateWorkingSet() && ws.isEmpty())) { - setSearchScope(SearchEngine.createWorkspaceScope()); - setSubtitle(null); - } else { - setSearchScope(JavaSearchScopeFactory.getInstance().createJavaSearchScope(ws, true)); - setSubtitle(ws.getLabel()); - } - - applyFilter(); - } - }); - fFilterActionGroup.fillViewMenu(menuManager); - } - // 335480 - 'Open JavaScript Type' dialog suggest using type filters even though they don't exist -// menuManager.add(new Separator()); -// menuManager.add(new TypeFiltersPreferencesAction()); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#createExtendedContentArea(org.eclipse.swt.widgets.Composite) - */ - protected Control createExtendedContentArea(Composite parent) { - Control addition= null; - - if (fExtension != null) { - - addition= fExtension.createContentArea(parent); - if (addition != null) { - GridData gd= new GridData(GridData.FILL_HORIZONTAL); - gd.horizontalSpan= 2; - addition.setLayoutData(gd); - - } - - fExtension.initialize(this); - } - - return addition; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.dialogs.SelectionDialog#setResult(java.util.List) - */ - protected void setResult(List newResult) { - - List resultToReturn= new ArrayList(); - - for (int i= 0; i < newResult.size(); i++) { - if (newResult.get(i) instanceof TypeNameMatch) { - IType type= ((TypeNameMatch) newResult.get(i)).getType(); - if (type.exists()) { - // items are added to history in the - // org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#computeResult() - // method - resultToReturn.add(type); - } else { - TypeNameMatch typeInfo= (TypeNameMatch) newResult.get(i); - IPackageFragmentRoot root= typeInfo.getPackageFragmentRoot(); - String containerName= JavaScriptElementLabels.getElementLabel(root, JavaScriptElementLabels.ROOT_QUALIFIED); - String message= Messages.format(JavaUIMessages.FilteredTypesSelectionDialog_dialogMessage, new String[] { typeInfo.getFullyQualifiedName(), containerName }); - MessageDialog.openError(getShell(), fTitle, message); - getSelectionHistory().remove(typeInfo); - } - } - } - - super.setResult(resultToReturn); - } - - /* - * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#create() - */ - public void create() { - super.create(); - Control patternControl= getPatternControl(); - if (patternControl instanceof Text) { - TextFieldNavigationHandler.install((Text) patternControl); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.window.Window#open() - */ - public int open() { - if (getInitialPattern() == null) { - IWorkbenchWindow window= JavaScriptPlugin.getActiveWorkbenchWindow(); - if (window != null) { - ISelection selection= window.getSelectionService().getSelection(); - if (selection instanceof ITextSelection) { - String text= ((ITextSelection) selection).getText(); - if (text != null) { - text= text.trim(); - if (text.length() > 0 && JavaScriptConventions.validateJavaScriptTypeName(text, JavaScriptCore.VERSION_1_3, JavaScriptCore.VERSION_1_3).isOK()) { - setInitialPattern(text, FULL_SELECTION); - } - } - } - } - } - return super.open(); - } - - /** - * Sets a new validator. - * - * @param validator - * the new validator - */ - public void setValidator(ISelectionStatusValidator validator) { - fValidator= validator; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#createFilter() - */ - protected ItemsFilter createFilter() { - return new TypeItemsFilter(fSearchScope, fElementKinds, fFilterExtension); - } - - protected Control createContents(Composite parent) { - Control contents= super.createContents(parent); - if (ColoredViewersManager.showColoredLabels()) { - if (contents instanceof Composite) { - Table listControl= findTableControl((Composite) contents); - if (listControl != null) { - installOwnerDraw(listControl); - } - } - } - return contents; - } - - private void installOwnerDraw(Table tableControl) { - new OwnerDrawSupport(tableControl) { // installs the owner draw listeners - public ColoredString getColoredLabel(Item item) { - String text= item.getText(); - ColoredString str= new ColoredString(text); - int index= text.indexOf('-'); - if (index != -1) { - str.colorize(index, str.length() - index, ColoredJavaElementLabels.QUALIFIER_STYLE); - } - return str; - } - - public Color getColor(String foregroundColorName, Display display) { - return PlatformUI.getWorkbench().getThemeManager().getCurrentTheme().getColorRegistry().get(foregroundColorName); - } - }; - } - - private Table findTableControl(Composite composite) { - Control[] children= composite.getChildren(); - for (int i= 0; i < children.length; i++) { - Control curr= children[i]; - if (curr instanceof Table) { - return (Table) curr; - } else if (curr instanceof Composite) { - Table res= findTableControl((Composite) curr); - if (res != null) { - return res; - } - } - } - return null; - } - - - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#fillContentProvider(org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.AbstractContentProvider, - * org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.ItemsFilter, - * org.eclipse.core.runtime.IProgressMonitor) - */ - protected void fillContentProvider(AbstractContentProvider provider, ItemsFilter itemsFilter, IProgressMonitor progressMonitor) throws CoreException { - TypeItemsFilter typeSearchFilter= (TypeItemsFilter) itemsFilter; - TypeSearchRequestor requestor= new TypeSearchRequestor(provider, typeSearchFilter); - SearchEngine engine= new SearchEngine((WorkingCopyOwner) null); - String packPattern= typeSearchFilter.getPackagePattern(); - progressMonitor.setTaskName(JavaUIMessages.FilteredTypesSelectionDialog_searchJob_taskName); - - /* - * Setting the filter into match everything mode avoids filtering twice - * by the same pattern (the search engine only provides filtered - * matches). For the case when the pattern is a camel case pattern with - * a terminator, the filter is not set to match everything mode because - * jdt.core's SearchPattern does not support that case. - */ - String typePattern= itemsFilter.getPattern(); - int matchRule= typeSearchFilter.getMatchRule(); - if (matchRule == SearchPattern.RULE_CAMELCASE_MATCH) { - // If the pattern is empty, the RULE_BLANK_MATCH will be chosen, so we don't have to check the pattern length - char lastChar= typePattern.charAt(typePattern.length() - 1); - - if (lastChar == '<' || lastChar == ' ') { - typePattern= typePattern.substring(0, typePattern.length() - 1); - } else { - typeSearchFilter.setMatchEverythingMode(true); - } - } else { - typeSearchFilter.setMatchEverythingMode(true); - } - - try { - engine.searchAllTypeNames(packPattern == null ? null : packPattern.toCharArray(), - typeSearchFilter.getPackageFlags(), //TODO: https://bugs.eclipse.org/bugs/show_bug.cgi?id=176017 - typePattern.toCharArray(), - matchRule, //TODO: https://bugs.eclipse.org/bugs/show_bug.cgi?id=176017 - typeSearchFilter.getElementKind(), - typeSearchFilter.getSearchScope(), - requestor, - IJavaScriptSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, - progressMonitor); - } finally { - typeSearchFilter.setMatchEverythingMode(false); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#getItemsComparator() - */ - protected Comparator getItemsComparator() { - return fTypeItemsComparator; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#getElementName(java.lang.Object) - */ - public String getElementName(Object item) { - TypeNameMatch type= (TypeNameMatch) item; - return fTypeInfoUtil.getText(type); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#validateItem(java.lang.Object) - */ - protected IStatus validateItem(Object item) { - - if (item == null) - return new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), IStatus.ERROR, "", null); //$NON-NLS-1$ - - if (fValidator != null) { - IType type= ((TypeNameMatch) item).getType(); - if (!type.exists()) - return new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), IStatus.ERROR, Messages.format(JavaUIMessages.FilteredTypesSelectionDialog_error_type_doesnot_exist, ((TypeNameMatch) item).getFullyQualifiedName()), null); - Object[] elements= { type }; - return fValidator.validate(elements); - } else - return new Status(IStatus.OK, JavaScriptPlugin.getPluginId(), IStatus.OK, "", null); //$NON-NLS-1$ - } - - /** - * Sets search scope used when searching for types. - * - * @param scope - * the new scope - */ - private void setSearchScope(IJavaScriptSearchScope scope) { - fSearchScope= scope; - } - - /* - * We only have to ensure history consistency here since the search engine - * takes care of working copies. - */ - private static class ConsistencyRunnable implements IRunnableWithProgress { - public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { - if (fgFirstTime) { - // Join the initialize after load job. - IJobManager manager= Job.getJobManager(); - manager.join(JavaScriptUI.ID_PLUGIN, monitor); - } - OpenTypeHistory history= OpenTypeHistory.getInstance(); - if (fgFirstTime || history.isEmpty()) { - if (history.needConsistencyCheck()) { - monitor.beginTask(JavaUIMessages.TypeSelectionDialog_progress_consistency, 100); - refreshSearchIndices(new SubProgressMonitor(monitor, 90)); - history.checkConsistency(new SubProgressMonitor(monitor, 10)); - } else { - refreshSearchIndices(monitor); - } - monitor.done(); - fgFirstTime= false; - } else { - history.checkConsistency(monitor); - } - } - public static boolean needsExecution() { - OpenTypeHistory history= OpenTypeHistory.getInstance(); - return fgFirstTime || history.isEmpty() || history.needConsistencyCheck(); - } - private void refreshSearchIndices(IProgressMonitor monitor) throws InvocationTargetException { - try { - new SearchEngine().searchAllTypeNames( - null, - 0, - // make sure we search a concrete name. This is faster according to Kent - "_______________".toCharArray(), //$NON-NLS-1$ - SearchPattern.RULE_EXACT_MATCH | SearchPattern.RULE_CASE_SENSITIVE, - IJavaScriptSearchConstants.ENUM, - SearchEngine.createWorkspaceScope(), - new TypeNameRequestor() {}, - IJavaScriptSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, - monitor); - } catch (JavaScriptModelException e) { - throw new InvocationTargetException(e); - } - } - } - - /* - * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#reloadCache(boolean, org.eclipse.core.runtime.IProgressMonitor) - */ - public void reloadCache(boolean checkDuplicates, IProgressMonitor monitor) { - IProgressMonitor remainingMonitor; - if (ConsistencyRunnable.needsExecution()) { - monitor.beginTask(JavaUIMessages.TypeSelectionDialog_progress_consistency, 10); - try { - ConsistencyRunnable runnable= new ConsistencyRunnable(); - runnable.run(new SubProgressMonitor(monitor, 1)); - } catch (InvocationTargetException e) { - ExceptionHandler.handle(e, JavaUIMessages.TypeSelectionDialog_error3Title, JavaUIMessages.TypeSelectionDialog_error3Message); - close(); - return; - } catch (InterruptedException e) { - // cancelled by user - close(); - return; - } - remainingMonitor= new SubProgressMonitor(monitor, 9); - } else { - remainingMonitor= monitor; - } - super.reloadCache(checkDuplicates, remainingMonitor); - monitor.done(); - } - - /* - * @see org.eclipse.wst.jsdt.ui.dialogs.ITypeSelectionComponent#triggerSearch() - */ - public void triggerSearch() { - fTypeFilterVersion++; - applyFilter(); - } - - /** - * The ShowContainerForDuplicatesAction provides means to - * show/hide container information for duplicate elements. - */ - private class ShowContainerForDuplicatesAction extends Action { - - /** - * Creates a new instance of the class - */ - public ShowContainerForDuplicatesAction() { - super(JavaUIMessages.FilteredTypeSelectionDialog_showContainerForDuplicatesAction, IAction.AS_CHECK_BOX); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.Action#run() - */ - public void run() { - fTypeInfoLabelProvider.setContainerInfo(isChecked()); - } - } - - private class TypeFiltersPreferencesAction extends Action { - - public TypeFiltersPreferencesAction() { - super(JavaUIMessages.FilteredTypesSelectionDialog_TypeFiltersPreferencesAction_label); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.action.Action#run() - */ - public void run() { - String typeFilterID= TypeFilterPreferencePage.TYPE_FILTER_PREF_PAGE_ID; - PreferencesUtil.createPreferenceDialogOn(getShell(), typeFilterID, new String[] { typeFilterID }, null).open(); - triggerSearch(); - } - } - - /** - * A LabelProvider for (the table of) types. - */ - private class TypeItemLabelProvider extends LabelProvider implements ILabelDecorator { - - private boolean fContainerInfo; - - - /** - * Construct a new TypeItemLabelProvider. F - */ - public TypeItemLabelProvider() { - - } - - public void setContainerInfo(boolean containerInfo) { - fContainerInfo= containerInfo; - fireLabelProviderChanged(new LabelProviderChangedEvent(this)); - } - - private boolean isInnerType(TypeNameMatch match) { - return match.getTypeQualifiedName().indexOf('.') != -1; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.viewers.LabelProvider#getImage(java.lang.Object) - */ - public Image getImage(Object element) { - if (!(element instanceof TypeNameMatch)) { - return super.getImage(element); - } - - TypeNameMatch type= (TypeNameMatch) element; - - ImageDescriptor iD= JavaElementImageProvider.getTypeImageDescriptor(isInnerType(type), false, type.getModifiers(), false); - - return JavaScriptPlugin.getImageDescriptorRegistry().get(iD); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.viewers.LabelProvider#getText(java.lang.Object) - */ - public String getText(Object element) { - if (!(element instanceof TypeNameMatch)) { - return super.getText(element); - } - - if (fContainerInfo && isDuplicateElement(element)) { - return fTypeInfoUtil.getFullyQualifiedText((TypeNameMatch) element); - } - - if (!fContainerInfo && isDuplicateElement(element)) { - return fTypeInfoUtil.getQualifiedText((TypeNameMatch) element); - } - - return fTypeInfoUtil.getText(element); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.viewers.ILabelDecorator#decorateImage(org.eclipse.swt.graphics.Image, - * java.lang.Object) - */ - public Image decorateImage(Image image, Object element) { - return null; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.viewers.ILabelDecorator#decorateText(java.lang.String, - * java.lang.Object) - */ - public String decorateText(String text, Object element) { - if (!(element instanceof TypeNameMatch)) { - return null; - } - - if (fContainerInfo && isDuplicateElement(element)) { - return fTypeInfoUtil.getFullyQualifiedText((TypeNameMatch) element); - } - - return fTypeInfoUtil.getQualifiedText((TypeNameMatch) element); - } - - } - - /** - * A LabelProvider for the label showing type details. - */ - private static class TypeItemDetailsLabelProvider extends LabelProvider { - - private final TypeNameMatchLabelProvider fLabelProvider= new TypeNameMatchLabelProvider(TypeNameMatchLabelProvider.SHOW_TYPE_CONTAINER_ONLY + TypeNameMatchLabelProvider.SHOW_ROOT_POSTFIX); - - private final TypeInfoUtil fTypeInfoUtil; - - public TypeItemDetailsLabelProvider(TypeInfoUtil typeInfoUtil) { - fTypeInfoUtil= typeInfoUtil; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.viewers.LabelProvider#getImage(java.lang.Object) - */ - public Image getImage(Object element) { - if (element instanceof TypeNameMatch) { - return fLabelProvider.getImage((element)); - } - - return super.getImage(element); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.viewers.LabelProvider#getText(java.lang.Object) - */ - public String getText(Object element) { - if (element instanceof TypeNameMatch) { - return fTypeInfoUtil.getQualificationText((TypeNameMatch) element); - } - - return super.getText(element); - } - } - - private static class TypeInfoUtil { - - private final ITypeInfoImageProvider fProviderExtension; - - private final TypeInfoRequestorAdapter fAdapter= new TypeInfoRequestorAdapter(); - - private final Map fLib2Name= new HashMap(); - - private final String[] fInstallLocations; - - private final String[] fVMNames; - - private boolean fFullyQualifyDuplicates; - - public TypeInfoUtil(ITypeInfoImageProvider extension) { - fProviderExtension= extension; - List locations= new ArrayList(); - List labels= new ArrayList(); - IVMInstallType[] installs= JavaRuntime.getVMInstallTypes(); - for (int i= 0; i < installs.length; i++) { - processVMInstallType(installs[i], locations, labels); - } - fInstallLocations= (String[]) locations.toArray(new String[locations.size()]); - fVMNames= (String[]) labels.toArray(new String[labels.size()]); - - } - - public void setFullyQualifyDuplicates(boolean value) { - fFullyQualifyDuplicates= value; - } - - private void processVMInstallType(IVMInstallType installType, List locations, List labels) { - if (installType != null) { - IVMInstall[] installs= installType.getVMInstalls(); - boolean isMac= Platform.OS_MACOSX.equals(Platform.getOS()); - final String HOME_SUFFIX= "/Home"; //$NON-NLS-1$ - for (int i= 0; i < installs.length; i++) { - String label= getFormattedLabel(installs[i].getName()); - LibraryLocation[] libLocations= installs[i].getLibraryLocations(); - if (libLocations != null) { - processLibraryLocation(libLocations, label); - } else { - String filePath= installs[i].getInstallLocation().getAbsolutePath(); - // on MacOS X install locations end in an additional - // "/Home" segment; remove it - if (isMac && filePath.endsWith(HOME_SUFFIX)) - filePath= filePath.substring(0, filePath.length() - HOME_SUFFIX.length() + 1); - locations.add(filePath); - labels.add(label); - } - } - } - } - - private void processLibraryLocation(LibraryLocation[] libLocations, String label) { - for (int l= 0; l < libLocations.length; l++) { - LibraryLocation location= libLocations[l]; - fLib2Name.put(location.getSystemLibraryPath().toOSString(), label); - } - } - - private String getFormattedLabel(String name) { - return Messages.format(JavaUIMessages.FilteredTypesSelectionDialog_library_name_format, name); - } - - public String getText(Object element) { - - return ((TypeNameMatch) element).getQualifiedName(); - } - - public String getQualifiedText(TypeNameMatch type) { - StringBuffer result= new StringBuffer(); - result.append(type.getQualifiedName()); - String containerName= type.getTypeContainerName(); - result.append(JavaScriptElementLabels.CONCAT_STRING); - if (containerName.length() > 0) { - result.append(containerName); - } else { - result.append(JavaUIMessages.FilteredTypesSelectionDialog_default_package); - } - return result.toString(); - } - - public String getFullyQualifiedText(TypeNameMatch type) { - StringBuffer result= new StringBuffer(); - result.append(type.getSimpleTypeName()); - String containerName= type.getTypeContainerName(); - if (containerName.length() > 0) { - result.append(JavaScriptElementLabels.CONCAT_STRING); - result.append(containerName); - } - result.append(JavaScriptElementLabels.CONCAT_STRING); - result.append(getContainerName(type)); - return result.toString(); - } - - public String getText(TypeNameMatch last, TypeNameMatch current, TypeNameMatch next) { - StringBuffer result= new StringBuffer(); - int qualifications= 0; - String currentTN= current.getSimpleTypeName(); - result.append(currentTN); - String currentTCN= getTypeContainerName(current); - if (last != null) { - String lastTN= last.getSimpleTypeName(); - String lastTCN= getTypeContainerName(last); - if (currentTCN.equals(lastTCN)) { - if (currentTN.equals(lastTN)) { - result.append(JavaScriptElementLabels.CONCAT_STRING); - result.append(currentTCN); - result.append(JavaScriptElementLabels.CONCAT_STRING); - result.append(getContainerName(current)); - return result.toString(); - } - } else if (currentTN.equals(lastTN)) { - qualifications= 1; - } - } - if (next != null) { - String nextTN= next.getSimpleTypeName(); - String nextTCN= getTypeContainerName(next); - if (currentTCN.equals(nextTCN)) { - if (currentTN.equals(nextTN)) { - result.append(JavaScriptElementLabels.CONCAT_STRING); - result.append(currentTCN); - result.append(JavaScriptElementLabels.CONCAT_STRING); - result.append(getContainerName(current)); - return result.toString(); - } - } else if (currentTN.equals(nextTN)) { - qualifications= 1; - } - } - if (qualifications > 0) { - result.append(JavaScriptElementLabels.CONCAT_STRING); - result.append(currentTCN); - if (fFullyQualifyDuplicates) { - result.append(JavaScriptElementLabels.CONCAT_STRING); - result.append(getContainerName(current)); - } - } - return result.toString(); - } - - public String getQualificationText(TypeNameMatch type) { - StringBuffer result= new StringBuffer(); - String containerName= type.getTypeContainerName(); - if (containerName.length() > 0) { - result.append(containerName); - result.append(JavaScriptElementLabels.CONCAT_STRING); - } - result.append(getContainerName(type)); - return result.toString(); - } - - private boolean isInnerType(TypeNameMatch match) { - return match.getTypeQualifiedName().indexOf('.') != -1; - } - - public ImageDescriptor getImageDescriptor(Object element) { - TypeNameMatch type= (TypeNameMatch) element; - if (fProviderExtension != null) { - fAdapter.setMatch(type); - ImageDescriptor descriptor= fProviderExtension.getImageDescriptor(fAdapter); - if (descriptor != null) - return descriptor; - } - return JavaElementImageProvider.getTypeImageDescriptor(isInnerType(type), false, type.getModifiers(), false); - } - - private String getTypeContainerName(TypeNameMatch info) { - String result= info.getTypeContainerName(); - if (result.length() > 0) - return result; - return JavaUIMessages.FilteredTypesSelectionDialog_default_package; - } - - private String getContainerName(TypeNameMatch type) { - IPackageFragmentRoot root= type.getPackageFragmentRoot(); - if (root.isExternal()) { - String name= root.getPath().toOSString(); - for (int i= 0; i < fInstallLocations.length; i++) { - if (name.startsWith(fInstallLocations[i])) { - return fVMNames[i]; - } - } - String lib= (String) fLib2Name.get(name); - if (lib != null) - return lib; - } - StringBuffer buf= new StringBuffer(); - JavaScriptElementLabels.getPackageFragmentRootLabel(root, JavaScriptElementLabels.ROOT_QUALIFIED | JavaScriptElementLabels.ROOT_VARIABLE, buf); - return buf.toString(); - } - } - - /** - * Filters types using pattern, scope, element kind and filter extension. - */ - private class TypeItemsFilter extends ItemsFilter { - - private final IJavaScriptSearchScope fScope; - - private final boolean fIsWorkspaceScope; - - private final int fElemKind; - - private final ITypeInfoFilterExtension fFilterExt; - - private final TypeInfoRequestorAdapter fAdapter= new TypeInfoRequestorAdapter(); - - private SearchPattern fPackageMatcher; - - private boolean fMatchEverything= false; - - private final int fMyTypeFilterVersion= fTypeFilterVersion; - - /** - * Creates instance of TypeItemsFilter - * - * @param scope - * @param elementKind - * @param extension - */ - public TypeItemsFilter(IJavaScriptSearchScope scope, int elementKind, ITypeInfoFilterExtension extension) { - super(new TypeSearchPattern()); - fScope= scope; - fIsWorkspaceScope= scope == null ? false : scope.equals(SearchEngine.createWorkspaceScope()); - fElemKind= elementKind; - fFilterExt= extension; - String stringPackage= ((TypeSearchPattern) patternMatcher).getPackagePattern(); - if (stringPackage != null) { - fPackageMatcher= new SearchPattern(); - fPackageMatcher.setPattern(stringPackage); - } else { - fPackageMatcher= null; - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.ItemsFilter#isSubFilter(org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.ItemsFilter) - */ - public boolean isSubFilter(ItemsFilter filter) { - if (!super.isSubFilter(filter)) - return false; - TypeItemsFilter typeItemsFilter= (TypeItemsFilter) filter; - if (fScope != typeItemsFilter.getSearchScope()) - return false; - if (fMyTypeFilterVersion != typeItemsFilter.getMyTypeFilterVersion()) - return false; - return getPattern().indexOf('.', filter.getPattern().length()) == -1; - } - - public boolean equalsFilter(ItemsFilter iFilter) { - if (!super.equalsFilter(iFilter)) - return false; - if (!(iFilter instanceof TypeItemsFilter)) - return false; - TypeItemsFilter typeItemsFilter= (TypeItemsFilter) iFilter; - if (fScope != typeItemsFilter.getSearchScope()) - return false; - if (fMyTypeFilterVersion != typeItemsFilter.getMyTypeFilterVersion()) - return false; - return true; - } - - public int getElementKind() { - return fElemKind; - } - - public ITypeInfoFilterExtension getFilterExtension() { - return fFilterExt; - } - - public IJavaScriptSearchScope getSearchScope() { - return fScope; - } - - public int getMyTypeFilterVersion() { - return fMyTypeFilterVersion; - } - - public String getPackagePattern() { - if (fPackageMatcher == null) - return null; - return fPackageMatcher.getPattern(); - } - - public int getPackageFlags() { - if (fPackageMatcher == null) - return SearchPattern.RULE_PREFIX_MATCH; - - return fPackageMatcher.getMatchRule(); - } - - public boolean matchesRawNamePattern(TypeNameMatch type) { - return Strings.startsWithIgnoreCase(type.getSimpleTypeName(), getPattern()); - } - - public boolean matchesCachedResult(TypeNameMatch type) { - if (!(matchesPackage(type) && matchesFilterExtension(type))) - return false; - return matchesName(type); - } - - public boolean matchesHistoryElement(TypeNameMatch type) { - if (!(matchesPackage(type) && matchesModifiers(type) && matchesScope(type) && matchesFilterExtension(type))) - return false; - return matchesName(type); - } - - public boolean matchesFilterExtension(TypeNameMatch type) { - if (fFilterExt == null) - return true; - fAdapter.setMatch(type); - return fFilterExt.select(fAdapter); - } - - private boolean matchesName(TypeNameMatch type) { - return matches(type.getSimpleTypeName()); - } - - private boolean matchesPackage(TypeNameMatch type) { - if (fPackageMatcher == null) - return true; - return fPackageMatcher.matches(type.getPackageName()); - } - - private boolean matchesScope(TypeNameMatch type) { - if (fIsWorkspaceScope) - return true; - return fScope.encloses(type.getType()); - - } - - private boolean matchesModifiers(TypeNameMatch type) { - if (fElemKind == IJavaScriptSearchConstants.TYPE) - return true; - int modifiers= type.getModifiers(); - switch (fElemKind) { - case IJavaScriptSearchConstants.CLASS: - return modifiers == 0; - } - return false; - } - - /** - * Set filter to "match everything" mode. - * - * @param matchEverything if true, {@link #matchItem(Object)} always returns true. - * If false, the filter is enabled. - */ - public void setMatchEverythingMode(boolean matchEverything) { - this.fMatchEverything= matchEverything; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.ItemsFilter#isConsistentItem(java.lang.Object) - */ - public boolean isConsistentItem(Object item) { - return true; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.ItemsFilter#matchItem(java.lang.Object) - */ - public boolean matchItem(Object item) { - - if (fMatchEverything) - return true; - - TypeNameMatch type= (TypeNameMatch) item; - if (!(matchesPackage(type) && matchesModifiers(type) && matchesScope(type) && matchesFilterExtension(type))) - return false; - return matchesName(type); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.ItemsFilter#matchesRawNamePattern(java.lang.Object) - */ - public boolean matchesRawNamePattern(Object item) { - TypeNameMatch type= (TypeNameMatch) item; - return matchesRawNamePattern(type); - } - - } - - /** - * Extends functionality of SearchPatterns - */ - private static class TypeSearchPattern extends SearchPattern { - - private String packagePattern; - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.dialogs.SearchPattern#setPattern(java.lang.String) - */ - public void setPattern(String stringPattern) { - String pattern= stringPattern; - String packPattern= null; - int index= stringPattern.lastIndexOf("."); //$NON-NLS-1$ - if (index != -1) { - packPattern= evaluatePackagePattern(stringPattern.substring(0, index)); - pattern= stringPattern.substring(index + 1); - if (pattern.length() == 0) - pattern= "**"; //$NON-NLS-1$ - } - super.setPattern(pattern); - packagePattern= packPattern; - } - - /* - * Transforms o.e.j to o*.e*.j* - */ - private String evaluatePackagePattern(String s) { - StringBuffer buf= new StringBuffer(); - boolean hasWildCard= false; - for (int i= 0; i < s.length(); i++) { - char ch= s.charAt(i); - if (ch == '.') { - if (!hasWildCard) { - buf.append('*'); - } - hasWildCard= false; - } else if (ch == '*' || ch == '?') { - hasWildCard= true; - } - buf.append(ch); - } - if (!hasWildCard) { - buf.append('*'); - } - return buf.toString(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.dialogs.SearchPattern#isNameCharAllowed(char) - */ - protected boolean isNameCharAllowed(char nameChar) { - return super.isNameCharAllowed(nameChar); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.dialogs.SearchPattern#isPatternCharAllowed(char) - */ - protected boolean isPatternCharAllowed(char patternChar) { - return super.isPatternCharAllowed(patternChar); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.dialogs.SearchPattern#isValidCamelCaseChar(char) - */ - protected boolean isValidCamelCaseChar(char ch) { - return super.isValidCamelCaseChar(ch); - } - - /** - * @return the packagePattern - */ - public String getPackagePattern() { - return packagePattern; - } - - } - - /** - * A TypeSearchRequestor collects matches filtered using - * TypeItemsFilter. The attached content provider is filled - * on the basis of the collected entries (instances of - * TypeNameMatch). - */ - private static class TypeSearchRequestor extends TypeNameMatchRequestor { - private volatile boolean fStop; - - private final AbstractContentProvider fContentProvider; - - private final TypeItemsFilter fTypeItemsFilter; - - public TypeSearchRequestor(AbstractContentProvider contentProvider, TypeItemsFilter typeItemsFilter) { - super(); - fContentProvider= contentProvider; - fTypeItemsFilter= typeItemsFilter; - } - - public void cancel() { - fStop= true; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.jsdt.core.search.TypeNameMatchRequestor#acceptTypeNameMatch(org.eclipse.wst.jsdt.core.search.TypeNameMatch) - */ - public void acceptTypeNameMatch(TypeNameMatch match) { - if (fStop) - return; - if (TypeFilter.isFiltered(match)) - return; - if (fTypeItemsFilter.matchesFilterExtension(match)) - fContentProvider.add(match, fTypeItemsFilter); - } - - } - - /** - * Compares TypeItems is used during sorting - */ - private static class TypeItemsComparator implements Comparator { - - private final Map fLib2Name= new HashMap(); - - private final String[] fInstallLocations; - - private final String[] fVMNames; - - /** - * Creates new instance of TypeItemsComparator - */ - public TypeItemsComparator() { - List locations= new ArrayList(); - List labels= new ArrayList(); - IVMInstallType[] installs= JavaRuntime.getVMInstallTypes(); - for (int i= 0; i < installs.length; i++) { - processVMInstallType(installs[i], locations, labels); - } - fInstallLocations= (String[]) locations.toArray(new String[locations.size()]); - fVMNames= (String[]) labels.toArray(new String[labels.size()]); - } - - private void processVMInstallType(IVMInstallType installType, List locations, List labels) { - if (installType != null) { - IVMInstall[] installs= installType.getVMInstalls(); - boolean isMac= Platform.OS_MACOSX.equals(Platform.getOS()); - final String HOME_SUFFIX= "/Home"; //$NON-NLS-1$ - for (int i= 0; i < installs.length; i++) { - String label= getFormattedLabel(installs[i].getName()); - LibraryLocation[] libLocations= installs[i].getLibraryLocations(); - if (libLocations != null) { - processLibraryLocation(libLocations, label); - } else { - String filePath= installs[i].getInstallLocation().getAbsolutePath(); - // on MacOS X install locations end in an additional - // "/Home" segment; remove it - if (isMac && filePath.endsWith(HOME_SUFFIX)) - filePath= filePath.substring(0, filePath.length() - HOME_SUFFIX.length() + 1); - locations.add(filePath); - labels.add(label); - } - } - } - } - - private void processLibraryLocation(LibraryLocation[] libLocations, String label) { - for (int l= 0; l < libLocations.length; l++) { - LibraryLocation location= libLocations[l]; - fLib2Name.put(location.getSystemLibraryPath().toString(), label); - } - } - - private String getFormattedLabel(String name) { - return MessageFormat.format(JavaUIMessages.FilteredTypesSelectionDialog_library_name_format, new Object[] { name }); - } - - /* - * (non-Javadoc) - * - * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) - */ - public int compare(Object left, Object right) { - - TypeNameMatch leftInfo= (TypeNameMatch) left; - TypeNameMatch rightInfo= (TypeNameMatch) right; - - int result= compareName(leftInfo.getSimpleTypeName(), rightInfo.getSimpleTypeName()); - if (result != 0) - return result; - result= compareTypeContainerName(leftInfo.getTypeContainerName(), rightInfo.getTypeContainerName()); - if (result != 0) - return result; - - int leftCategory= getElementTypeCategory(leftInfo); - int rightCategory= getElementTypeCategory(rightInfo); - if (leftCategory < rightCategory) - return -1; - if (leftCategory > rightCategory) - return +1; - return compareContainerName(leftInfo, rightInfo); - } - - private int compareName(String leftString, String rightString) { - int result= leftString.compareToIgnoreCase(rightString); - if (result != 0 || rightString.length() == 0) { - return result; - } else if (Strings.isLowerCase(leftString.charAt(0)) && !Strings.isLowerCase(rightString.charAt(0))) { - return +1; - } else if (Strings.isLowerCase(rightString.charAt(0)) && !Strings.isLowerCase(leftString.charAt(0))) { - return -1; - } else { - return leftString.compareTo(rightString); - } - } - - private int compareTypeContainerName(String leftString, String rightString) { - int leftLength= leftString.length(); - int rightLength= rightString.length(); - if (leftLength == 0 && rightLength > 0) - return -1; - if (leftLength == 0 && rightLength == 0) - return 0; - if (leftLength > 0 && rightLength == 0) - return +1; - return compareName(leftString, rightString); - } - - private int compareContainerName(TypeNameMatch leftType, TypeNameMatch rightType) { - return getContainerName(leftType).compareTo(getContainerName(rightType)); - } - - private String getContainerName(TypeNameMatch type) { - IPackageFragmentRoot root= type.getPackageFragmentRoot(); - if (root.isExternal()) { - String name= root.getPath().toOSString(); - for (int i= 0; i < fInstallLocations.length; i++) { - if (name.startsWith(fInstallLocations[i])) { - return fVMNames[i]; - } - } - String lib= (String) fLib2Name.get(name); - if (lib != null) - return lib; - } - StringBuffer buf= new StringBuffer(); - JavaScriptElementLabels.getPackageFragmentRootLabel(root, JavaScriptElementLabels.ROOT_QUALIFIED | JavaScriptElementLabels.ROOT_VARIABLE, buf); - return buf.toString(); - } - - private int getElementTypeCategory(TypeNameMatch type) { - try { - if (type.getPackageFragmentRoot().getKind() == IPackageFragmentRoot.K_SOURCE) - return 0; - } catch (JavaScriptModelException e) { - JavaScriptPlugin.log(e); - } - return 1; - } - } - - /** - * Extends the SelectionHistory, providing support for - * OpenTypeHistory. - */ - protected class TypeSelectionHistory extends SelectionHistory { - - /** - * Creates new instance of TypeSelectionHistory - */ - - public TypeSelectionHistory() { - super(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.SelectionHistory#accessed(java.lang.Object) - */ - public synchronized void accessed(Object object) { - super.accessed(object); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.SelectionHistory#remove(java.lang.Object) - */ - public synchronized boolean remove(Object element) { - OpenTypeHistory.getInstance().remove((TypeNameMatch) element); - return super.remove(element); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.SelectionHistory#load(org.eclipse.ui.IMemento) - */ - public void load(IMemento memento) { - TypeNameMatch[] types= OpenTypeHistory.getInstance().getTypeInfos(); - - for (int i= 0; i < types.length; i++) { - TypeNameMatch type= types[i]; - accessed(type); - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.SelectionHistory#save(org.eclipse.ui.IMemento) - */ - public void save(IMemento memento) { - persistHistory(); - } - - /** - * Stores contents of the local history into persistent history - * container. - */ - private synchronized void persistHistory() { - if (getReturnCode() == OK) { - Object[] items= getHistoryItems(); - for (int i= 0; i < items.length; i++) { - OpenTypeHistory.getInstance().accessed((TypeNameMatch) items[i]); - } - } - } - - protected Object restoreItemFromMemento(IMemento element) { - return null; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.SelectionHistory#storeItemToMemento(java.lang.Object, - * org.eclipse.ui.IMemento) - */ - protected void storeItemToMemento(Object item, IMemento element) { - - } - - } - -} +/******************************************************************************* + * Copyright (c) 2000, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.wst.jsdt.internal.ui.dialogs; + +import java.io.IOException; +import java.io.StringReader; +import java.io.StringWriter; +import java.lang.reflect.InvocationTargetException; +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Platform; +import org.eclipse.core.runtime.Status; +import org.eclipse.core.runtime.SubProgressMonitor; +import org.eclipse.core.runtime.jobs.IJobManager; +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.jface.action.Action; +import org.eclipse.jface.action.IAction; +import org.eclipse.jface.action.IMenuManager; +import org.eclipse.jface.dialogs.IDialogSettings; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.operation.IRunnableContext; +import org.eclipse.jface.operation.IRunnableWithProgress; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.jface.text.ITextSelection; +import org.eclipse.jface.util.IPropertyChangeListener; +import org.eclipse.jface.util.PropertyChangeEvent; +import org.eclipse.jface.viewers.ILabelDecorator; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.LabelProvider; +import org.eclipse.jface.viewers.LabelProviderChangedEvent; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Item; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Table; +import org.eclipse.swt.widgets.Text; +import org.eclipse.ui.IMemento; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.IWorkingSet; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.WorkbenchException; +import org.eclipse.ui.XMLMemento; +import org.eclipse.ui.dialogs.FilteredItemsSelectionDialog; +import org.eclipse.ui.dialogs.ISelectionStatusValidator; +import org.eclipse.ui.dialogs.PreferencesUtil; +import org.eclipse.ui.dialogs.SearchPattern; +import org.eclipse.wst.jsdt.core.IPackageFragmentRoot; +import org.eclipse.wst.jsdt.core.IType; +import org.eclipse.wst.jsdt.core.JavaScriptConventions; +import org.eclipse.wst.jsdt.core.JavaScriptCore; +import org.eclipse.wst.jsdt.core.JavaScriptModelException; +import org.eclipse.wst.jsdt.core.WorkingCopyOwner; +import org.eclipse.wst.jsdt.core.compiler.CharOperation; +import org.eclipse.wst.jsdt.core.infer.IInferEngine; +import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchConstants; +import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope; +import org.eclipse.wst.jsdt.core.search.SearchEngine; +import org.eclipse.wst.jsdt.core.search.TypeNameMatch; +import org.eclipse.wst.jsdt.core.search.TypeNameMatchRequestor; +import org.eclipse.wst.jsdt.core.search.TypeNameRequestor; +import org.eclipse.wst.jsdt.internal.corext.util.Messages; +import org.eclipse.wst.jsdt.internal.corext.util.OpenTypeHistory; +import org.eclipse.wst.jsdt.internal.corext.util.Strings; +import org.eclipse.wst.jsdt.internal.corext.util.TypeFilter; +import org.eclipse.wst.jsdt.internal.corext.util.TypeInfoRequestorAdapter; +import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds; +import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin; +import org.eclipse.wst.jsdt.internal.ui.JavaUIMessages; +import org.eclipse.wst.jsdt.internal.ui.preferences.TypeFilterPreferencePage; +import org.eclipse.wst.jsdt.internal.ui.search.JavaSearchScopeFactory; +import org.eclipse.wst.jsdt.internal.ui.util.ExceptionHandler; +import org.eclipse.wst.jsdt.internal.ui.util.TypeNameMatchLabelProvider; +import org.eclipse.wst.jsdt.internal.ui.viewsupport.ColoredJavaElementLabels; +import org.eclipse.wst.jsdt.internal.ui.viewsupport.ColoredString; +import org.eclipse.wst.jsdt.internal.ui.viewsupport.ColoredViewersManager; +import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider; +import org.eclipse.wst.jsdt.internal.ui.viewsupport.OwnerDrawSupport; +import org.eclipse.wst.jsdt.internal.ui.workingsets.WorkingSetFilterActionGroup; +import org.eclipse.wst.jsdt.launching.IVMInstall; +import org.eclipse.wst.jsdt.launching.IVMInstallType; +import org.eclipse.wst.jsdt.launching.JavaRuntime; +import org.eclipse.wst.jsdt.launching.LibraryLocation; +import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels; +import org.eclipse.wst.jsdt.ui.JavaScriptUI; +import org.eclipse.wst.jsdt.ui.dialogs.ITypeInfoFilterExtension; +import org.eclipse.wst.jsdt.ui.dialogs.ITypeInfoImageProvider; +import org.eclipse.wst.jsdt.ui.dialogs.ITypeSelectionComponent; +import org.eclipse.wst.jsdt.ui.dialogs.TypeSelectionExtension; + +/** + * Shows a list of Java types to the user with a text entry field for a string + * pattern used to filter the list of types. + * + * + */ +public class FilteredTypesSelectionDialog extends FilteredItemsSelectionDialog implements ITypeSelectionComponent { + + /** + * Disabled "Show Container for Duplicates because of + * https://bugs.eclipse.org/bugs/show_bug.cgi?id=184693 . + */ + private static final boolean BUG_184693= true; + + private static final String DIALOG_SETTINGS= "org.eclipse.wst.jsdt.internal.ui.dialogs.FilteredTypesSelectionDialog"; //$NON-NLS-1$ + + private static final String SHOW_CONTAINER_FOR_DUPLICATES= "ShowContainerForDuplicates"; //$NON-NLS-1$ + + private static final String WORKINGS_SET_SETTINGS= "WorkingSet"; //$NON-NLS-1$ + + private WorkingSetFilterActionGroup fFilterActionGroup; + + private final TypeItemLabelProvider fTypeInfoLabelProvider; + + private String fTitle; + + private ShowContainerForDuplicatesAction fShowContainerForDuplicatesAction; + + private IJavaScriptSearchScope fSearchScope; + + private boolean fAllowScopeSwitching; + + private final int fElementKinds; + + private final ITypeInfoFilterExtension fFilterExtension; + + private final TypeSelectionExtension fExtension; + + private ISelectionStatusValidator fValidator; + + private final TypeInfoUtil fTypeInfoUtil; + + private static boolean fgFirstTime= true; + + private final TypeItemsComparator fTypeItemsComparator; + + private int fTypeFilterVersion= 0; + + /** + * Creates new FilteredTypesSelectionDialog instance + * + * @param parent + * shell to parent the dialog on + * @param multi + * true if multiple selection is allowed + * @param context + * context used to execute long-running operations associated + * with this dialog + * @param scope + * scope used when searching for types + * @param elementKinds + * flags defining nature of searched elements; the only valid + * values are: IJavaScriptSearchConstants.TYPE + * IJavaScriptSearchConstants.ANNOTATION_TYPE + * IJavaScriptSearchConstants.INTERFACE + * IJavaScriptSearchConstants.ENUM + * IJavaScriptSearchConstants.CLASS_AND_INTERFACE + * IJavaScriptSearchConstants.CLASS_AND_ENUM. + * Please note that the bitwise OR combination of the elementary + * constants is not supported. + */ + public FilteredTypesSelectionDialog(Shell parent, boolean multi, IRunnableContext context, IJavaScriptSearchScope scope, int elementKinds) { + this(parent, multi, context, scope, elementKinds, null); + } + + /** + * Creates new FilteredTypesSelectionDialog instance. + * + * @param shell + * shell to parent the dialog on + * @param multi + * true if multiple selection is allowed + * @param context + * context used to execute long-running operations associated + * with this dialog + * @param scope + * scope used when searching for types. If the scope is null, + * then workspace is scope is used as default, and the user can + * choose a working set as scope. + * @param elementKinds + * flags defining nature of searched elements; the only valid + * values are: IJavaScriptSearchConstants.TYPE + * IJavaScriptSearchConstants.ANNOTATION_TYPE + * IJavaScriptSearchConstants.INTERFACE + * IJavaScriptSearchConstants.ENUM + * IJavaScriptSearchConstants.CLASS_AND_INTERFACE + * IJavaScriptSearchConstants.CLASS_AND_ENUM. + * Please note that the bitwise OR combination of the elementary + * constants is not supported. + * @param extension + * an extension of the standard type selection dialog; See + * {@link TypeSelectionExtension} + */ + public FilteredTypesSelectionDialog(Shell shell, boolean multi, IRunnableContext context, IJavaScriptSearchScope scope, int elementKinds, TypeSelectionExtension extension) { + super(shell, multi); + + setSelectionHistory(new TypeSelectionHistory()); + + if (scope == null) { + fAllowScopeSwitching= true; + scope= SearchEngine.createWorkspaceScope(); + } + PlatformUI.getWorkbench().getHelpSystem().setHelp(shell, IJavaHelpContextIds.TYPE_SELECTION_DIALOG2); + + fElementKinds= elementKinds; + fExtension= extension; + fFilterExtension= (extension == null) ? null : extension.getFilterExtension(); + fSearchScope= scope; + + if (extension != null) { + fValidator= extension.getSelectionValidator(); + } + + fTypeInfoUtil= new TypeInfoUtil(extension != null ? extension.getImageProvider() : null); + + fTypeInfoLabelProvider= new TypeItemLabelProvider(); + + setListLabelProvider(fTypeInfoLabelProvider); + setListSelectionLabelDecorator(fTypeInfoLabelProvider); + setDetailsLabelProvider(new TypeItemDetailsLabelProvider(fTypeInfoUtil)); + + fTypeItemsComparator= new TypeItemsComparator(); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.dialogs.SelectionDialog#setTitle(java.lang.String) + */ + public void setTitle(String title) { + super.setTitle(title); + fTitle= title; + } + + /** + * Adds or replaces subtitle of the dialog + * + * @param text + * the new subtitle for this dialog + */ + private void setSubtitle(String text) { + if (text == null || text.length() == 0) { + getShell().setText(fTitle); + } else { + getShell().setText(Messages.format(JavaUIMessages.FilteredTypeSelectionDialog_titleFormat, new String[] { fTitle, text })); + } + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.dialogs.AbstractSearchDialog#getDialogSettings() + */ + protected IDialogSettings getDialogSettings() { + IDialogSettings settings= JavaScriptPlugin.getDefault().getDialogSettings().getSection(DIALOG_SETTINGS); + + if (settings == null) { + settings= JavaScriptPlugin.getDefault().getDialogSettings().addNewSection(DIALOG_SETTINGS); + } + + return settings; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.dialogs.AbstractSearchDialog#storeDialog(org.eclipse.jface.dialogs.IDialogSettings) + */ + protected void storeDialog(IDialogSettings settings) { + super.storeDialog(settings); + + if (! BUG_184693) { + settings.put(SHOW_CONTAINER_FOR_DUPLICATES, fShowContainerForDuplicatesAction.isChecked()); + } + + if (fFilterActionGroup != null) { + XMLMemento memento= XMLMemento.createWriteRoot("workingSet"); //$NON-NLS-1$ + fFilterActionGroup.saveState(memento); + fFilterActionGroup.dispose(); + StringWriter writer= new StringWriter(); + try { + memento.save(writer); + settings.put(WORKINGS_SET_SETTINGS, writer.getBuffer().toString()); + } catch (IOException e) { + // don't do anything. Simply don't store the settings + JavaScriptPlugin.log(e); + } + } + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.dialogs.AbstractSearchDialog#restoreDialog(org.eclipse.jface.dialogs.IDialogSettings) + */ + protected void restoreDialog(IDialogSettings settings) { + super.restoreDialog(settings); + + if (! BUG_184693) { + boolean showContainer= settings.getBoolean(SHOW_CONTAINER_FOR_DUPLICATES); + fShowContainerForDuplicatesAction.setChecked(showContainer); + fTypeInfoLabelProvider.setContainerInfo(showContainer); + } else { + fTypeInfoLabelProvider.setContainerInfo(true); + } + + if (fAllowScopeSwitching) { + String setting= settings.get(WORKINGS_SET_SETTINGS); + if (setting != null) { + try { + IMemento memento= XMLMemento.createReadRoot(new StringReader(setting)); + fFilterActionGroup.restoreState(memento); + } catch (WorkbenchException e) { + // don't do anything. Simply don't restore the settings + JavaScriptPlugin.log(e); + } + } + IWorkingSet ws= fFilterActionGroup.getWorkingSet(); + if (ws == null || (ws.isAggregateWorkingSet() && ws.isEmpty())) { + setSearchScope(SearchEngine.createWorkspaceScope()); + setSubtitle(null); + } else { + setSearchScope(JavaSearchScopeFactory.getInstance().createJavaSearchScope(ws, true)); + setSubtitle(ws.getLabel()); + } + } + + // TypeNameMatch[] types = OpenTypeHistory.getInstance().getTypeInfos(); + // + // for (int i = 0; i < types.length; i++) { + // TypeNameMatch type = types[i]; + // accessedHistoryItem(type); + // } + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.dialogs.AbstractSearchDialog#fillViewMenu(org.eclipse.jface.action.IMenuManager) + */ + protected void fillViewMenu(IMenuManager menuManager) { + super.fillViewMenu(menuManager); + + if (! BUG_184693) { + fShowContainerForDuplicatesAction= new ShowContainerForDuplicatesAction(); + menuManager.add(fShowContainerForDuplicatesAction); + } + if (fAllowScopeSwitching) { + fFilterActionGroup= new WorkingSetFilterActionGroup(getShell(), JavaScriptPlugin.getActivePage(), new IPropertyChangeListener() { + public void propertyChange(PropertyChangeEvent event) { + IWorkingSet ws= (IWorkingSet) event.getNewValue(); + if (ws == null || (ws.isAggregateWorkingSet() && ws.isEmpty())) { + setSearchScope(SearchEngine.createWorkspaceScope()); + setSubtitle(null); + } else { + setSearchScope(JavaSearchScopeFactory.getInstance().createJavaSearchScope(ws, true)); + setSubtitle(ws.getLabel()); + } + + applyFilter(); + } + }); + fFilterActionGroup.fillViewMenu(menuManager); + } + //no type filter preference pages currently exist for JSDT + //menuManager.add(new Separator()); + //menuManager.add(new TypeFiltersPreferencesAction()); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#createExtendedContentArea(org.eclipse.swt.widgets.Composite) + */ + protected Control createExtendedContentArea(Composite parent) { + Control addition= null; + + if (fExtension != null) { + + addition= fExtension.createContentArea(parent); + if (addition != null) { + GridData gd= new GridData(GridData.FILL_HORIZONTAL); + gd.horizontalSpan= 2; + addition.setLayoutData(gd); + + } + + fExtension.initialize(this); + } + + return addition; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.dialogs.SelectionDialog#setResult(java.util.List) + */ + protected void setResult(List newResult) { + + List resultToReturn= new ArrayList(); + + for (int i= 0; i < newResult.size(); i++) { + if (newResult.get(i) instanceof TypeNameMatch) { + IType type= ((TypeNameMatch) newResult.get(i)).getType(); + if (type.exists()) { + // items are added to history in the + // org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#computeResult() + // method + resultToReturn.add(type); + } else { + TypeNameMatch typeInfo= (TypeNameMatch) newResult.get(i); + IPackageFragmentRoot root= typeInfo.getPackageFragmentRoot(); + String containerName= JavaScriptElementLabels.getElementLabel(root, JavaScriptElementLabels.ROOT_QUALIFIED); + String message= Messages.format(JavaUIMessages.FilteredTypesSelectionDialog_dialogMessage, new String[] { typeInfo.getFullyQualifiedName(), containerName }); + MessageDialog.openError(getShell(), fTitle, message); + getSelectionHistory().remove(typeInfo); + } + } + } + + super.setResult(resultToReturn); + } + + /* + * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#create() + */ + public void create() { + super.create(); + Control patternControl= getPatternControl(); + if (patternControl instanceof Text) { + TextFieldNavigationHandler.install((Text) patternControl); + } + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.window.Window#open() + */ + public int open() { + if (getInitialPattern() == null) { + IWorkbenchWindow window= JavaScriptPlugin.getActiveWorkbenchWindow(); + if (window != null) { + ISelection selection= window.getSelectionService().getSelection(); + if (selection instanceof ITextSelection) { + String text= ((ITextSelection) selection).getText(); + if (text != null) { + text= text.trim(); + if (text.length() > 0 && JavaScriptConventions.validateJavaScriptTypeName(text, JavaScriptCore.VERSION_1_3, JavaScriptCore.VERSION_1_3).isOK()) { + setInitialPattern(text, FULL_SELECTION); + } + } + } + } + } + return super.open(); + } + + /** + * Sets a new validator. + * + * @param validator + * the new validator + */ + public void setValidator(ISelectionStatusValidator validator) { + fValidator= validator; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#createFilter() + */ + protected ItemsFilter createFilter() { + return new TypeItemsFilter(fSearchScope, fElementKinds, fFilterExtension); + } + + protected Control createContents(Composite parent) { + Control contents= super.createContents(parent); + if (ColoredViewersManager.showColoredLabels()) { + if (contents instanceof Composite) { + Table listControl= findTableControl((Composite) contents); + if (listControl != null) { + installOwnerDraw(listControl); + } + } + } + return contents; + } + + private void installOwnerDraw(Table tableControl) { + new OwnerDrawSupport(tableControl) { // installs the owner draw listeners + public ColoredString getColoredLabel(Item item) { + String text= item.getText(); + ColoredString str= new ColoredString(text); + int index= text.indexOf('-'); + if (index != -1) { + str.colorize(index, str.length() - index, ColoredJavaElementLabels.QUALIFIER_STYLE); + } + return str; + } + + public Color getColor(String foregroundColorName, Display display) { + return PlatformUI.getWorkbench().getThemeManager().getCurrentTheme().getColorRegistry().get(foregroundColorName); + } + }; + } + + private Table findTableControl(Composite composite) { + Control[] children= composite.getChildren(); + for (int i= 0; i < children.length; i++) { + Control curr= children[i]; + if (curr instanceof Table) { + return (Table) curr; + } else if (curr instanceof Composite) { + Table res= findTableControl((Composite) curr); + if (res != null) { + return res; + } + } + } + return null; + } + + + + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#fillContentProvider(org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.AbstractContentProvider, + * org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.ItemsFilter, + * org.eclipse.core.runtime.IProgressMonitor) + */ + protected void fillContentProvider(AbstractContentProvider provider, ItemsFilter itemsFilter, IProgressMonitor progressMonitor) throws CoreException { + TypeItemsFilter typeSearchFilter= (TypeItemsFilter) itemsFilter; + TypeSearchRequestor requestor= new TypeSearchRequestor(provider, typeSearchFilter); + SearchEngine engine= new SearchEngine((WorkingCopyOwner) null); + progressMonitor.setTaskName(JavaUIMessages.FilteredTypesSelectionDialog_searchJob_taskName); + + /* + * Setting the filter into match everything mode avoids filtering twice + * by the same pattern (the search engine only provides filtered + * matches). For the case when the pattern is a camel case pattern with + * a terminator, the filter is not set to match everything mode because + * jdt.core's SearchPattern does not support that case. + */ + String prefix= typeSearchFilter.getInitialPattern(); + int matchRule= typeSearchFilter.getMatchRule(); + if (matchRule == SearchPattern.RULE_CAMELCASE_MATCH) { + // If the pattern is empty, the RULE_BLANK_MATCH will be chosen, so we don't have to check the pattern length + char lastChar= prefix.charAt(prefix.length() - 1); + + if (lastChar == '<' || lastChar == ' ') { + prefix= prefix.substring(0, prefix.length() - 1); + } else { + typeSearchFilter.setMatchEverythingMode(true); + } + matchRule |= SearchPattern.RULE_PREFIX_MATCH; + } else { + typeSearchFilter.setMatchEverythingMode(true); + } + + try { + engine.searchAllTypeNames(prefix.toCharArray(), + matchRule, //TODO: https://bugs.eclipse.org/bugs/show_bug.cgi?id=176017 + typeSearchFilter.getElementKind(), + typeSearchFilter.getSearchScope(), + requestor, + IJavaScriptSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, + progressMonitor); + } finally { + typeSearchFilter.setMatchEverythingMode(false); + } + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#getItemsComparator() + */ + protected Comparator getItemsComparator() { + return fTypeItemsComparator; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#getElementName(java.lang.Object) + */ + public String getElementName(Object item) { + TypeNameMatch type= (TypeNameMatch) item; + return fTypeInfoUtil.getText(type); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#validateItem(java.lang.Object) + */ + protected IStatus validateItem(Object item) { + + if (item == null) + return new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), IStatus.ERROR, "", null); //$NON-NLS-1$ + + if (fValidator != null) { + IType type= ((TypeNameMatch) item).getType(); + if (!type.exists()) + return new Status(IStatus.ERROR, JavaScriptPlugin.getPluginId(), IStatus.ERROR, Messages.format(JavaUIMessages.FilteredTypesSelectionDialog_error_type_doesnot_exist, ((TypeNameMatch) item).getFullyQualifiedName()), null); + Object[] elements= { type }; + return fValidator.validate(elements); + } else + return new Status(IStatus.OK, JavaScriptPlugin.getPluginId(), IStatus.OK, "", null); //$NON-NLS-1$ + } + + /** + * Sets search scope used when searching for types. + * + * @param scope + * the new scope + */ + private void setSearchScope(IJavaScriptSearchScope scope) { + fSearchScope= scope; + } + + /* + * We only have to ensure history consistency here since the search engine + * takes care of working copies. + */ + private static class ConsistencyRunnable implements IRunnableWithProgress { + public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { + if (fgFirstTime) { + // Join the initialize after load job. + IJobManager manager= Job.getJobManager(); + manager.join(JavaScriptUI.ID_PLUGIN, monitor); + } + OpenTypeHistory history= OpenTypeHistory.getInstance(); + if (fgFirstTime || history.isEmpty()) { + if (history.needConsistencyCheck()) { + monitor.beginTask(JavaUIMessages.TypeSelectionDialog_progress_consistency, 100); + refreshSearchIndices(new SubProgressMonitor(monitor, 90)); + history.checkConsistency(new SubProgressMonitor(monitor, 10)); + } else { + refreshSearchIndices(monitor); + } + monitor.done(); + fgFirstTime= false; + } else { + history.checkConsistency(monitor); + } + } + public static boolean needsExecution() { + OpenTypeHistory history= OpenTypeHistory.getInstance(); + return fgFirstTime || history.isEmpty() || history.needConsistencyCheck(); + } + private void refreshSearchIndices(IProgressMonitor monitor) throws InvocationTargetException { + try { + new SearchEngine().searchAllTypeNames( + null, + 0, + // make sure we search a concrete name. This is faster according to Kent + "_______________".toCharArray(), //$NON-NLS-1$ + SearchPattern.RULE_EXACT_MATCH | SearchPattern.RULE_CASE_SENSITIVE, + IJavaScriptSearchConstants.ENUM, + SearchEngine.createWorkspaceScope(), + new TypeNameRequestor() {}, + IJavaScriptSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, + monitor); + } catch (JavaScriptModelException e) { + throw new InvocationTargetException(e); + } + } + } + + /* + * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#reloadCache(boolean, org.eclipse.core.runtime.IProgressMonitor) + */ + public void reloadCache(boolean checkDuplicates, IProgressMonitor monitor) { + IProgressMonitor remainingMonitor; + if (ConsistencyRunnable.needsExecution()) { + monitor.beginTask(JavaUIMessages.TypeSelectionDialog_progress_consistency, 10); + try { + ConsistencyRunnable runnable= new ConsistencyRunnable(); + runnable.run(new SubProgressMonitor(monitor, 1)); + } catch (InvocationTargetException e) { + ExceptionHandler.handle(e, JavaUIMessages.TypeSelectionDialog_error3Title, JavaUIMessages.TypeSelectionDialog_error3Message); + close(); + return; + } catch (InterruptedException e) { + // cancelled by user + close(); + return; + } + remainingMonitor= new SubProgressMonitor(monitor, 9); + } else { + remainingMonitor= monitor; + } + super.reloadCache(checkDuplicates, remainingMonitor); + monitor.done(); + } + + /* + * @see org.eclipse.wst.jsdt.ui.dialogs.ITypeSelectionComponent#triggerSearch() + */ + public void triggerSearch() { + fTypeFilterVersion++; + applyFilter(); + } + + /** + * The ShowContainerForDuplicatesAction provides means to + * show/hide container information for duplicate elements. + */ + private class ShowContainerForDuplicatesAction extends Action { + + /** + * Creates a new instance of the class + */ + public ShowContainerForDuplicatesAction() { + super(JavaUIMessages.FilteredTypeSelectionDialog_showContainerForDuplicatesAction, IAction.AS_CHECK_BOX); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.action.Action#run() + */ + public void run() { + fTypeInfoLabelProvider.setContainerInfo(isChecked()); + } + } + + private class TypeFiltersPreferencesAction extends Action { + + public TypeFiltersPreferencesAction() { + super(JavaUIMessages.FilteredTypesSelectionDialog_TypeFiltersPreferencesAction_label); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.action.Action#run() + */ + public void run() { + String typeFilterID= TypeFilterPreferencePage.TYPE_FILTER_PREF_PAGE_ID; + PreferencesUtil.createPreferenceDialogOn(getShell(), typeFilterID, new String[] { typeFilterID }, null).open(); + triggerSearch(); + } + } + + /** + * A LabelProvider for (the table of) types. + */ + private class TypeItemLabelProvider extends LabelProvider implements ILabelDecorator { + + private boolean fContainerInfo; + + + /** + * Construct a new TypeItemLabelProvider. F + */ + public TypeItemLabelProvider() { + + } + + public void setContainerInfo(boolean containerInfo) { + fContainerInfo= containerInfo; + fireLabelProviderChanged(new LabelProviderChangedEvent(this)); + } + + private boolean isInnerType(TypeNameMatch match) { + return match.getTypeQualifiedName().indexOf('.') != -1; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.viewers.LabelProvider#getImage(java.lang.Object) + */ + public Image getImage(Object element) { + if (!(element instanceof TypeNameMatch)) { + return super.getImage(element); + } + + TypeNameMatch type= (TypeNameMatch) element; + + ImageDescriptor iD= JavaElementImageProvider.getTypeImageDescriptor(isInnerType(type), false, type.getModifiers(), false); + + return JavaScriptPlugin.getImageDescriptorRegistry().get(iD); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.viewers.LabelProvider#getText(java.lang.Object) + */ + public String getText(Object element) { + if (!(element instanceof TypeNameMatch)) { + return super.getText(element); + } + + if (fContainerInfo && isDuplicateElement(element)) { + return fTypeInfoUtil.getFullyQualifiedText((TypeNameMatch) element); + } + + if (!fContainerInfo && isDuplicateElement(element)) { + return fTypeInfoUtil.getQualifiedText((TypeNameMatch) element); + } + + return fTypeInfoUtil.getText(element); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.viewers.ILabelDecorator#decorateImage(org.eclipse.swt.graphics.Image, + * java.lang.Object) + */ + public Image decorateImage(Image image, Object element) { + return null; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.viewers.ILabelDecorator#decorateText(java.lang.String, + * java.lang.Object) + */ + public String decorateText(String text, Object element) { + if (!(element instanceof TypeNameMatch)) { + return null; + } + + if (fContainerInfo && isDuplicateElement(element)) { + return fTypeInfoUtil.getFullyQualifiedText((TypeNameMatch) element); + } + + return fTypeInfoUtil.getQualifiedText((TypeNameMatch) element); + } + + } + + /** + * A LabelProvider for the label showing type details. + */ + private static class TypeItemDetailsLabelProvider extends LabelProvider { + + private final TypeNameMatchLabelProvider fLabelProvider= new TypeNameMatchLabelProvider(TypeNameMatchLabelProvider.SHOW_TYPE_CONTAINER_ONLY + TypeNameMatchLabelProvider.SHOW_ROOT_POSTFIX); + + private final TypeInfoUtil fTypeInfoUtil; + + public TypeItemDetailsLabelProvider(TypeInfoUtil typeInfoUtil) { + fTypeInfoUtil= typeInfoUtil; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.viewers.LabelProvider#getImage(java.lang.Object) + */ + public Image getImage(Object element) { + if (element instanceof TypeNameMatch) { + return fLabelProvider.getImage((element)); + } + + return super.getImage(element); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.viewers.LabelProvider#getText(java.lang.Object) + */ + public String getText(Object element) { + if (element instanceof TypeNameMatch) { + return fTypeInfoUtil.getQualificationText((TypeNameMatch) element); + } + + return super.getText(element); + } + } + + private static class TypeInfoUtil { + + private final ITypeInfoImageProvider fProviderExtension; + + private final TypeInfoRequestorAdapter fAdapter= new TypeInfoRequestorAdapter(); + + private final Map fLib2Name= new HashMap(); + + private final String[] fInstallLocations; + + private final String[] fVMNames; + + private boolean fFullyQualifyDuplicates; + + public TypeInfoUtil(ITypeInfoImageProvider extension) { + fProviderExtension= extension; + List locations= new ArrayList(); + List labels= new ArrayList(); + IVMInstallType[] installs= JavaRuntime.getVMInstallTypes(); + for (int i= 0; i < installs.length; i++) { + processVMInstallType(installs[i], locations, labels); + } + fInstallLocations= (String[]) locations.toArray(new String[locations.size()]); + fVMNames= (String[]) labels.toArray(new String[labels.size()]); + + } + + public void setFullyQualifyDuplicates(boolean value) { + fFullyQualifyDuplicates= value; + } + + private void processVMInstallType(IVMInstallType installType, List locations, List labels) { + if (installType != null) { + IVMInstall[] installs= installType.getVMInstalls(); + boolean isMac= Platform.OS_MACOSX.equals(Platform.getOS()); + final String HOME_SUFFIX= "/Home"; //$NON-NLS-1$ + for (int i= 0; i < installs.length; i++) { + String label= getFormattedLabel(installs[i].getName()); + LibraryLocation[] libLocations= installs[i].getLibraryLocations(); + if (libLocations != null) { + processLibraryLocation(libLocations, label); + } else { + String filePath= installs[i].getInstallLocation().getAbsolutePath(); + // on MacOS X install locations end in an additional + // "/Home" segment; remove it + if (isMac && filePath.endsWith(HOME_SUFFIX)) + filePath= filePath.substring(0, filePath.length() - HOME_SUFFIX.length() + 1); + locations.add(filePath); + labels.add(label); + } + } + } + } + + private void processLibraryLocation(LibraryLocation[] libLocations, String label) { + for (int l= 0; l < libLocations.length; l++) { + LibraryLocation location= libLocations[l]; + fLib2Name.put(location.getSystemLibraryPath().toOSString(), label); + } + } + + private String getFormattedLabel(String name) { + return Messages.format(JavaUIMessages.FilteredTypesSelectionDialog_library_name_format, name); + } + + public String getText(Object element) { + + return ((TypeNameMatch) element).getQualifiedName(); + } + + public String getQualifiedText(TypeNameMatch type) { + StringBuffer result= new StringBuffer(); + result.append(type.getQualifiedName()); + String containerName= type.getTypeContainerName(); + result.append(JavaScriptElementLabels.CONCAT_STRING); + if (containerName.length() > 0) { + result.append(containerName); + } else { + result.append(JavaUIMessages.FilteredTypesSelectionDialog_default_package); + } + return result.toString(); + } + + public String getFullyQualifiedText(TypeNameMatch type) { + StringBuffer result= new StringBuffer(); + result.append(type.getSimpleTypeName()); + String containerName= type.getTypeContainerName(); + if (containerName.length() > 0) { + result.append(JavaScriptElementLabels.CONCAT_STRING); + result.append(containerName); + } + result.append(JavaScriptElementLabels.CONCAT_STRING); + result.append(getContainerName(type)); + return result.toString(); + } + + public String getText(TypeNameMatch last, TypeNameMatch current, TypeNameMatch next) { + StringBuffer result= new StringBuffer(); + int qualifications= 0; + String currentTN= current.getSimpleTypeName(); + result.append(currentTN); + String currentTCN= getTypeContainerName(current); + if (last != null) { + String lastTN= last.getSimpleTypeName(); + String lastTCN= getTypeContainerName(last); + if (currentTCN.equals(lastTCN)) { + if (currentTN.equals(lastTN)) { + result.append(JavaScriptElementLabels.CONCAT_STRING); + result.append(currentTCN); + result.append(JavaScriptElementLabels.CONCAT_STRING); + result.append(getContainerName(current)); + return result.toString(); + } + } else if (currentTN.equals(lastTN)) { + qualifications= 1; + } + } + if (next != null) { + String nextTN= next.getSimpleTypeName(); + String nextTCN= getTypeContainerName(next); + if (currentTCN.equals(nextTCN)) { + if (currentTN.equals(nextTN)) { + result.append(JavaScriptElementLabels.CONCAT_STRING); + result.append(currentTCN); + result.append(JavaScriptElementLabels.CONCAT_STRING); + result.append(getContainerName(current)); + return result.toString(); + } + } else if (currentTN.equals(nextTN)) { + qualifications= 1; + } + } + if (qualifications > 0) { + result.append(JavaScriptElementLabels.CONCAT_STRING); + result.append(currentTCN); + if (fFullyQualifyDuplicates) { + result.append(JavaScriptElementLabels.CONCAT_STRING); + result.append(getContainerName(current)); + } + } + return result.toString(); + } + + public String getQualificationText(TypeNameMatch type) { + StringBuffer result= new StringBuffer(); + String containerName= type.getTypeContainerName(); + if (containerName.length() > 0) { + result.append(containerName); + result.append(JavaScriptElementLabels.CONCAT_STRING); + } + result.append(getContainerName(type)); + return result.toString(); + } + + private boolean isInnerType(TypeNameMatch match) { + return match.getTypeQualifiedName().indexOf('.') != -1; + } + + public ImageDescriptor getImageDescriptor(Object element) { + TypeNameMatch type= (TypeNameMatch) element; + if (fProviderExtension != null) { + fAdapter.setMatch(type); + ImageDescriptor descriptor= fProviderExtension.getImageDescriptor(fAdapter); + if (descriptor != null) + return descriptor; + } + return JavaElementImageProvider.getTypeImageDescriptor(isInnerType(type), false, type.getModifiers(), false); + } + + private String getTypeContainerName(TypeNameMatch info) { + String result= info.getTypeContainerName(); + if (result.length() > 0) + return result; + return JavaUIMessages.FilteredTypesSelectionDialog_default_package; + } + + private String getContainerName(TypeNameMatch type) { + IPackageFragmentRoot root= type.getPackageFragmentRoot(); + if (root.isExternal()) { + String name= root.getPath().toOSString(); + for (int i= 0; i < fInstallLocations.length; i++) { + if (name.startsWith(fInstallLocations[i])) { + return fVMNames[i]; + } + } + String lib= (String) fLib2Name.get(name); + if (lib != null) + return lib; + } + StringBuffer buf= new StringBuffer(); + JavaScriptElementLabels.getPackageFragmentRootLabel(root, JavaScriptElementLabels.ROOT_QUALIFIED | JavaScriptElementLabels.ROOT_VARIABLE, buf); + return buf.toString(); + } + } + + /** + * Filters types using pattern, scope, element kind and filter extension. + */ + private class TypeItemsFilter extends ItemsFilter { + + private final IJavaScriptSearchScope fScope; + + private final boolean fIsWorkspaceScope; + + private final int fElemKind; + + private final ITypeInfoFilterExtension fFilterExt; + + private final TypeInfoRequestorAdapter fAdapter= new TypeInfoRequestorAdapter(); + + private SearchPattern fPackageMatcher; + + private boolean fMatchEverything= false; + + private final int fMyTypeFilterVersion= fTypeFilterVersion; + + private TypeSearchPattern fInitialPattern; + + /** + * Creates instance of TypeItemsFilter + * + * @param scope + * @param elementKind + * @param extension + */ + public TypeItemsFilter(IJavaScriptSearchScope scope, int elementKind, ITypeInfoFilterExtension extension) { + super(new TypeSearchPattern()); + fScope= scope; + fIsWorkspaceScope= scope == null ? false : scope.equals(SearchEngine.createWorkspaceScope()); + fElemKind= elementKind; + fFilterExt= extension; + String initialString = ((TypeSearchPattern) patternMatcher).getInitialString(); + String stringPackage= ((TypeSearchPattern) patternMatcher).getPackagePattern(); + fInitialPattern = new TypeSearchPattern(); + fInitialPattern.setInitialPattern(initialString); + if (stringPackage != null) { + fPackageMatcher= new SearchPattern(); + fPackageMatcher.setPattern(stringPackage); + } else { + fPackageMatcher= null; + } + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.ItemsFilter#isSubFilter(org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.ItemsFilter) + */ + public boolean isSubFilter(ItemsFilter filter) { + if (!super.isSubFilter(filter)) + return false; + TypeItemsFilter typeItemsFilter= (TypeItemsFilter) filter; + if (fScope != typeItemsFilter.getSearchScope()) + return false; + if (fMyTypeFilterVersion != typeItemsFilter.getMyTypeFilterVersion()) + return false; + return getPattern().indexOf('.', filter.getPattern().length()) == -1; + } + + public boolean equalsFilter(ItemsFilter iFilter) { + if (!super.equalsFilter(iFilter)) + return false; + if (!(iFilter instanceof TypeItemsFilter)) + return false; + TypeItemsFilter typeItemsFilter= (TypeItemsFilter) iFilter; + if (fScope != typeItemsFilter.getSearchScope()) + return false; + if (fMyTypeFilterVersion != typeItemsFilter.getMyTypeFilterVersion()) + return false; + return true; + } + + public int getElementKind() { + return fElemKind; + } + + public ITypeInfoFilterExtension getFilterExtension() { + return fFilterExt; + } + + public IJavaScriptSearchScope getSearchScope() { + return fScope; + } + + public int getMyTypeFilterVersion() { + return fMyTypeFilterVersion; + } + + public String getPackagePattern() { + if (fPackageMatcher == null) + return null; + return fPackageMatcher.getPattern(); + } + + public int getPackageFlags() { + if (fPackageMatcher == null) + return SearchPattern.RULE_PREFIX_MATCH; + + return fPackageMatcher.getMatchRule(); + } + + public String getInitialPattern() { + if (fInitialPattern == null) + return null; + return fInitialPattern.getPattern(); + } + + public boolean matchesRawNamePattern(TypeNameMatch type) { + return Strings.startsWithIgnoreCase(type.getSimpleTypeName(), getPattern()); + } + + public boolean matchesCachedResult(TypeNameMatch type) { + if (!(matchesPackage(type) && matchesFilterExtension(type))) + return false; + return matchesName(type); + } + + public boolean matchesHistoryElement(TypeNameMatch type) { + if (!(matchesPackage(type) && matchesModifiers(type) && matchesScope(type) && matchesFilterExtension(type))) + return false; + return matchesName(type); + } + + public boolean matchesFilterExtension(TypeNameMatch type) { + if (fFilterExt == null) + return true; + fAdapter.setMatch(type); + return fFilterExt.select(fAdapter); + } + + private boolean matchesName(TypeNameMatch type) { + return matches(type.getSimpleTypeName()); + } + + private boolean matchesPackage(TypeNameMatch type) { + if (fPackageMatcher == null) + return true; + return fPackageMatcher.matches(type.getPackageName()); + } + + private boolean matchesScope(TypeNameMatch type) { + if (fIsWorkspaceScope) + return true; + return fScope.encloses(type.getType()); + + } + + private boolean matchesModifiers(TypeNameMatch type) { + if (fElemKind == IJavaScriptSearchConstants.TYPE) + return true; + int modifiers= type.getModifiers(); + switch (fElemKind) { + case IJavaScriptSearchConstants.CLASS: + return modifiers == 0; + } + return false; + } + + /** + * Set filter to "match everything" mode. + * + * @param matchEverything if true, {@link #matchItem(Object)} always returns true. + * If false, the filter is enabled. + */ + public void setMatchEverythingMode(boolean matchEverything) { + this.fMatchEverything= matchEverything; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.ItemsFilter#isConsistentItem(java.lang.Object) + */ + public boolean isConsistentItem(Object item) { + return true; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.ItemsFilter#matchItem(java.lang.Object) + */ + public boolean matchItem(Object item) { + + if (fMatchEverything) + return true; + + TypeNameMatch type= (TypeNameMatch) item; + if (!(matchesPackage(type) && matchesModifiers(type) && matchesScope(type) && matchesFilterExtension(type))) + return false; + + return + fInitialPattern.matches(type.getPackageName()) || + matchesName(type); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.ItemsFilter#matchesRawNamePattern(java.lang.Object) + */ + public boolean matchesRawNamePattern(Object item) { + TypeNameMatch type= (TypeNameMatch) item; + return matchesRawNamePattern(type); + } + + public int getMatchRule() { + return fInitialPattern.getMatchRule(); + } + + } + + /** + * Extends functionality of SearchPatterns + */ + private static class TypeSearchPattern extends SearchPattern { + + private String packagePattern; + private String initialString; + + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.dialogs.SearchPattern#setPattern(java.lang.String) + */ + public void setPattern(String stringPattern) { + initialString = stringPattern; + String pattern= stringPattern; + String packPattern= null; + int index= stringPattern.lastIndexOf("."); //$NON-NLS-1$ + if (index != -1) { + packPattern= evaluatePackagePattern(stringPattern.substring(0, index)); + pattern= stringPattern.substring(index + 1); + if (pattern.length() == 0) + pattern= "**"; //$NON-NLS-1$ + } + super.setPattern(pattern); + packagePattern= packPattern; + } + + public void setInitialPattern(String stringPattern) { + super.setPattern(stringPattern); + } + + /* + * Transforms o.e.j to o*.e*.j* + */ + private String evaluatePackagePattern(String s) { + StringBuffer buf= new StringBuffer(); + boolean hasWildCard= false; + for (int i= 0; i < s.length(); i++) { + char ch= s.charAt(i); + if (ch == '.') { + if (!hasWildCard) { + buf.append('*'); + } + hasWildCard= false; + } else if (ch == '*' || ch == '?') { + hasWildCard= true; + } + buf.append(ch); + } + if (!hasWildCard) { + buf.append('*'); + } + return buf.toString(); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.dialogs.SearchPattern#isNameCharAllowed(char) + */ + protected boolean isNameCharAllowed(char nameChar) { + return super.isNameCharAllowed(nameChar); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.dialogs.SearchPattern#isPatternCharAllowed(char) + */ + protected boolean isPatternCharAllowed(char patternChar) { + return super.isPatternCharAllowed(patternChar); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.dialogs.SearchPattern#isValidCamelCaseChar(char) + */ + protected boolean isValidCamelCaseChar(char ch) { + return ch != '.'; + } + + /** + * @return the packagePattern + */ + public String getPackagePattern() { + return packagePattern; + } + + /** + * @return the initialPattern + */ + public String getInitialString() { + return initialString; + } + + } + + /** + * A TypeSearchRequestor collects matches filtered using + * TypeItemsFilter. The attached content provider is filled + * on the basis of the collected entries (instances of + * TypeNameMatch). + */ + private static class TypeSearchRequestor extends TypeNameMatchRequestor { + private volatile boolean fStop; + + private final AbstractContentProvider fContentProvider; + + private final TypeItemsFilter fTypeItemsFilter; + + public TypeSearchRequestor(AbstractContentProvider contentProvider, TypeItemsFilter typeItemsFilter) { + super(); + fContentProvider= contentProvider; + fTypeItemsFilter= typeItemsFilter; + } + + public void cancel() { + fStop= true; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.wst.jsdt.core.search.TypeNameMatchRequestor#acceptTypeNameMatch(org.eclipse.wst.jsdt.core.search.TypeNameMatch) + */ + public void acceptTypeNameMatch(TypeNameMatch match) { + if (fStop) + return; + if (TypeFilter.isFiltered(match)) + return; + if (CharOperation.indexOf(IInferEngine.ANONYMOUS_PREFIX, match.getSimpleTypeName().toCharArray(), false) == 0) + return; + if (fTypeItemsFilter.matchesFilterExtension(match)) + fContentProvider.add(match, fTypeItemsFilter); + } + + } + + /** + * Compares TypeItems is used during sorting + */ + private static class TypeItemsComparator implements Comparator { + + private final Map fLib2Name= new HashMap(); + + private final String[] fInstallLocations; + + private final String[] fVMNames; + + /** + * Creates new instance of TypeItemsComparator + */ + public TypeItemsComparator() { + List locations= new ArrayList(); + List labels= new ArrayList(); + IVMInstallType[] installs= JavaRuntime.getVMInstallTypes(); + for (int i= 0; i < installs.length; i++) { + processVMInstallType(installs[i], locations, labels); + } + fInstallLocations= (String[]) locations.toArray(new String[locations.size()]); + fVMNames= (String[]) labels.toArray(new String[labels.size()]); + } + + private void processVMInstallType(IVMInstallType installType, List locations, List labels) { + if (installType != null) { + IVMInstall[] installs= installType.getVMInstalls(); + boolean isMac= Platform.OS_MACOSX.equals(Platform.getOS()); + final String HOME_SUFFIX= "/Home"; //$NON-NLS-1$ + for (int i= 0; i < installs.length; i++) { + String label= getFormattedLabel(installs[i].getName()); + LibraryLocation[] libLocations= installs[i].getLibraryLocations(); + if (libLocations != null) { + processLibraryLocation(libLocations, label); + } else { + String filePath= installs[i].getInstallLocation().getAbsolutePath(); + // on MacOS X install locations end in an additional + // "/Home" segment; remove it + if (isMac && filePath.endsWith(HOME_SUFFIX)) + filePath= filePath.substring(0, filePath.length() - HOME_SUFFIX.length() + 1); + locations.add(filePath); + labels.add(label); + } + } + } + } + + private void processLibraryLocation(LibraryLocation[] libLocations, String label) { + for (int l= 0; l < libLocations.length; l++) { + LibraryLocation location= libLocations[l]; + fLib2Name.put(location.getSystemLibraryPath().toString(), label); + } + } + + private String getFormattedLabel(String name) { + return MessageFormat.format(JavaUIMessages.FilteredTypesSelectionDialog_library_name_format, new Object[] { name }); + } + + /* + * (non-Javadoc) + * + * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) + */ + public int compare(Object left, Object right) { + + TypeNameMatch leftInfo= (TypeNameMatch) left; + TypeNameMatch rightInfo= (TypeNameMatch) right; + + int result= compareName(leftInfo.getSimpleTypeName(), rightInfo.getSimpleTypeName()); + if (result != 0) + return result; + result= compareTypeContainerName(leftInfo.getTypeContainerName(), rightInfo.getTypeContainerName()); + if (result != 0) + return result; + + int leftCategory= getElementTypeCategory(leftInfo); + int rightCategory= getElementTypeCategory(rightInfo); + if (leftCategory < rightCategory) + return -1; + if (leftCategory > rightCategory) + return +1; + return compareContainerName(leftInfo, rightInfo); + } + + private int compareName(String leftString, String rightString) { + int result= leftString.compareToIgnoreCase(rightString); + if (result != 0 || rightString.length() == 0) { + return result; + } else if (Strings.isLowerCase(leftString.charAt(0)) && !Strings.isLowerCase(rightString.charAt(0))) { + return +1; + } else if (Strings.isLowerCase(rightString.charAt(0)) && !Strings.isLowerCase(leftString.charAt(0))) { + return -1; + } else { + return leftString.compareTo(rightString); + } + } + + private int compareTypeContainerName(String leftString, String rightString) { + int leftLength= leftString.length(); + int rightLength= rightString.length(); + if (leftLength == 0 && rightLength > 0) + return -1; + if (leftLength == 0 && rightLength == 0) + return 0; + if (leftLength > 0 && rightLength == 0) + return +1; + return compareName(leftString, rightString); + } + + private int compareContainerName(TypeNameMatch leftType, TypeNameMatch rightType) { + return getContainerName(leftType).compareTo(getContainerName(rightType)); + } + + private String getContainerName(TypeNameMatch type) { + IPackageFragmentRoot root= type.getPackageFragmentRoot(); + if (root.isExternal()) { + String name= root.getPath().toOSString(); + for (int i= 0; i < fInstallLocations.length; i++) { + if (name.startsWith(fInstallLocations[i])) { + return fVMNames[i]; + } + } + String lib= (String) fLib2Name.get(name); + if (lib != null) + return lib; + } + StringBuffer buf= new StringBuffer(); + JavaScriptElementLabels.getPackageFragmentRootLabel(root, JavaScriptElementLabels.ROOT_QUALIFIED | JavaScriptElementLabels.ROOT_VARIABLE, buf); + return buf.toString(); + } + + private int getElementTypeCategory(TypeNameMatch type) { + try { + if (type.getPackageFragmentRoot().getKind() == IPackageFragmentRoot.K_SOURCE) + return 0; + } catch (JavaScriptModelException e) { + JavaScriptPlugin.log(e); + } + return 1; + } + } + + /** + * Extends the SelectionHistory, providing support for + * OpenTypeHistory. + */ + protected class TypeSelectionHistory extends SelectionHistory { + + /** + * Creates new instance of TypeSelectionHistory + */ + + public TypeSelectionHistory() { + super(); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.SelectionHistory#accessed(java.lang.Object) + */ + public synchronized void accessed(Object object) { + super.accessed(object); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.SelectionHistory#remove(java.lang.Object) + */ + public synchronized boolean remove(Object element) { + OpenTypeHistory.getInstance().remove((TypeNameMatch) element); + return super.remove(element); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.SelectionHistory#load(org.eclipse.ui.IMemento) + */ + public void load(IMemento memento) { + TypeNameMatch[] types= OpenTypeHistory.getInstance().getTypeInfos(); + + for (int i= 0; i < types.length; i++) { + TypeNameMatch type= types[i]; + accessed(type); + } + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.SelectionHistory#save(org.eclipse.ui.IMemento) + */ + public void save(IMemento memento) { + persistHistory(); + } + + /** + * Stores contents of the local history into persistent history + * container. + */ + private synchronized void persistHistory() { + if (getReturnCode() == OK) { + Object[] items= getHistoryItems(); + for (int i= 0; i < items.length; i++) { + OpenTypeHistory.getInstance().accessed((TypeNameMatch) items[i]); + } + } + } + + protected Object restoreItemFromMemento(IMemento element) { + return null; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.SelectionHistory#storeItemToMemento(java.lang.Object, + * org.eclipse.ui.IMemento) + */ + protected void storeItemToMemento(Object item, IMemento element) { + + } + + } + +} diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/OverrideMethodDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/OverrideMethodDialog.java index 8525407b..4a076cf7 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/OverrideMethodDialog.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/OverrideMethodDialog.java @@ -191,16 +191,7 @@ public class OverrideMethodDialog extends SourceActionDialog { } private static class OverrideMethodComparator extends ViewerComparator { - - private ITypeBinding[] fAllTypes= new ITypeBinding[0]; - - public OverrideMethodComparator(ITypeBinding curr) { - if (curr != null) { - ITypeBinding[] superTypes= Bindings.getAllSuperTypes(curr); - fAllTypes= new ITypeBinding[superTypes.length + 1]; - fAllTypes[0]= curr; - System.arraycopy(superTypes, 0, fAllTypes, 1, superTypes.length); - } + public OverrideMethodComparator() { } /* @@ -247,23 +238,6 @@ public class OverrideMethodDialog extends SourceActionDialog { } } - private static ITypeBinding getSuperType(final ITypeBinding binding, final String name) { - - if (binding.isArray() || binding.isPrimitive()) - return null; - - if (binding.getQualifiedName().startsWith(name)) - return binding; - - final ITypeBinding type= binding.getSuperclass(); - if (type != null) { - final ITypeBinding result= getSuperType(type, name); - if (result != null) - return result; - } - return null; - } - private JavaScriptUnit fUnit= null; public OverrideMethodDialog(Shell shell, CompilationUnitEditor editor, IType type, boolean isSubType) throws JavaScriptModelException { @@ -310,19 +284,19 @@ public class OverrideMethodDialog extends SourceActionDialog { } IFunction[] typesArrays= (IFunction[]) types.toArray(new IFunction[types.size()]); -// OverrideMethodComparator comparator= null;//new OverrideMethodComparator(binding); -// if (expanded.isEmpty() && typesArrays.length > 0) { -// comparator.sort(null, typesArrays); -// expanded.add(typesArrays[0]); -// } - setExpandedElements(typesArrays); + ViewerComparator comparator= new OverrideMethodComparator(); + if (expanded.isEmpty() && typesArrays.length > 0) { + comparator.sort(null, typesArrays); + expanded.add(typesArrays[0]); + } + setExpandedElements(expanded.toArray()); ((OverrideMethodContentProvider) getContentProvider()).init(parentMethods); setTitle(JavaUIMessages.OverrideMethodDialog_dialog_title); setMessage(null); setValidator(new OverrideMethodValidator(parentMethods.length)); -// setComparator(comparator); + setComparator(comparator); setContainerMode(true); setSize(60, 18); setInput(new Object()); diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/TypeInfoViewer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/TypeInfoViewer.java index 2dce2d78..976b38c0 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/TypeInfoViewer.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/TypeInfoViewer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/TypeSelectionDialog2.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/TypeSelectionDialog2.java index b77d0505..81a7e0e2 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/TypeSelectionDialog2.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/dialogs/TypeSelectionDialog2.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/CustomFiltersDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/CustomFiltersDialog.java index 16d0e709..7d0a61fd 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/CustomFiltersDialog.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/CustomFiltersDialog.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/FieldsFilter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/FieldsFilter.java index 74eedbf7..ac9f8a91 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/FieldsFilter.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/FieldsFilter.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/FilterMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/FilterMessages.properties index 87b3dbe8..6400cfa4 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/FilterMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/FilterMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2007 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR CustomFiltersDialog_title= JavaScript Element Filters CustomFiltersDialog_patternInfo= The patterns are separated by comma, where\n* = any string, ? = any character, ,, = , diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/LibraryFilter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/LibraryFilter.java index b37951f2..61d39fa5 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/LibraryFilter.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/LibraryFilter.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -12,7 +12,6 @@ package org.eclipse.wst.jsdt.internal.ui.filters; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; -import org.eclipse.wst.jsdt.internal.ui.packageview.JsGlobalScopeContainer; import org.eclipse.wst.jsdt.ui.ProjectLibraryRoot; @@ -28,9 +27,9 @@ public class LibraryFilter extends ViewerFilter { public boolean select(Viewer viewer, Object parentElement, Object element) { if (element instanceof ProjectLibraryRoot) { return false; - } else if (element instanceof JsGlobalScopeContainer.RequiredProjectWrapper) { - return false; - } + } //else if (element instanceof JsGlobalScopeContainer.RequiredProjectWrapper) { +// return false; +// } return true; } } diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/NonPublicFilter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/NonPublicFilter.java index 22a96ac8..2165c06b 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/NonPublicFilter.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/NonPublicFilter.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/StaticsFilter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/StaticsFilter.java index 43128d09..8de50bcf 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/StaticsFilter.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/filters/StaticsFilter.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/MultiFixMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/MultiFixMessages.properties index 42328a3c..ccb59941 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/MultiFixMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/MultiFixMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2005, 2007 IBM Corporation and others. +# Copyright (c) 2005, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,9 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR + StringMultiFix_AddMissingNonNls_description=Add missing '$NON-NLS$' tags StringMultiFix_RemoveUnnecessaryNonNls_description=Remove unnecessary '$NON-NLS$' tags diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/SaveParticipantMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/SaveParticipantMessages.properties index 906d9ad8..d872da76 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/SaveParticipantMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/SaveParticipantMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2005, 2007 IBM Corporation and others. +# Copyright (c) 2005, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,9 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_NONE + CleanUpSaveParticipantPreferenceConfiguration_SaveActionPreferencePage_FormatSource_Checkbox=Format &source code CleanUpSaveParticipantPreferenceConfiguration_CleanUpActionsTopNodeName_Checkbox=Per&form the selected actions on save CleanUpSaveParticipantPreferenceConfiguration_AdditionalActions_Checkbox=Addi&tional actions diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/UnusedCodeCleanUp.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/UnusedCodeCleanUp.java index 7db3af3b..44ebf9ab 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/UnusedCodeCleanUp.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/fix/UnusedCodeCleanUp.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/AbstractInfoView.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/AbstractInfoView.java index 715f68b5..31706e7c 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/AbstractInfoView.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/AbstractInfoView.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/InfoViewMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/InfoViewMessages.properties index 34477793..97d631c6 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/InfoViewMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/InfoViewMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2007 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,7 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### - +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_NONE CopyAction_label= &Copy CopyAction_tooltip= Copy the Selected Text to the Clipboard diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/JavadocView.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/JavadocView.java index ac0aa806..8a36a447 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/JavadocView.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/infoviews/JavadocView.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -24,8 +24,6 @@ import org.eclipse.core.runtime.Platform; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.dialogs.MessageDialogWithToggle; -import org.eclipse.wst.jsdt.internal.ui.text.html.HTMLPrinter; -import org.eclipse.wst.jsdt.internal.ui.text.html.HTMLTextPresenter; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.text.BadLocationException; @@ -68,8 +66,9 @@ import org.eclipse.ui.texteditor.IAbstractTextEditorHelpContextIds; import org.eclipse.ui.texteditor.IDocumentProvider; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.wst.jsdt.core.IClassFile; -import org.eclipse.wst.jsdt.core.IJavaScriptUnit; import org.eclipse.wst.jsdt.core.IJavaScriptElement; +import org.eclipse.wst.jsdt.core.IJavaScriptUnit; +import org.eclipse.wst.jsdt.core.ILocalVariable; import org.eclipse.wst.jsdt.core.IMember; import org.eclipse.wst.jsdt.core.IOpenable; import org.eclipse.wst.jsdt.core.IPackageFragmentRoot; @@ -78,8 +77,10 @@ import org.eclipse.wst.jsdt.internal.corext.javadoc.JavaDocLocations; import org.eclipse.wst.jsdt.internal.ui.IJavaHelpContextIds; import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin; import org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor; -import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels; +import org.eclipse.wst.jsdt.internal.ui.text.html.HTMLPrinter; +import org.eclipse.wst.jsdt.internal.ui.text.html.HTMLTextPresenter; import org.eclipse.wst.jsdt.ui.JSdocContentAccess; +import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels; import org.eclipse.wst.jsdt.ui.PreferenceConstants; import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions; import org.osgi.framework.Bundle; @@ -593,6 +594,21 @@ public class JavadocView extends AbstractInfoView { if (reader != null) { HTMLPrinter.addParagraph(buffer, reader); } + } else if (curr != null && curr.getElementType() == IJavaScriptElement.LOCAL_VARIABLE) { + Reader reader = null; + try { + reader= JSdocContentAccess.getHTMLContentReader((ILocalVariable)curr, false, true); + } + catch (JavaScriptModelException e) { + reader= new StringReader(InfoViewMessages.JavadocView_error_gettingJavadoc); + JavaScriptPlugin.log(e.getStatus()); + } + if (reader != null) { + HTMLPrinter.addParagraph(buffer, reader); + } + else { + HTMLPrinter.addSmallHeader(buffer, InfoViewMessages.JavadocView_noInformation); + } } } diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocExportMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocExportMessages.java index 9ff6e643..31cf26b2 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocExportMessages.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocExportMessages.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocExportMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocExportMessages.properties index 5bfa5d27..3c1cfe4b 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocExportMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocExportMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2007 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR JavadocSpecificsWizardPage_description=Configure JSDoc arguments. diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocSpecificsWizardPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocSpecificsWizardPage.java index 83e5fa8d..abe734b6 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocSpecificsWizardPage.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javadocexport/JavadocSpecificsWizardPage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ASTProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ASTProvider.java index 96b061fe..bc014e2c 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ASTProvider.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ASTProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/BasicCompilationUnitEditorActionContributor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/BasicCompilationUnitEditorActionContributor.java index a28ce11e..36861327 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/BasicCompilationUnitEditorActionContributor.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/BasicCompilationUnitEditorActionContributor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/CompilationUnitDocumentProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/CompilationUnitDocumentProvider.java index e4df4ea2..46d0e1c8 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/CompilationUnitDocumentProvider.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/CompilationUnitDocumentProvider.java @@ -104,7 +104,6 @@ import org.eclipse.wst.jsdt.internal.corext.util.Messages; import org.eclipse.wst.jsdt.internal.ui.IJavaStatusConstants; import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages; import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin; -import org.eclipse.wst.jsdt.internal.ui.Logger; import org.eclipse.wst.jsdt.internal.ui.javaeditor.saveparticipant.IPostSaveListener; import org.eclipse.wst.jsdt.internal.ui.text.correction.JavaCorrectionProcessor; import org.eclipse.wst.jsdt.internal.ui.text.java.IProblemRequestorExtension; @@ -1015,15 +1014,8 @@ public class CompilationUnitDocumentProvider extends TextFileDocumentProvider im try { final IStorage storage= editorInput.getStorage(); final IPath storagePath= storage.getFullPath(); - if (storage.getName() == null || storagePath == null) { - if (storagePath == null) { - Logger.log(Logger.INFO, "Unsupported editor input: null path"); //$NON-NLS-1$ - } - else if (storage.getName() == null) { - Logger.log(Logger.INFO, "Unsupported editor input: no name"); //$NON-NLS-1$ - } + if (storage.getName() == null || storagePath == null) return null; - } final IPath documentPath; if (storage instanceof IFileState) diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/CompilationUnitEditor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/CompilationUnitEditor.java index f3c21c6c..1bf85d3c 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/CompilationUnitEditor.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/CompilationUnitEditor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ConstructedJavaEditorMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ConstructedJavaEditorMessages.properties index 05df3b1f..0f7e25ca 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ConstructedJavaEditorMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ConstructedJavaEditorMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2008 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_NONE CompilationUnitEditorActionContributor.ToggleInsertMode.label=Sma&rt Insert Mode CompilationUnitEditorActionContributor.ToggleInsertMode.tooltip=Toggle Smart Insert Mode @@ -151,7 +153,7 @@ GotoMatchingBracket.label= Matching &Bracket GotoMatchingBracket.tooltip=Go to Matching Bracket GotoMatchingBracket.description=Go to Matching Bracket -SourceAttachmentDialog.title=Attachments For ''{0}'' +SourceAttachmentDialog.title=Attachments For "{0}" SourceAttachmentDialog.error.title=Error Attaching Source SourceAttachmentDialog.error.message=An error occurred while associating the source diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/EditorHighlightingSynchronizer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/EditorHighlightingSynchronizer.java index 4a28e35e..c23d514e 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/EditorHighlightingSynchronizer.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/EditorHighlightingSynchronizer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/EditorUtility.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/EditorUtility.java index 45b77c4e..6e1f0893 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/EditorUtility.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/EditorUtility.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -186,6 +186,7 @@ public class EditorUtility { if (element == null) return; + // only change selection if the part is not active if (part instanceof JavaEditor) { ((JavaEditor) part).setSelection(element); return; @@ -404,7 +405,7 @@ public class EditorUtility { if (Util.isMetadataFileName(elementName) || Util.isJavaLikeFileName(elementName)) { IResource resource=element.getResource(); - if (resource instanceof IFile) + if (resource instanceof IFile && !org.eclipse.wst.jsdt.internal.compiler.util.Util.isArchiveFileName(resource.getName())) return new FileEditorInput((IFile) resource); } diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ICompoundEditListener.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ICompoundEditListener.java index 816b647d..8dc4c6be 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ICompoundEditListener.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/ICompoundEditListener.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/InternalClassFileEditorInput.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/InternalClassFileEditorInput.java index 712b8026..cce20dfe 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/InternalClassFileEditorInput.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/InternalClassFileEditorInput.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -19,6 +19,7 @@ import org.eclipse.wst.jsdt.core.IClassFile; import org.eclipse.wst.jsdt.core.IJavaScriptElement; import org.eclipse.wst.jsdt.core.JavaScriptModelException; import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages; +import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels; /** @@ -76,7 +77,10 @@ public class InternalClassFileEditorInput implements IClassFileEditorInput, IPer * @see IEditorInput#getToolTipText() */ public String getToolTipText() { - return fClassFile.getType().getFullyQualifiedName(); +// return fClassFile.getType().getFullyQualifiedName(); + StringBuffer s = new StringBuffer(); + JavaScriptElementLabels.getElementLabel(fClassFile, JavaScriptElementLabels.ALL_POST_QUALIFIED | JavaScriptElementLabels.APPEND_ROOT_PATH, s); + return s.toString(); } /* diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaAnnotationImageProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaAnnotationImageProvider.java index 5315ff0a..6c0e13da 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaAnnotationImageProvider.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaAnnotationImageProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaAnnotationIterator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaAnnotationIterator.java index 24b0144c..23252088 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaAnnotationIterator.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaAnnotationIterator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaEditor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaEditor.java index 0e02138a..dd068aa8 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaEditor.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaEditor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaEditorMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaEditorMessages.java index f1b0741a..72e81924 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaEditorMessages.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaEditorMessages.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaEditorMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaEditorMessages.properties index f391e4e5..79ac3839 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaEditorMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaEditorMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2007 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR AddImportOnSelection_label=A&dd Import AddImportOnSelection_tooltip=Create Import Statement on Selection diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaElementHyperlink.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaElementHyperlink.java index f3743bb9..1b5fc9f1 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaElementHyperlink.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaElementHyperlink.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaElementHyperlinkDetector.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaElementHyperlinkDetector.java index d296c107..db78fa5c 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaElementHyperlinkDetector.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaElementHyperlinkDetector.java @@ -31,7 +31,59 @@ import org.eclipse.wst.jsdt.internal.ui.text.JavaWordFinder; * */ public class JavaElementHyperlinkDetector extends AbstractHyperlinkDetector { + + /** + * + * @param textViewer + * @param region + * @param canShowMultipleHyperlinks + * @param ast + * @return + */ + public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks, JavaScriptUnit ast) { + ITextEditor textEditor= (ITextEditor)getAdapter(ITextEditor.class); + if (region == null || !(textEditor instanceof JavaEditor)) + return null; + + IAction openAction= textEditor.getAction("OpenEditor"); //$NON-NLS-1$ + if (openAction == null) + return null; + int offset= region.getOffset(); + + IJavaScriptElement input= EditorUtility.getEditorInputJavaElement(textEditor, false); + if (input == null) + return null; + + //get the possibly hyperlink word region + IDocument document= textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput()); + IRegion wordRegion= JavaWordFinder.findWord(document, offset); + if (wordRegion == null) + return null; + + if(ast==null) { + //search the AST for the word region to determine if it is a candidate for a link + ast = JavaScriptPlugin.getDefault().getASTProvider().getAST( + input, ASTProvider.WAIT_NO, null); + } + + if(ast != null) { + int start = wordRegion.getOffset(); + int end = start + wordRegion.getLength(); + HyperlinkCandidateVisitor visitor = new HyperlinkCandidateVisitor(start, end); + try { + ast.accept(visitor); + } catch(HyperlinkCandidateVisitor.HyperlinkCandidateFoundException e) { + //just means the visiting has been cut off early + } + if(visitor.fFoundCandidate) { + return new IHyperlink[] {new JavaElementHyperlink(wordRegion, openAction)}; + } + } + + return null; + } + /* * @see org.eclipse.jface.text.hyperlink.IHyperlinkDetector#detectHyperlinks(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion, boolean) */ @@ -76,7 +128,7 @@ public class JavaElementHyperlinkDetector extends AbstractHyperlinkDetector { return null; } - + /** *

Visits an AST looking for a node between the given start and end offsets * that could be a hyperlink candidate.

diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaOutlinePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaOutlinePage.java index 7de5924f..e2000bab 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaOutlinePage.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/JavaOutlinePage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/OverrideIndicatorImageProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/OverrideIndicatorImageProvider.java index 3fb2f17d..f2073c8c 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/OverrideIndicatorImageProvider.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/OverrideIndicatorImageProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/RemoveOccurrenceAnnotations.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/RemoveOccurrenceAnnotations.java index 39beaa7e..d7382956 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/RemoveOccurrenceAnnotations.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/RemoveOccurrenceAnnotations.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/SpecificContentAssistExecutor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/SpecificContentAssistExecutor.java index ad669cb0..4a5ff5ca 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/SpecificContentAssistExecutor.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/SpecificContentAssistExecutor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/ISaveParticipantPreferenceConfiguration.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/ISaveParticipantPreferenceConfiguration.java index 113fbdce..401ea08f 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/ISaveParticipantPreferenceConfiguration.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/ISaveParticipantPreferenceConfiguration.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2007 IBM Corporation and others. + * Copyright (c) 2006, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/SaveParticipantDescriptor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/SaveParticipantDescriptor.java index a6d37b4e..acc523f1 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/SaveParticipantDescriptor.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/SaveParticipantDescriptor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2007 IBM Corporation and others. + * Copyright (c) 2006, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/SaveParticipantMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/SaveParticipantMessages.java index 3244d71c..66d46f74 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/SaveParticipantMessages.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/SaveParticipantMessages.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2007 IBM Corporation and others. + * Copyright (c) 2006, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/SaveParticipantMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/SaveParticipantMessages.properties index 3dcc0868..5dfcb9c4 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/SaveParticipantMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/saveparticipant/SaveParticipantMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2006, 2007 IBM Corporation and others. +# Copyright (c) 2006, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,5 +8,7 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR SaveParticipantRegistry_participantNotFound= The ''{0}'' save participant could not be found and will be disabled. diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/SelectionActionMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/SelectionActionMessages.java index 0eb50fcb..af26cd44 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/SelectionActionMessages.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/SelectionActionMessages.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/SelectionActionMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/SelectionActionMessages.properties index 3d3cce90..a5520476 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/SelectionActionMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/javaeditor/selectionactions/SelectionActionMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2007 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_NONE StructureSelect_error_title= Expand Selection To StructureSelect_error_message= No source code attached to class file. To perform this operation you will need to attach source. diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaModelAdapterFactory.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaModelAdapterFactory.java index 0ab5850e..53be12f4 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaModelAdapterFactory.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaModelAdapterFactory.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaRefactoringDescriptorResourceMapping.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaRefactoringDescriptorResourceMapping.java index 18f878ad..4ef14ff9 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaRefactoringDescriptorResourceMapping.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaRefactoringDescriptorResourceMapping.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaRefactoringHistoryResourceMapping.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaRefactoringHistoryResourceMapping.java index 2afeb2e9..e12d2bd6 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaRefactoringHistoryResourceMapping.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaRefactoringHistoryResourceMapping.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaResourceMapping.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaResourceMapping.java index 1b4f06b2..10353efe 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaResourceMapping.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/JavaResourceMapping.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/ModelMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/ModelMessages.properties index 620d4136..92a476b3 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/ModelMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/model/ModelMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2005, 2007 IBM Corporation and others. +# Copyright (c) 2005, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,5 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_NONE + JavaModelLabelProvider_project_preferences_label=Settings JavaModelLabelProvider_refactorings_label=Refactorings diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/CommonLayoutActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/CommonLayoutActionGroup.java index cd874359..87cba25e 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/CommonLayoutActionGroup.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/CommonLayoutActionGroup.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/JavaNavigatorContentProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/JavaNavigatorContentProvider.java index e8f707c7..07964836 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/JavaNavigatorContentProvider.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/JavaNavigatorContentProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2003, 2010 IBM Corporation and others. + * Copyright (c) 2003, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -105,13 +105,19 @@ public class JavaNavigatorContentProvider extends } public Object getParent(Object element) { - Object parent= super.getParent(element); - if (parent instanceof IJavaScriptModel) { - return parent.equals(getViewerInput()) ? fRealInput : parent; - } - if (parent instanceof IJavaScriptProject) { - return ((IJavaScriptProject)parent).getProject(); + Object parent = null; + + // can't handle IResources + if (!(element instanceof IResource)) { + parent= super.getParent(element); + if (parent instanceof IJavaScriptModel) { + return parent.equals(getViewerInput()) ? fRealInput : parent; + } + if (parent instanceof IJavaScriptProject) { + return ((IJavaScriptProject)parent).getProject(); + } } + return parent; } diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/JavaNavigatorLabelProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/JavaNavigatorLabelProvider.java index a249c45d..9dea96ec 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/JavaNavigatorLabelProvider.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/JavaNavigatorLabelProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/PackageExplorerOpenActionProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/PackageExplorerOpenActionProvider.java index c9b3d2b1..7002e3ba 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/PackageExplorerOpenActionProvider.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/PackageExplorerOpenActionProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2003, 2007 IBM Corporation and others. + * Copyright (c) 2003, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -35,10 +35,10 @@ public class PackageExplorerOpenActionProvider extends CommonActionProvider { public void fillActionBars(IActionBars actionBars) { if (fInViewPart) { fOpenGroup.fillActionBars(actionBars); - - if (fOpenAndExpand == null && fOpenGroup.getOpenAction().isEnabled()) // TODO: is not updated! + + if (fOpenAndExpand == null) // TODO: is not updated! actionBars.setGlobalActionHandler(ICommonActionConstants.OPEN, fOpenGroup.getOpenAction()); - else if (fOpenAndExpand != null && fOpenAndExpand.isEnabled()) + else if (fOpenAndExpand != null) actionBars.setGlobalActionHandler(ICommonActionConstants.OPEN, fOpenAndExpand); } @@ -66,7 +66,10 @@ public class PackageExplorerOpenActionProvider extends CommonActionProvider { fOpenGroup = new OpenEditorActionGroup(viewPart); if (site.getStructuredViewer() instanceof TreeViewer) + { fOpenAndExpand = new OpenAndExpand(workbenchSite.getSite(), (OpenAction) fOpenGroup.getOpenAction(), (TreeViewer) site.getStructuredViewer()); + fOpenAndExpand.setActionDefinitionId( "org.eclipse.wst.jsdt.ui.edit.text.java.openandexpand" ); // Make this different from F3 file open handler to avoid handler conflicts + } fInViewPart = true; } } diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/deferred/ClearPlaceHolderJob.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/deferred/ClearPlaceHolderJob.java new file mode 100644 index 00000000..80611b87 --- /dev/null +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/deferred/ClearPlaceHolderJob.java @@ -0,0 +1,49 @@ +/******************************************************************************* + * Copyright (c) 2012 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.wst.jsdt.internal.ui.navigator.deferred; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.jface.viewers.AbstractTreeViewer; +import org.eclipse.ui.progress.UIJob; +import org.eclipse.wst.jsdt.internal.ui.packageview.PackagesMessages; + +public class ClearPlaceHolderJob extends UIJob { + + private AbstractTreeViewer viewer; + private LoadingModelNode placeHolder; + private Object[] children; + private Object parent; + + public ClearPlaceHolderJob(AbstractTreeViewer viewer, LoadingModelNode placeHolder, Object parent, Object[] children) { + super(PackagesMessages.UpdatingViewer); + this.viewer = viewer; + this.placeHolder = placeHolder; + this.parent = parent; + this.children = children; + setRule(new NonConflictingRule()); + } + + public IStatus runInUIThread(IProgressMonitor monitor) { + if (!viewer.getControl().isDisposed()) { + try { + viewer.getControl().setRedraw(false); + viewer.add(parent, children); + viewer.remove(placeHolder); + } + finally { + viewer.getControl().setRedraw(true); + } + } + return Status.OK_STATUS; + } +} \ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/deferred/LoadingModelNode.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/deferred/LoadingModelNode.java new file mode 100644 index 00000000..5f16a002 --- /dev/null +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/deferred/LoadingModelNode.java @@ -0,0 +1,167 @@ +/******************************************************************************* + * Copyright (c) 2011 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.wst.jsdt.internal.ui.navigator.deferred; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.swt.graphics.Image; +import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages; +import org.eclipse.wst.jsdt.internal.ui.packageview.PackageFragmentRootContainer; +import org.eclipse.wst.jsdt.internal.ui.packageview.PackagesMessages; + +public class LoadingModelNode { + + private static ImageDescriptor loadingOne; + private static ImageDescriptor loadingTwo; + private static ImageDescriptor loadingThree; + private static ImageDescriptor loadingFour; + + private static final Set loadingFiles = new HashSet(); + private static final Map placeHolders = new HashMap(); + + static { + try { + loadingOne = JavaPluginImages.DESC_TOOL_LOADING_1; + loadingTwo = JavaPluginImages.DESC_TOOL_LOADING_2; + loadingThree = JavaPluginImages.DESC_TOOL_LOADING_3; + loadingFour = JavaPluginImages.DESC_TOOL_LOADING_4; + } catch (RuntimeException e) { + loadingOne = ImageDescriptor.getMissingImageDescriptor(); + loadingTwo = ImageDescriptor.getMissingImageDescriptor(); + loadingThree = ImageDescriptor.getMissingImageDescriptor(); + loadingFour = ImageDescriptor.getMissingImageDescriptor(); + } + } + + private String text; + private String text1; + private String text2; + private String text3; + private int count = 0; + private boolean disposed = false; + private PackageFragmentRootContainer packageFragmentRootContainer; + + /** + * Return a place holder node to sit in the tree until data is available. + * This place holder node will be animated for the user's enjoyment. + * + * @param modelFile The modelFile to be loaded + * @return A new unique place holder for this file for a given load cycle + */ + public static LoadingModelNode createPlaceHolder(PackageFragmentRootContainer packageFragmentRootContainer) { + LoadingModelNode node = null; + synchronized (LoadingModelNode.class) { + if(placeHolders.containsKey(packageFragmentRootContainer)) + node = (LoadingModelNode) placeHolders.get(packageFragmentRootContainer); + else + placeHolders.put(packageFragmentRootContainer, node = new LoadingModelNode(packageFragmentRootContainer)); + } + return node; + } + + public LoadingModelNode(PackageFragmentRootContainer packageFragmentRootContainer) { + text = PackagesMessages.LoadingJavaScriptNode; + text1 = text + "."; //$NON-NLS-1$ + text2 = text + ".."; //$NON-NLS-1$ + text3 = text + "..."; //$NON-NLS-1$ + this.packageFragmentRootContainer = packageFragmentRootContainer; + } + + public String getText() { + + switch ( count % 4) { + case 0 : + return text; + case 1 : + return text1; + case 2 : + return text2; + case 3 : + default : + return text3; + } + } + + public Image getImage() { + switch ( count = (++count % 4)) { + case 0 : + return loadingOne.createImage(); + case 1 : + return loadingTwo.createImage(); + case 2 : + return loadingThree.createImage(); + case 3 : + default : + return loadingFour.createImage(); + } + } + + public boolean isDisposed() { + return disposed; + } + + public void dispose() { + synchronized (LoadingModelNode.class) { + disposed = true; + placeHolders.remove(packageFragmentRootContainer); + loadingFiles.remove(packageFragmentRootContainer); + } + } + + /** + * Employ a Test and Set (TST) primitive to ensure + * that only job is spawned to load the model file + * + * + * @return True only if no other jobs are trying to load this model. + */ + public static boolean canBeginLoading(PackageFragmentRootContainer packageFragmentRootContainer) { + synchronized (LoadingModelNode.class) { + if(loadingFiles.contains(packageFragmentRootContainer)) + return false; + loadingFiles.add(packageFragmentRootContainer); + return true; + } + + } + + /** + * Return true if a job has requested permission to load the model file + * @param modelFile The model file that should be loaded + * @return True only if a job is trying to load the model. + */ + public static boolean isBeingLoaded(PackageFragmentRootContainer packageFragmentRootContainer) { + synchronized (LoadingModelNode.class) { + return loadingFiles.contains(packageFragmentRootContainer); + } + } + + + public int hashCode() { + return packageFragmentRootContainer.hashCode(); + } + + public boolean equals(Object o) { + if(o instanceof LoadingModelNode) { + return packageFragmentRootContainer.equals( ((LoadingModelNode)o).packageFragmentRootContainer ); + } + return false; + } + + public String toString() { + return "LoadingModelNode for " + packageFragmentRootContainer.getLabel(); //$NON-NLS-1$ + } + +} diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/deferred/LoadingModelUIAnimationJob.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/deferred/LoadingModelUIAnimationJob.java new file mode 100644 index 00000000..680a91d9 --- /dev/null +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/deferred/LoadingModelUIAnimationJob.java @@ -0,0 +1,54 @@ +/******************************************************************************* + * Copyright (c) 2011 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.wst.jsdt.internal.ui.navigator.deferred; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.jface.viewers.AbstractTreeViewer; +import org.eclipse.ui.progress.UIJob; + +public class LoadingModelUIAnimationJob extends UIJob { + + /* we update the animation frame every 250 ms */ + private static final long DELAY = 200; + + /* the node holding the place for the model (the "Loading ..." in the tree ) */ + private LoadingModelNode placeHolder; + private AbstractTreeViewer viewer; + + public LoadingModelUIAnimationJob(AbstractTreeViewer viewer, + LoadingModelNode placeHolder) { + super(placeHolder.getText()); + this.viewer = viewer; + this.placeHolder = placeHolder; + /* + * this way we don't put alot of noise in the progress view, except for + * power users that turn on "show system jobs" in the view + */ + setSystem(true); + setRule(new NonConflictingRule()); + } + + public IStatus runInUIThread(IProgressMonitor monitor) { + + if (!placeHolder.isDisposed()) { + + /* update the animation frame */ + viewer.update(placeHolder, null); + + /* reschedule for the next animation frame */ + schedule(DELAY); + } + return Status.OK_STATUS; + + } +} diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/deferred/NonConflictingRule.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/deferred/NonConflictingRule.java new file mode 100644 index 00000000..91ea0540 --- /dev/null +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/navigator/deferred/NonConflictingRule.java @@ -0,0 +1,25 @@ +/******************************************************************************* + * Copyright (c) 2011 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.wst.jsdt.internal.ui.navigator.deferred; + +import org.eclipse.core.runtime.jobs.ISchedulingRule; + +public class NonConflictingRule implements ISchedulingRule{ + public static final NonConflictingRule INSTANCE = new NonConflictingRule(); + + public boolean contains(ISchedulingRule rule) { + return rule == this; + } + + public boolean isConflicting(ISchedulingRule rule) { + return rule == this; + } +} diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/GotoRequiredProjectAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/GotoRequiredProjectAction.java index 0bdf843a..0c230da9 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/GotoRequiredProjectAction.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/GotoRequiredProjectAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -30,9 +30,10 @@ class GotoRequiredProjectAction extends Action { public void run() { IStructuredSelection selection= (IStructuredSelection)fPackageExplorer.getSite().getSelectionProvider().getSelection(); Object element= selection.getFirstElement(); - if (element instanceof JsGlobalScopeContainer.RequiredProjectWrapper) { - JsGlobalScopeContainer.RequiredProjectWrapper wrapper= (JsGlobalScopeContainer.RequiredProjectWrapper) element; - fPackageExplorer.tryToReveal(wrapper.getProject()); - } + fPackageExplorer.tryToReveal(element); +// if (element instanceof JsGlobalScopeContainer.RequiredProjectWrapper) { +// JsGlobalScopeContainer.RequiredProjectWrapper wrapper= (JsGlobalScopeContainer.RequiredProjectWrapper) element; +// fPackageExplorer.tryToReveal(wrapper.project); +// } } } diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/LayoutActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/LayoutActionGroup.java index e66818e8..7957d0e0 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/LayoutActionGroup.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/LayoutActionGroup.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/LibraryContainer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/LibraryContainer.java index 59548f7e..dd0c1bbf 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/LibraryContainer.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/LibraryContainer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -71,4 +71,11 @@ public class LibraryContainer extends PackageFragmentRootContainer { } return (IPackageFragmentRoot[]) list.toArray(new IPackageFragmentRoot[list.size()]); } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + public String toString() { + return getJavaProject().getDisplayName(); + } } diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackageExplorerContentProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackageExplorerContentProvider.java index 4adb32b5..de0cc362 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackageExplorerContentProvider.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackageExplorerContentProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -23,12 +23,13 @@ import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; +import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; +import org.eclipse.jface.viewers.AbstractTreeViewer; import org.eclipse.jface.viewers.IBasicPropertyConstants; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.StructuredSelection; @@ -58,6 +59,9 @@ import org.eclipse.wst.jsdt.core.JavaScriptModelException; import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil; import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin; import org.eclipse.wst.jsdt.internal.ui.navigator.ContainerFolder; +import org.eclipse.wst.jsdt.internal.ui.navigator.deferred.ClearPlaceHolderJob; +import org.eclipse.wst.jsdt.internal.ui.navigator.deferred.LoadingModelNode; +import org.eclipse.wst.jsdt.internal.ui.navigator.deferred.LoadingModelUIAnimationJob; import org.eclipse.wst.jsdt.internal.ui.workingsets.WorkingSetModel; import org.eclipse.wst.jsdt.ui.PreferenceConstants; import org.eclipse.wst.jsdt.ui.ProjectLibraryRoot; @@ -291,8 +295,23 @@ public class PackageExplorerContentProvider extends StandardJavaScriptElementCon if(parentElement instanceof ContainerFolder) { return getContainerPackageFragmentRoots((PackageFragmentRootContainer)((ContainerFolder)parentElement).getParentObject()); } - if (parentElement instanceof PackageFragmentRootContainer) - return getContainerPackageFragmentRoots((PackageFragmentRootContainer)parentElement, fIsFlatLayout, null); + if (parentElement instanceof PackageFragmentRootContainer) { + if(LoadingModelNode.isBeingLoaded((PackageFragmentRootContainer)parentElement)) { + return new Object[] { + LoadingModelNode.createPlaceHolder((PackageFragmentRootContainer)parentElement) }; + } else { + LoadingModelNode placeHolder = + LoadingModelNode.createPlaceHolder((PackageFragmentRootContainer)parentElement); + /* we need to load the model, + possible long running operation */ + if(LoadingModelNode.canBeginLoading((PackageFragmentRootContainer)parentElement)) + new LoadModelJob((AbstractTreeViewer)fViewer, + placeHolder, + (PackageFragmentRootContainer)parentElement) + .schedule(); + return new Object[] { placeHolder }; + } + } else if (parentElement instanceof NamespaceGroup && ((NamespaceGroup) parentElement).getPackageFragmentRootContainer() != null) { return getContainerPackageFragmentRoots(((NamespaceGroup) parentElement).getPackageFragmentRootContainer(), true, ((NamespaceGroup) parentElement)); } @@ -714,7 +733,13 @@ public class PackageExplorerContentProvider extends StandardJavaScriptElementCon private Object[] getContainerPackageFragmentRoots(PackageFragmentRootContainer container, boolean neverGroup, NamespaceGroup onlyGroup) { Object[] children = container.getChildren(); - if(children==null) return new Object[0]; + if (children == null) + return new Object[0]; + for (int i = 0; i < children.length; i++) { + /* if one of the children is not a JS model element, or is an archive, return as-is for further navigation */ + if (!(children[i] instanceof IJavaScriptElement) || (((IJavaScriptElement) children[i]).getElementType() == IJavaScriptElement.PACKAGE_FRAGMENT_ROOT && ((IPackageFragmentRoot) children[i]).isArchive())) + return children; + } ArrayList allChildren = new ArrayList(); ArrayList expanded = new ArrayList(); @@ -817,6 +842,8 @@ public class PackageExplorerContentProvider extends StandardJavaScriptElementCon } private Object[] getContainerPackageFragmentRootsDeprc(PackageFragmentRootContainer container, boolean createFolder) { + + if(container!=null) { Object[] children = container.getChildren(); @@ -869,9 +896,8 @@ public class PackageExplorerContentProvider extends StandardJavaScriptElementCon return allChildren.toArray(); - } - else { - return new IAdaptable[0]; + }else { + return new Object[0]; } } @@ -1507,4 +1533,40 @@ public class PackageExplorerContentProvider extends StandardJavaScriptElementCon } } } + + // inner class for deferred model loading + public class LoadModelJob extends Job { + + private LoadingModelNode placeHolder; + private AbstractTreeViewer viewer; + private PackageFragmentRootContainer packageFragmentRootContainer; + + public LoadModelJob(AbstractTreeViewer viewer, LoadingModelNode placeHolder, PackageFragmentRootContainer packageFragmentRootContainer) { + super(placeHolder.getText()); + this.viewer = viewer; + this.placeHolder = placeHolder; + this.packageFragmentRootContainer = packageFragmentRootContainer; + } + + protected IStatus run(IProgressMonitor monitor) { + + LoadingModelUIAnimationJob updateUIJob = new LoadingModelUIAnimationJob(viewer, placeHolder); + updateUIJob.schedule(); + + Object[] retVal = new Object[0]; + try { + // Load the model in the background after starting the animation job + + retVal = getContainerPackageFragmentRoots(packageFragmentRootContainer, fIsFlatLayout, null); + + } finally { + /* dispose of the place holder, causes the termination of the animation job */ + placeHolder.dispose(); + new ClearPlaceHolderJob(viewer, placeHolder, packageFragmentRootContainer, retVal).schedule(); + } + + return Status.OK_STATUS; + } + + } } diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackageExplorerLabelProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackageExplorerLabelProvider.java index 043b9383..0654666b 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackageExplorerLabelProvider.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackageExplorerLabelProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -25,6 +25,7 @@ import org.eclipse.wst.jsdt.core.IJavaScriptElement; import org.eclipse.wst.jsdt.core.IJavaScriptUnit; import org.eclipse.wst.jsdt.core.IPackageFragment; import org.eclipse.wst.jsdt.internal.ui.navigator.ContainerFolder; +import org.eclipse.wst.jsdt.internal.ui.navigator.deferred.LoadingModelNode; import org.eclipse.wst.jsdt.internal.ui.viewsupport.AppearanceAwareLabelProvider; import org.eclipse.wst.jsdt.internal.ui.viewsupport.ColoredString; import org.eclipse.wst.jsdt.internal.ui.viewsupport.JavaElementImageProvider; @@ -85,6 +86,8 @@ public class PackageExplorerLabelProvider extends AppearanceAwareLabelProvider { public String getText(Object element) { if(element instanceof ContainerFolder) { return ((ContainerFolder)element).toString(); + } else if (element instanceof LoadingModelNode) { + return ((LoadingModelNode)element).getText(); } String text= getSpecificText(element); if (text != null) { @@ -108,7 +111,7 @@ public class PackageExplorerLabelProvider extends AppearanceAwareLabelProvider { } if(element instanceof IClassFile) { - text = ((IClassFile)element).getPath().lastSegment(); +// text = ((IClassFile)element).getPath().lastSegment(); }else if (element instanceof IJavaScriptUnit) { text = ((IJavaScriptUnit)element).getPath().lastSegment(); } @@ -149,6 +152,8 @@ public class PackageExplorerLabelProvider extends AppearanceAwareLabelProvider { if(element instanceof ContainerFolder) { return super.getImage(((ContainerFolder)element).getParentObject()); + } else if (element instanceof LoadingModelNode) { + return ((LoadingModelNode)element).getImage(); } if (element instanceof IWorkingSet) { diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackageExplorerPart.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackageExplorerPart.java index 8562d1c8..1fe41bee 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackageExplorerPart.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackageExplorerPart.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackagesMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackagesMessages.java index 7212f2b9..1128fff2 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackagesMessages.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackagesMessages.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -65,6 +65,8 @@ public final class PackagesMessages extends NLS { public static String PackageExplorerPart_workspace; public static String PackageExplorerPart_workingSetModel; public static String PackageExplorerContentProvider_update_job_description; + public static String LoadingJavaScriptNode; + public static String UpdatingViewer; static { NLS.initializeMessages(BUNDLE_NAME, PackagesMessages.class); diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackagesMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackagesMessages.properties index 1283b4f4..c8e3b007 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackagesMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/PackagesMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2008 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,7 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### - +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR DragAdapter_deleting=Deleting ... DragAdapter_problem=Problem while moving or copying files. @@ -69,3 +70,6 @@ LayoutActionGroup_hierarchicalLayoutAction_label= &Grouped JsGlobalScopeContainer_unbound_label={0} (unbound) JsGlobalScopeContainer_unknown_label={0} (unknown) LibraryContainer_name=Referenced Libraries + +LoadingJavaScriptNode=Loading JavaScript Model +UpdatingViewer=Updating viewer... diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/ToggleLinkingAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/ToggleLinkingAction.java index fd7b20bb..2cb8f486 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/ToggleLinkingAction.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/ToggleLinkingAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/WorkingSetAwareContentProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/WorkingSetAwareContentProvider.java index 2153fd0b..eb58ae14 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/WorkingSetAwareContentProvider.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/packageview/WorkingSetAwareContentProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/AbstractConfigurationBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/AbstractConfigurationBlock.java index ce0a9253..3dfeac62 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/AbstractConfigurationBlock.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/AbstractConfigurationBlock.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/AppearancePreferencePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/AppearancePreferencePage.java index fb006e08..e8f24133 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/AppearancePreferencePage.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/AppearancePreferencePage.java @@ -31,7 +31,7 @@ import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.IDialogFieldListene import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField; import org.eclipse.wst.jsdt.ui.PreferenceConstants; -public final class AppearancePreferencePage extends PreferencePage implements IWorkbenchPreferencePage { +public class AppearancePreferencePage extends PreferencePage implements IWorkbenchPreferencePage { private static final String SHOW_CU_CHILDREN= PreferenceConstants.SHOW_CU_CHILDREN; private static final String PREF_METHOD_RETURNTYPE= PreferenceConstants.APPEARANCE_METHOD_RETURNTYPE; diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/BuildPathsPropertyPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/BuildPathsPropertyPage.java index 10c9af68..8d92e0cd 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/BuildPathsPropertyPage.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/BuildPathsPropertyPage.java @@ -44,9 +44,9 @@ import org.eclipse.wst.jsdt.internal.ui.wizards.IStatusChangeListener; import org.eclipse.wst.jsdt.internal.ui.wizards.buildpaths.BuildPathsBlock; /** - * Property page for configuring the JavaScript Include path + * Property page for configuring the Java build path */ -public final class BuildPathsPropertyPage extends PropertyPage implements IStatusChangeListener { +public class BuildPathsPropertyPage extends PropertyPage implements IStatusChangeListener { public static final String PROP_ID= "org.eclipse.wst.jsdt.ui.propertyPages.BuildPathsPropertyPage"; //$NON-NLS-1$ diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeAssistFavoritesPreferencePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeAssistFavoritesPreferencePage.java index 253cde45..c5150913 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeAssistFavoritesPreferencePage.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeAssistFavoritesPreferencePage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007 IBM Corporation and others. + * Copyright (c) 2007, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeAssistPreferencePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeAssistPreferencePage.java index 0dc0260d..94c8af30 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeAssistPreferencePage.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeAssistPreferencePage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeFormatterPreferencePage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeFormatterPreferencePage.java index d0fa4394..b249db55 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeFormatterPreferencePage.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/CodeFormatterPreferencePage.java @@ -20,7 +20,7 @@ import org.eclipse.wst.jsdt.internal.ui.preferences.formatter.ProfileConfigurati /* * The page to configure the code formatter options. */ -public final class CodeFormatterPreferencePage extends ProfilePreferencePage { +public class CodeFormatterPreferencePage extends ProfilePreferencePage { public static final String PREF_ID= "org.eclipse.wst.jsdt.ui.preferences.CodeFormatterPreferencePage"; //$NON-NLS-1$ public static final String PROP_ID= "org.eclipse.wst.jsdt.ui.propertyPages.CodeFormatterPreferencePage"; //$NON-NLS-1$ diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ColorSettingPreviewCode.txt b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ColorSettingPreviewCode.txt index 1af303f2..278595ab 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ColorSettingPreviewCode.txt +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/ColorSettingPreviewCode.txt @@ -10,7 +10,7 @@ var arr = []; function foo() { /* This comment may span multiple lines. */ var var1 = new Object(); - var obj = [ make: "Toyota", model: "Celica", year: 2000 ]; + var obj = { carMake: 'Amet', carModel: 'Porro', carYear: 2012 }; var s = "abc123"; clear(var1); } diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/IPreferenceAndPropertyConfigurationBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/IPreferenceAndPropertyConfigurationBlock.java index d4333af3..c7c98e69 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/IPreferenceAndPropertyConfigurationBlock.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/IPreferenceAndPropertyConfigurationBlock.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/IPreferenceConfigurationBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/IPreferenceConfigurationBlock.java index b3f92b85..1fb75c17 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/IPreferenceConfigurationBlock.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/IPreferenceConfigurationBlock.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaBuildConfigurationBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaBuildConfigurationBlock.java index 78e29f06..71926063 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaBuildConfigurationBlock.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaBuildConfigurationBlock.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaEditorAppearanceConfigurationBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaEditorAppearanceConfigurationBlock.java index 2438a0c2..7a076fe3 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaEditorAppearanceConfigurationBlock.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavaEditorAppearanceConfigurationBlock.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavadocConfigurationBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavadocConfigurationBlock.java index d6088200..8e5aa2fb 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavadocConfigurationBlock.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavadocConfigurationBlock.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavadocProblemsConfigurationBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavadocProblemsConfigurationBlock.java index 51a186e0..9abacf91 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavadocProblemsConfigurationBlock.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/JavadocProblemsConfigurationBlock.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/MarkOccurrencesConfigurationBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/MarkOccurrencesConfigurationBlock.java index 46fb9947..900e9c88 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/MarkOccurrencesConfigurationBlock.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/MarkOccurrencesConfigurationBlock.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/MockupPreferenceStore.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/MockupPreferenceStore.java index 7c95f882..fb9a1722 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/MockupPreferenceStore.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/MockupPreferenceStore.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/OverlayPreferenceStore.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/OverlayPreferenceStore.java index 3446cddb..035d90f6 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/OverlayPreferenceStore.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/OverlayPreferenceStore.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/PreferencesMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/PreferencesMessages.properties index aef50408..38ac9529 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/PreferencesMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/PreferencesMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2010 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -10,7 +10,8 @@ # John Kaplan, johnkaplantech@gmail.com - 108071 [code templates] template for body of newly created class # Sebastian Davids, sdavids@gmx.de - 187316 [preferences] Mark Occurences Pref Page; Link to ############################################################################### - +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR BuildPathsPropertyPage_error_message=An error occurred while setting the include path BuildPathsPropertyPage_error_title=Error Setting Include Path diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpMessages.java index 7b1bb799..d2529103 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpMessages.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpMessages.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpMessages.properties index 63985bcc..0fa7e8f0 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CleanUpMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2005, 2010 IBM Corporation and others. +# Copyright (c) 2005, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,9 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_NONE + CleanUpModifyDialog_TabPageName_CodeStyle=&Code Style CleanUpModifyDialog_TabPageName_CodeFormating=Code &Organizing diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CodeStyleTabPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CodeStyleTabPage.java index 0816e01d..ce5b7f81 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CodeStyleTabPage.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/cleanup/CodeStyleTabPage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/BracesTabPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/BracesTabPage.java index 50fb752b..cbba53f4 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/BracesTabPage.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/BracesTabPage.java @@ -37,7 +37,7 @@ public class BracesTabPage extends FormatterTabPage { " var xyz = 'one';\n" + //$NON-NLS-1$ " var arr1 = [ '1', '2', '3', '4' ];\n" + //$NON-NLS-1$ " var arr2 = [];\n" + //$NON-NLS-1$ - " var car = { carMake: 'Toyota', carModel: 'Celica', carYear: 2000 };\n" + //$NON-NLS-1$ + " var car = { carMake: 'Amet', carModel: 'Porro', carYear: 2012 };\n" + //$NON-NLS-1$ " var car2 = {};\n" + //$NON-NLS-1$ "\n" + //$NON-NLS-1$ " switch (data) {\n" + //$NON-NLS-1$ diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/FormatterMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/FormatterMessages.properties index a9c88744..40a39bb7 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/FormatterMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/preferences/formatter/FormatterMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2010 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -10,7 +10,8 @@ # istvan@benedek-home.de - 103706 [formatter] indent empty lines # Aaron Luchko, aluchko@redhat.com - 105926 [Formatter] Exporting Unnamed profile fails silently ############################################################################### - +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR WhiteSpaceTabPage_assignments=Assignments WhiteSpaceTabPage_assignments_before_assignment_operator=before assignment operator @@ -405,7 +406,7 @@ CommentsTabPage_group2_title=JSDoc comment settings CommentsTabPage_clear_blank_lines=Remove blank l&ines CommentsTabPage_blank_line_before_javadoc_tags=Blan&k line before JSDoc tags CommentsTabPage_indent_javadoc_tags=Indent JSDoc tag&s -CommentsTabPage_indent_description_after_param=Ind&ent description a&fter @param +CommentsTabPage_indent_description_after_param=Indent description a&fter @param CommentsTabPage_new_line_after_param_tags=New line &after @param tags CommentsTabPage_group3_title=Line width CommentsTabPage_line_width=Ma&ximum line width for comments: diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ExtractSupertypeWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ExtractSupertypeWizard.java index 6485a654..889ebbf8 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ExtractSupertypeWizard.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/ExtractSupertypeWizard.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2007 IBM Corporation and others. + * Copyright (c) 2006, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IntroduceIndirectionWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IntroduceIndirectionWizard.java index f020cb21..a0c51309 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IntroduceIndirectionWizard.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/IntroduceIndirectionWizard.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/NLSUIMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/NLSUIMessages.properties index 0a77998f..6d90067d 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/NLSUIMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/NLSUIMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2007 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR ExternalizeWizard_name=Externalize Strings ExternalizeWizard_select=Select strings to externalize diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/NLSSearchMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/NLSSearchMessages.properties index 194c33e7..d43ec472 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/NLSSearchMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/nls/search/NLSSearchMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2007 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR SearchOperation_singularLabelPostfix=''{0}'' - 1 problem in ''{1}'' SearchOperation_pluralLabelPatternPostfix=''{0}'' - {1} problems in ''{2}'' diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/refactoringui.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/refactoringui.properties index db78ca79..8ce33b2b 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/refactoringui.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/refactoringui.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2008 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR ####################################### # org.eclipse.wst.jsdt.internal.ui.refactoring diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameLinkedMode.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameLinkedMode.java index 18501474..53b466aa 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameLinkedMode.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameLinkedMode.java @@ -274,6 +274,42 @@ public class RenameLinkedMode { // anim.schedule(); // } + /** + * @param offset + * @param length + */ + public void start(int offset, int length) { + ISourceViewer viewer = fEditor.getViewer(); + IDocument document = viewer.getDocument(); + int cursorPosition = viewer.getSelectedRange().x; + viewer.setSelectedRange(offset, length); + + try { + JavaScriptUnit root = JavaScriptPlugin.getDefault().getASTProvider().getAST(getCompilationUnit(), ASTProvider.WAIT_YES, null); + + fLinkedPositionGroup = new LinkedPositionGroup(); + ASTNode selectedNode = NodeFinder.perform(root, offset, length); + if (! (selectedNode instanceof SimpleName)) + return; + SimpleName nameNode = (SimpleName) selectedNode; + LinkedPosition linkedPosition = new LinkedPosition(document, nameNode.getStartPosition(), nameNode.getLength()); + fLinkedPositionGroup.addPosition(linkedPosition); + + fLinkedModeModel = new LinkedModeModel(); + fLinkedModeModel.addGroup(fLinkedPositionGroup); + fLinkedModeModel.forceInstall(); + fLinkedModeModel.addLinkingListener(new EditorHighlightingSynchronizer(fEditor)); + + LinkedModeUI ui = new EditorLinkedModeUI(fLinkedModeModel, viewer); + ui.setExitPosition(viewer, cursorPosition, 0, Integer.MAX_VALUE); + ui.setExitPolicy(new ExitPolicy(document)); + ui.enter(); + + } catch (BadLocationException e) { + JavaScriptPlugin.log(e); + } + } + void doRename(boolean showPreview) { cancel(); diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameTypeWizardInputPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameTypeWizardInputPage.java index de516370..bb476b6a 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameTypeWizardInputPage.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameTypeWizardInputPage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameTypeWizardSimilarElementsOptionsDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameTypeWizardSimilarElementsOptionsDialog.java index 6154e656..b8f7f223 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameTypeWizardSimilarElementsOptionsDialog.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/RenameTypeWizardSimilarElementsOptionsDialog.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgMessages.properties index 6afcbb54..db021921 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/reorg/ReorgMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2008 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR CutAction_text=Cu&t diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchQuery.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchQuery.java index 62cebcba..5906d054 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchQuery.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/JavaSearchQuery.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SearchMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SearchMessages.properties index 8d2bb465..6390a179 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SearchMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/search/SearchMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2008 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR SearchLabelProvider_exact_singular={0} (1 match) SearchLabelProvider_exact_noCount={0} diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/AbstractJavaScanner.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/AbstractJavaScanner.java index 70f53db1..34979bca 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/AbstractJavaScanner.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/AbstractJavaScanner.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/CombinedWordRule.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/CombinedWordRule.java index 6c3bedf3..85e6c98d 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/CombinedWordRule.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/CombinedWordRule.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/CompositeReconcilingStrategy.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/CompositeReconcilingStrategy.java index 6daf4b25..dbc31961 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/CompositeReconcilingStrategy.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/CompositeReconcilingStrategy.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/DocumentCharacterIterator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/DocumentCharacterIterator.java index 4362d93a..f32b8d9c 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/DocumentCharacterIterator.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/DocumentCharacterIterator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/FastJavaPartitionScanner.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/FastJavaPartitionScanner.java index f5c57e5a..7c412d11 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/FastJavaPartitionScanner.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/FastJavaPartitionScanner.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/HTMLAnnotationHover.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/HTMLAnnotationHover.java index 1c9dd9ac..189df5e4 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/HTMLAnnotationHover.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/HTMLAnnotationHover.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/ITypingRunListener.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/ITypingRunListener.java index 3f162e17..8da955b9 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/ITypingRunListener.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/ITypingRunListener.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaBreakIterator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaBreakIterator.java index 6429c72d..eb7afbee 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaBreakIterator.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaBreakIterator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaChangeHover.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaChangeHover.java index cb58a35d..d9bcfb5a 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaChangeHover.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaChangeHover.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaColorManager.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaColorManager.java index 5adc3e24..dd324d23 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaColorManager.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaColorManager.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaOutlineInformationControl.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaOutlineInformationControl.java index adeecc46..8cbe8e52 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaOutlineInformationControl.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaOutlineInformationControl.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaPresentationReconciler.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaPresentationReconciler.java index 366c8243..4ea86e35 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaPresentationReconciler.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaPresentationReconciler.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaWordIterator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaWordIterator.java index bb064f85..05988d8c 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaWordIterator.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/JavaWordIterator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/SequenceCharacterIterator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/SequenceCharacterIterator.java index 2fff66c2..269271a5 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/SequenceCharacterIterator.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/SequenceCharacterIterator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/SmartBackspaceManager.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/SmartBackspaceManager.java index 43260176..9e0f5ef4 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/SmartBackspaceManager.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/SmartBackspaceManager.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/Symbols.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/Symbols.java index 4b3bf8f7..ea41c711 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/Symbols.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/Symbols.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/TextMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/TextMessages.properties index 00680b58..25bca52e 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/TextMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/TextMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2007 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,8 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### - - +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_NONE JavaOutlineInformationControl_SortByDefiningTypeAction_label= Sort by the Defining &Type JavaOutlineInformationControl_SortByDefiningTypeAction_tooltip= Sort Members by the Defining Type diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/TypingRun.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/TypingRun.java index 99e7f314..20143a44 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/TypingRun.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/TypingRun.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/TypingRunDetector.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/TypingRunDetector.java index 9aa5bec2..6041392c 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/TypingRunDetector.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/TypingRunDetector.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/comment/CommentFormattingContext.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/comment/CommentFormattingContext.java index 63cfb864..fbfc81fe 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/comment/CommentFormattingContext.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/comment/CommentFormattingContext.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/CorrectionMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/CorrectionMessages.properties index d761479f..c424bf5d 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/CorrectionMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/CorrectionMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2008 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR # ------ SerialVersionProposal diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/JavaCorrectionProcessor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/JavaCorrectionProcessor.java index 45c6a653..5177dedc 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/JavaCorrectionProcessor.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/JavaCorrectionProcessor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/NewCUCompletionUsingWizardProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/NewCUCompletionUsingWizardProposal.java index 000e4361..e06b24a5 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/NewCUCompletionUsingWizardProposal.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/correction/NewCUCompletionUsingWizardProposal.java @@ -12,14 +12,8 @@ package org.eclipse.wst.jsdt.internal.ui.text.correction; import org.eclipse.core.runtime.Assert; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.viewers.StructuredSelection; -import org.eclipse.jface.window.Window; import org.eclipse.jface.wizard.IWizardPage; -import org.eclipse.jface.wizard.WizardDialog; -import org.eclipse.swt.widgets.Shell; import org.eclipse.wst.jsdt.core.IJavaScriptElement; import org.eclipse.wst.jsdt.core.IJavaScriptUnit; import org.eclipse.wst.jsdt.core.IPackageFragment; @@ -30,15 +24,10 @@ import org.eclipse.wst.jsdt.core.dom.CatchClause; import org.eclipse.wst.jsdt.core.dom.FunctionDeclaration; import org.eclipse.wst.jsdt.core.dom.ITypeBinding; import org.eclipse.wst.jsdt.core.dom.Name; -import org.eclipse.wst.jsdt.core.dom.rewrite.ImportRewrite; -import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility; import org.eclipse.wst.jsdt.internal.corext.dom.ASTNodes; import org.eclipse.wst.jsdt.internal.corext.dom.Bindings; -import org.eclipse.wst.jsdt.internal.corext.util.JavaModelUtil; import org.eclipse.wst.jsdt.internal.corext.util.Messages; import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages; -import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin; -import org.eclipse.wst.jsdt.internal.ui.util.PixelConverter; import org.eclipse.wst.jsdt.internal.ui.viewsupport.BindingLabelProvider; import org.eclipse.wst.jsdt.internal.ui.wizards.NewClassCreationWizard; import org.eclipse.wst.jsdt.internal.ui.wizards.NewElementWizard; @@ -162,51 +151,51 @@ public class NewCUCompletionUsingWizardProposal extends ChangeCorrectionProposal public void apply(IDocument document) { - NewElementWizard wizard= null; - wizard.init(JavaScriptPlugin.getDefault().getWorkbench(), new StructuredSelection(fCompilationUnit)); - - IType createdType= null; - - if (fShowDialog) { - Shell shell= JavaScriptPlugin.getActiveWorkbenchShell(); - WizardDialog dialog= new WizardDialog(shell, wizard); - PixelConverter converter= new PixelConverter(JFaceResources.getDialogFont()); - dialog.setMinimumPageSize(converter.convertWidthInCharsToPixels(70), converter.convertHeightInCharsToPixels(20)); - dialog.create(); - dialog.getShell().setText(CorrectionMessages.NewCUCompletionUsingWizardProposal_dialogtitle); - - configureWizardPage(wizard); - if (dialog.open() == Window.OK) { - createdType= (IType) wizard.getCreatedElement(); - } - } else { - wizard.addPages(); - try { - NewTypeWizardPage page= configureWizardPage(wizard); - page.createType(null); - createdType= page.getCreatedType(); - } catch (CoreException e) { - JavaScriptPlugin.log(e); - } catch (InterruptedException e) { - } - } - - if (createdType != null) { - IJavaScriptElement container= createdType.getParent(); - if (container instanceof IJavaScriptUnit) { - container= container.getParent(); - } - if (!container.equals(fTypeContainer)) { - // add import - try { - ImportRewrite rewrite= StubUtility.createImportRewrite(fCompilationUnit, true); - rewrite.addImport(createdType.getFullyQualifiedName('.')); - JavaModelUtil.applyEdit(fCompilationUnit, rewrite.rewriteImports(null), false, null); - } catch (CoreException e) { - } - } - fCreatedType= createdType; - } +// NewElementWizard wizard= null; +// wizard.init(JavaScriptPlugin.getDefault().getWorkbench(), new StructuredSelection(fCompilationUnit)); +// +// IType createdType= null; +// +// if (fShowDialog) { +// Shell shell= JavaScriptPlugin.getActiveWorkbenchShell(); +// WizardDialog dialog= new WizardDialog(shell, wizard); +// PixelConverter converter= new PixelConverter(JFaceResources.getDialogFont()); +// dialog.setMinimumPageSize(converter.convertWidthInCharsToPixels(70), converter.convertHeightInCharsToPixels(20)); +// dialog.create(); +// dialog.getShell().setText(CorrectionMessages.NewCUCompletionUsingWizardProposal_dialogtitle); +// +// configureWizardPage(wizard); +// if (dialog.open() == Window.OK) { +// createdType= (IType) wizard.getCreatedElement(); +// } +// } else { +// wizard.addPages(); +// try { +// NewTypeWizardPage page= configureWizardPage(wizard); +// page.createType(null); +// createdType= page.getCreatedType(); +// } catch (CoreException e) { +// JavaScriptPlugin.log(e); +// } catch (InterruptedException e) { +// } +// } +// +// if (createdType != null) { +// IJavaScriptElement container= createdType.getParent(); +// if (container instanceof IJavaScriptUnit) { +// container= container.getParent(); +// } +// if (!container.equals(fTypeContainer)) { +// // add import +// try { +// ImportRewrite rewrite= StubUtility.createImportRewrite(fCompilationUnit, true); +// rewrite.addImport(createdType.getFullyQualifiedName('.')); +// JavaModelUtil.applyEdit(fCompilationUnit, rewrite.rewriteImports(null), false, null); +// } catch (CoreException e) { +// } +// } +// fCreatedType= createdType; +// } } diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/folding/EmptyJavaFoldingPreferenceBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/folding/EmptyJavaFoldingPreferenceBlock.java index c7a203f5..80c78cd2 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/folding/EmptyJavaFoldingPreferenceBlock.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/folding/EmptyJavaFoldingPreferenceBlock.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/folding/FoldingMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/folding/FoldingMessages.properties index 76c28dc2..37b5b3f7 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/folding/FoldingMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/folding/FoldingMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2007 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,7 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### - +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR DefaultJavaFoldingPreferenceBlock_title= Initially fold these elements: DefaultJavaFoldingPreferenceBlock_comments= &Comments diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/folding/JavaFoldingStructureProviderDescriptor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/folding/JavaFoldingStructureProviderDescriptor.java index 444acc7a..63f40449 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/folding/JavaFoldingStructureProviderDescriptor.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/folding/JavaFoldingStructureProviderDescriptor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/BrowserInformationControl.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/BrowserInformationControl.java index a25f1859..0db142db 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/BrowserInformationControl.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/BrowserInformationControl.java @@ -2,7 +2,7 @@ package org.eclipse.wst.jsdt.internal.ui.text.html; // COPIED FROM org.eclipse.jface.internal.text.html // to get around "discouraged access" errors /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/HTMLMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/HTMLMessages.java index cc2bda8e..b8ca0fa9 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/HTMLMessages.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/HTMLMessages.java @@ -1,7 +1,7 @@ // COPIED FROM org.eclipse.jface.internal.text.html // to get around "discouraged access" errors /******************************************************************************* - * Copyright (c) 2006, 2007 IBM Corporation and others. + * Copyright (c) 2006, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/HTMLMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/HTMLMessages.properties index 6b501b1b..e50db4cf 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/HTMLMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/HTMLMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2006, 2007 IBM Corporation and others. +# Copyright (c) 2006, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,7 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### - +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_NONE HTMLTextPresenter.ellipse= ... diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/HTMLPrinter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/HTMLPrinter.java index c30f01fe..bfda0449 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/HTMLPrinter.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/HTMLPrinter.java @@ -1,7 +1,7 @@ // COPIED FROM org.eclipse.jface.internal.text.html // to get around "discouraged access" errors /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/HTMLTextPresenter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/HTMLTextPresenter.java index 0bc7c856..c6c6631e 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/HTMLTextPresenter.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/html/HTMLTextPresenter.java @@ -1,7 +1,7 @@ // COPIED FROM org.eclipse.jface.internal.text.html // to get around "discouraged access" errors /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/AbstractJavaCompletionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/AbstractJavaCompletionProposal.java index 4632681a..26070432 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/AbstractJavaCompletionProposal.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/AbstractJavaCompletionProposal.java @@ -672,7 +672,7 @@ public abstract class AbstractJavaCompletionProposal implements IJavaCompletionP * @param prefix the current prefix in the document * @return true if prefix is a valid prefix of this proposal */ - protected boolean isValidPrefix(String prefix) { + public boolean isValidPrefix(String prefix) { /* * See http://dev.eclipse.org/bugs/show_bug.cgi?id=17667 * why we do not use the replacement string. @@ -1016,4 +1016,22 @@ public abstract class AbstractJavaCompletionProposal implements IJavaCompletionP return proposal != null && (proposal.getKind() == CompletionProposal.METHOD_REF || proposal.getKind() == CompletionProposal.FIELD_REF); } + /** + *

+ * Two proposals are equal if their display strings are the same. + *

+ * + * @see java.lang.Object#equals(java.lang.Object) + */ + public boolean equals(Object obj) { + boolean equal = false; + + if(obj instanceof AbstractJavaCompletionProposal) { + AbstractJavaCompletionProposal other = (AbstractJavaCompletionProposal)obj; + equal = this.getDisplayString().equals(other.getDisplayString()); + } + + return equal; + } + } diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/AlphabeticSorter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/AlphabeticSorter.java index 4f8b472a..2d53ba0a 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/AlphabeticSorter.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/AlphabeticSorter.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2007 IBM Corporation and others. + * Copyright (c) 2006, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/CompletionProposalComputerDescriptor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/CompletionProposalComputerDescriptor.java index 5cf29353..8624a77c 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/CompletionProposalComputerDescriptor.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/CompletionProposalComputerDescriptor.java @@ -71,7 +71,7 @@ final class CompletionProposalComputerDescriptor { * first invocation, as it may take longer due to plug-in initialization etc. See also * {@link #fIsReportingDelay}. */ - private static final long MAX_DELAY= 7500; + private static final long MAX_DELAY= 7000; /* log constants */ private static final String COMPUTE_COMPLETION_PROPOSALS= "computeCompletionProposals()"; //$NON-NLS-1$ diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/CompletionProposalComputerRegistry.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/CompletionProposalComputerRegistry.java index d400768e..b0f0f5e2 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/CompletionProposalComputerRegistry.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/CompletionProposalComputerRegistry.java @@ -29,6 +29,7 @@ import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.InvalidRegistryObjectException; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; +import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.IPreferenceStore; @@ -320,36 +321,39 @@ public final class CompletionProposalComputerRegistry { */ void informUser(CompletionProposalComputerDescriptor descriptor, IStatus status) { JavaScriptPlugin.log(status); - String title= JavaTextMessages.CompletionProposalComputerRegistry_error_dialog_title; - CompletionProposalCategory category= descriptor.getCategory(); - IContributor culprit= descriptor.getContributor(); - Set affectedPlugins= getAffectedContributors(category, culprit); - - final String avoidHint; - final String culpritName= culprit == null ? null : culprit.getName(); - if (affectedPlugins.isEmpty()) - avoidHint= Messages.format(JavaTextMessages.CompletionProposalComputerRegistry_messageAvoidanceHint, new Object[] {culpritName, category.getDisplayName()}); - else - avoidHint= Messages.format(JavaTextMessages.CompletionProposalComputerRegistry_messageAvoidanceHintWithWarning, new Object[] {culpritName, category.getDisplayName(), toString(affectedPlugins)}); - - String message= status.getMessage(); - // inlined from MessageDialog.openError - MessageDialog dialog = new MessageDialog(JavaScriptPlugin.getActiveWorkbenchShell(), title, null /* default image */, message, MessageDialog.ERROR, new String[] { IDialogConstants.OK_LABEL }, 0) { - protected Control createCustomArea(Composite parent) { - Link link= new Link(parent, SWT.NONE); - link.setText(avoidHint); - link.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - PreferencesUtil.createPreferenceDialogOn(getShell(), "org.eclipse.wst.jsdt.ui.preferences.CodeAssistPreferenceAdvanced", null, null).open(); //$NON-NLS-1$ - } - }); - GridData gridData= new GridData(SWT.FILL, SWT.BEGINNING, true, false); - gridData.widthHint= this.getMinimumMessageWidth(); - link.setLayoutData(gridData); - return link; - } - }; - dialog.open(); + + if(!ErrorDialog.AUTOMATED_MODE) { + String title= JavaTextMessages.CompletionProposalComputerRegistry_error_dialog_title; + CompletionProposalCategory category= descriptor.getCategory(); + IContributor culprit= descriptor.getContributor(); + Set affectedPlugins= getAffectedContributors(category, culprit); + + final String avoidHint; + final String culpritName= culprit == null ? null : culprit.getName(); + if (affectedPlugins.isEmpty()) + avoidHint= Messages.format(JavaTextMessages.CompletionProposalComputerRegistry_messageAvoidanceHint, new Object[] {culpritName, category.getDisplayName()}); + else + avoidHint= Messages.format(JavaTextMessages.CompletionProposalComputerRegistry_messageAvoidanceHintWithWarning, new Object[] {culpritName, category.getDisplayName(), toString(affectedPlugins)}); + + String message= status.getMessage(); + // inlined from MessageDialog.openError + MessageDialog dialog = new MessageDialog(JavaScriptPlugin.getActiveWorkbenchShell(), title, null /* default image */, message, MessageDialog.ERROR, new String[] { IDialogConstants.OK_LABEL }, 0) { + protected Control createCustomArea(Composite parent) { + Link link= new Link(parent, SWT.NONE); + link.setText(avoidHint); + link.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + PreferencesUtil.createPreferenceDialogOn(getShell(), "org.eclipse.wst.jsdt.ui.preferences.CodeAssistPreferenceAdvanced", null, null).open(); //$NON-NLS-1$ + } + }); + GridData gridData= new GridData(SWT.FILL, SWT.BEGINNING, true, false); + gridData.widthHint= this.getMinimumMessageWidth(); + link.setLayoutData(gridData); + return link; + } + }; + dialog.open(); + } } /** diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ContentAssistComputerParameter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ContentAssistComputerParameter.java index 0ee0f3df..e9eddf4e 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ContentAssistComputerParameter.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ContentAssistComputerParameter.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/FieldProposalInfo.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/FieldProposalInfo.java index 5d69f003..b31e9451 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/FieldProposalInfo.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/FieldProposalInfo.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2010 IBM Corporation and others. + * Copyright (c) 2005, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -10,13 +10,30 @@ *******************************************************************************/ package org.eclipse.wst.jsdt.internal.ui.text.java; +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.wst.jsdt.core.CompletionProposal; import org.eclipse.wst.jsdt.core.IField; +import org.eclipse.wst.jsdt.core.IJavaScriptElement; import org.eclipse.wst.jsdt.core.IJavaScriptProject; +import org.eclipse.wst.jsdt.core.ILocalVariable; import org.eclipse.wst.jsdt.core.IMember; import org.eclipse.wst.jsdt.core.IType; import org.eclipse.wst.jsdt.core.JavaScriptModelException; +import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope; +import org.eclipse.wst.jsdt.core.search.SearchEngine; +import org.eclipse.wst.jsdt.core.search.SearchMatch; +import org.eclipse.wst.jsdt.core.search.SearchParticipant; +import org.eclipse.wst.jsdt.core.search.SearchPattern; +import org.eclipse.wst.jsdt.core.search.SearchRequestor; +import org.eclipse.wst.jsdt.internal.core.DefaultWorkingCopyOwner; +import org.eclipse.wst.jsdt.internal.core.search.matching.FieldPattern; +import org.eclipse.wst.jsdt.internal.core.util.QualificationHelpers; import org.eclipse.wst.jsdt.internal.corext.template.java.SignatureUtil; +import org.eclipse.wst.jsdt.internal.ui.Logger; /** @@ -24,8 +41,7 @@ import org.eclipse.wst.jsdt.internal.corext.template.java.SignatureUtil; * * */ -public final class FieldProposalInfo extends MemberProposalInfo { - +public final class FieldProposalInfo extends MemberProposalInfo { /** * Creates a new proposal info. * @@ -35,34 +51,116 @@ public final class FieldProposalInfo extends MemberProposalInfo { public FieldProposalInfo(IJavaScriptProject project, CompletionProposal proposal) { super(project, proposal); } - + /** - * Resolves the member described by the receiver and returns it if found. - * Returns null if no corresponding member can be found. - * - * @return the resolved member or null if none is found - * @throws JavaScriptModelException if accessing the java model fails + *

Returns the java element that this computer corresponds to, possibly null.

+ * + *

NOTE: This overrides the parent implementation so that {@link #resolveMember()} is not called + * because the field proposal can resolve to a none {@link IMember}.

+ * + * @return the java element that this computer corresponds to, possibly null + * @throws JavaScriptModelException + */ + public IJavaScriptElement getJavaElement() throws JavaScriptModelException { + if (!fJavaElementResolved) { + fJavaElementResolved= true; + //call the internal resolve rather then #resolveMember + fElement = resolve(); + } + return fElement; + } + + /** + * @see org.eclipse.wst.jsdt.internal.ui.text.java.MemberProposalInfo#resolveMember() */ protected IMember resolveMember() throws JavaScriptModelException { - char[] declarationSignature= fProposal.getDeclarationSignature(); - // for synthetic fields on arrays, declaration signatures may be null - // TODO remove when https://bugs.eclipse.org/bugs/show_bug.cgi?id=84690 gets fixed - if (declarationSignature == null) - return null; - String typeName= SignatureUtil.stripSignatureToFQN(String.valueOf(declarationSignature)); - IType[] types = this.fJavaProject.findTypes(typeName); - if(types != null && types.length > 0) { - for(int i = 0; i < types.length; ++i) { - IType type = types[i]; - if (type != null) { - String name= String.valueOf(fProposal.getName()); - IField field= type.getField(name); - if (field.exists()) - return field; + IMember member = null; + IJavaScriptElement element = this.resolve(); + if(element instanceof IMember) { + member = (IMember)element; + } + return member; + } + + /** + * @return {@link IJavaScriptElement} that this field proposal resolves to + * + * @throws JavaScriptModelException + */ + private IJavaScriptElement resolve() throws JavaScriptModelException { + //get the type name + char[] typeNameChars = fProposal.getDeclarationTypeName(); + String declaringTypeName = null; + if(typeNameChars != null) { + declaringTypeName = String.valueOf(typeNameChars); + } + + /* try using the signature if type name not set + * NOTE: old way of doing things, should be removed at some point + */ + if(declaringTypeName == null) { + char[] declarationSignature= fProposal.getDeclarationSignature(); + if(declarationSignature != null) { + declaringTypeName = SignatureUtil.stripSignatureToFQN(String.valueOf(declarationSignature)); + } + } + + //find the field + IJavaScriptElement resolvedField = null; + if(declaringTypeName != null) { + String fieldName = String.valueOf(fProposal.getName()); + + IType[] types = this.fJavaProject.findTypes(declaringTypeName); + if(types != null && types.length > 0) { + for(int i = 0; i < types.length && resolvedField == null; ++i) { + IType type = types[i]; + if (type != null) { + IField field = type.getField(fieldName); + if (field.exists()) { + resolvedField = field; + } + } } + } else { + //create the search pattern + char[][] seperatedDeclaringTypename = QualificationHelpers.seperateFullyQualifedName(declaringTypeName.toCharArray()); +// if(!CharOperation.equals(seperatedDeclaringTypename[QualificationHelpers.SIMPLE_NAMES_INDEX], IIndexConstants.GLOBAL_SYMBOL)) { + FieldPattern fieldPattern = new FieldPattern(true, false, false, + fieldName.toCharArray(), + seperatedDeclaringTypename[QualificationHelpers.QULIFIERS_INDEX], + seperatedDeclaringTypename[QualificationHelpers.SIMPLE_NAMES_INDEX], + SearchPattern.R_EXACT_MATCH); + + //search the index for a match + SearchEngine searchEngine = new SearchEngine(DefaultWorkingCopyOwner.PRIMARY); + IJavaScriptSearchScope scope = SearchEngine.createJavaSearchScope(new IJavaScriptElement[] {this.fJavaProject}); + final List matches = new ArrayList(); + try { + searchEngine.search(fieldPattern, + new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()}, + scope, + new SearchRequestor() { + public void acceptSearchMatch(SearchMatch match) throws CoreException { + Object element = match.getElement(); + if(element instanceof IField || element instanceof ILocalVariable) { + matches.add(element); + } + } + }, + new NullProgressMonitor()); //using a NPM here maybe a bad idea, but nothing better to do right now + } + catch (CoreException e) { + Logger.logException("Failed index search for field: " + fieldName, e); //$NON-NLS-1$ + } + + // just use the first match found + if(!matches.isEmpty()) { + resolvedField = (IJavaScriptElement)matches.get(0); + } +// } } } - return null; + return resolvedField; } } diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/HippieProposalComputer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/HippieProposalComputer.java index 1e132b4a..9431cf5f 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/HippieProposalComputer.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/HippieProposalComputer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/IProblemRequestorExtension.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/IProblemRequestorExtension.java index c72c404d..f6899955 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/IProblemRequestorExtension.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/IProblemRequestorExtension.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaCompletionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaCompletionProposal.java index 2c30be78..e43fab28 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaCompletionProposal.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaCompletionProposal.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -88,7 +88,7 @@ public class JavaCompletionProposal extends AbstractJavaCompletionProposal { /* * @see org.eclipse.wst.jsdt.internal.ui.text.java.AbstractJavaCompletionProposal#isValidPrefix(java.lang.String) */ - protected boolean isValidPrefix(String prefix) { + public boolean isValidPrefix(String prefix) { String word= getDisplayString(); if (isInJavadoc()) { int idx = word.indexOf("{@link "); //$NON-NLS-1$ diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaContentAssistHandler.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaContentAssistHandler.java index 5a4c2eb1..407a3406 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaContentAssistHandler.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaContentAssistHandler.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaMethodCompletionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaMethodCompletionProposal.java index 791022cb..c02e7e09 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaMethodCompletionProposal.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaMethodCompletionProposal.java @@ -198,8 +198,13 @@ public class JavaMethodCompletionProposal extends LazyJavaCompletionProposal { parameterCount= Signature.getParameterCount(fProposal.getSignature()) % 10; // we don't care about insane methods with >9 parameters } else { char[][] params = this.fProposal.getParamaterNames(); - parameterList = CharOperation.concatWith(params, ','); - parameterCount = params.length % 10; // we don't care about insane methods with >9 parameters + if(params != null) { + parameterList = CharOperation.concatWith(params, ','); + parameterCount = params.length % 10; // we don't care about insane methods with >9 parameters + } else { + parameterList = new char[0]; + parameterCount = 0; + } } StringBuffer buf= new StringBuffer(name.length + 2 + parameterList.length); @@ -214,7 +219,7 @@ public class JavaMethodCompletionProposal extends LazyJavaCompletionProposal { /* * @see org.eclipse.wst.jsdt.internal.ui.text.java.AbstractJavaCompletionProposal#isValidPrefix(java.lang.String) */ - protected boolean isValidPrefix(String prefix) { + public boolean isValidPrefix(String prefix) { if (super.isValidPrefix(prefix)) return true; diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaTextMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaTextMessages.properties index 7ed2b169..db81925c 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaTextMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaTextMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2008 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,7 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### - +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR CompletionProcessor_error_accessing_title=Error Accessing JavaScript file CompletionProcessor_error_accessing_message=Cannot access JavaScript file diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaTypeCompletionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaTypeCompletionProposal.java index bfde7264..712d85ab 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaTypeCompletionProposal.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavaTypeCompletionProposal.java @@ -106,7 +106,7 @@ public class JavaTypeCompletionProposal extends JavaCompletionProposal { /* * @see org.eclipse.wst.jsdt.internal.ui.text.java.AbstractJavaCompletionProposal#isValidPrefix(java.lang.String) */ - protected boolean isValidPrefix(String prefix) { + public boolean isValidPrefix(String prefix) { return super.isValidPrefix(prefix) || isPrefix(prefix, fUnqualifiedTypeName) || isPrefix(prefix, fFullyQualifiedTypeName); } diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavadocDoubleClickStrategy.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavadocDoubleClickStrategy.java index 2e7dd2ad..305a0fdd 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavadocDoubleClickStrategy.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/JavadocDoubleClickStrategy.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/LazyJavaCompletionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/LazyJavaCompletionProposal.java index 0f7ee37e..1e7e519d 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/LazyJavaCompletionProposal.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/LazyJavaCompletionProposal.java @@ -331,7 +331,7 @@ public class LazyJavaCompletionProposal extends AbstractJavaCompletionProposal { /* * @see org.eclipse.wst.jsdt.internal.ui.text.java.AbstractJavaCompletionProposal#isValidPrefix(java.lang.String) */ - protected boolean isValidPrefix(String prefix) { + public boolean isValidPrefix(String prefix) { if (super.isValidPrefix(prefix)) return true; diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/LazyJavaTypeCompletionProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/LazyJavaTypeCompletionProposal.java index 3446017d..b87deacd 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/LazyJavaTypeCompletionProposal.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/LazyJavaTypeCompletionProposal.java @@ -292,13 +292,9 @@ public class LazyJavaTypeCompletionProposal extends LazyJavaCompletionProposal { /* * @see org.eclipse.wst.jsdt.internal.ui.text.java.LazyJavaCompletionProposal#isValidPrefix(java.lang.String) */ - protected boolean isValidPrefix(String prefix) { + public boolean isValidPrefix(String prefix) { return isPrefix(prefix, getSimpleTypeName()) || isPrefix(prefix, getQualifiedTypeName()); } - - public boolean isValidTypePrefix(String prefix) { - return isValidPrefix(prefix); - } /* * @see org.eclipse.wst.jsdt.internal.ui.text.java.JavaCompletionProposal#getCompletionText() diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/MemberProposalInfo.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/MemberProposalInfo.java index 55a424cd..3d1c830e 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/MemberProposalInfo.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/MemberProposalInfo.java @@ -28,7 +28,7 @@ public abstract class MemberProposalInfo extends ProposalInfo { protected final CompletionProposal fProposal; /* cache filled lazily */ - private boolean fJavaElementResolved= false; + protected boolean fJavaElementResolved= false; /** * Creates a new proposal info. diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/MethodProposalInfo.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/MethodProposalInfo.java index 43721906..1d9563e3 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/MethodProposalInfo.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/MethodProposalInfo.java @@ -11,18 +11,31 @@ package org.eclipse.wst.jsdt.internal.ui.text.java; +import java.util.ArrayList; import java.util.HashMap; +import java.util.List; import java.util.Map; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.wst.jsdt.core.CompletionProposal; import org.eclipse.wst.jsdt.core.IFunction; +import org.eclipse.wst.jsdt.core.IJavaScriptElement; import org.eclipse.wst.jsdt.core.IJavaScriptProject; import org.eclipse.wst.jsdt.core.IMember; import org.eclipse.wst.jsdt.core.IType; -import org.eclipse.wst.jsdt.core.ITypeRoot; import org.eclipse.wst.jsdt.core.JavaScriptModelException; import org.eclipse.wst.jsdt.core.Signature; +import org.eclipse.wst.jsdt.core.search.IJavaScriptSearchScope; +import org.eclipse.wst.jsdt.core.search.SearchEngine; +import org.eclipse.wst.jsdt.core.search.SearchMatch; +import org.eclipse.wst.jsdt.core.search.SearchParticipant; +import org.eclipse.wst.jsdt.core.search.SearchPattern; +import org.eclipse.wst.jsdt.core.search.SearchRequestor; +import org.eclipse.wst.jsdt.internal.core.DefaultWorkingCopyOwner; +import org.eclipse.wst.jsdt.internal.core.search.matching.MethodPattern; import org.eclipse.wst.jsdt.internal.corext.template.java.SignatureUtil; +import org.eclipse.wst.jsdt.internal.ui.Logger; /** @@ -56,47 +69,92 @@ public final class MethodProposalInfo extends MemberProposalInfo { * @throws JavaScriptModelException if accessing the java model fails */ protected IMember resolveMember() throws JavaScriptModelException { - char[] declarationSignature= fProposal.getDeclarationSignature(); + //get the type name + char[] typeNameChars = fProposal.getDeclarationTypeName(); + String declaringTypeName = null; + if(typeNameChars != null) { + declaringTypeName = String.valueOf(typeNameChars); + } + + /* try using the signature if type name not set + * NOTE: old way of doing things, should be removed at some point + */ + if(declaringTypeName == null) { + char[] declarationSignature= fProposal.getDeclarationSignature(); + if(declarationSignature != null) { + declaringTypeName = SignatureUtil.stripSignatureToFQN(String.valueOf(declarationSignature)); + } + } + IFunction func = null; - if (declarationSignature!=null) { - String typeName = SignatureUtil.stripSignatureToFQN(String - .valueOf(declarationSignature)); - String name = String.valueOf(fProposal.getName()); + if (declaringTypeName!=null) { + String functionName = String.valueOf(fProposal.getName()); //get the parameter type names - String[] paramTypeNameStrings; - char[] signature = fProposal.getSignature(); - if(signature != null && signature.length > 0) { - paramTypeNameStrings = Signature.getParameterTypes(String.valueOf(fProposal.getSignature())); - } else { - char[][] paramTypeNameChars = this.fProposal.getParameterTypeNames(); + String[] paramTypeNameStrings = null; + char[][] paramTypeNameChars = this.fProposal.getParameterTypeNames(); + if(paramTypeNameChars != null) { paramTypeNameStrings = new String[paramTypeNameChars.length]; for(int i = 0; i < paramTypeNameChars.length; ++i) { - paramTypeNameStrings[i] = String.valueOf(paramTypeNameChars[i]); + paramTypeNameStrings[i] = paramTypeNameChars[i] != null ? String.valueOf(paramTypeNameChars[i]) : null; + } + } else { + char[] signature = fProposal.getSignature(); + if(signature != null && signature.length > 0) { + paramTypeNameStrings = Signature.getParameterTypes(String.valueOf(fProposal.getSignature())); + } else { + paramTypeNameStrings = new String[0]; } } //search all the possible types until a match is found - IType[] types = fJavaProject.findTypes(typeName); + IType[] types = fJavaProject.findTypes(declaringTypeName); if(types != null && types.length >0) { for(int i = 0; i < types.length && func == null; ++i) { IType type = types[i]; if (type != null) { boolean isConstructor = fProposal.isConstructor(); try { - func = findMethod(name, paramTypeNameStrings, isConstructor, type); + func = findMethod(functionName, paramTypeNameStrings, isConstructor, type); } catch(JavaScriptModelException e) { //ignore, could not find method } } } } else { - ITypeRoot typeRoot=fJavaProject.findTypeRoot(typeName); - if(typeRoot != null) { - func = typeRoot.getFunction(name, paramTypeNameStrings); + //search the index for a match + MethodPattern methodPattern = new MethodPattern(true, false, + functionName.toCharArray(), + new char[][] {declaringTypeName.toCharArray()}, + SearchPattern.R_EXACT_MATCH); + + SearchEngine searchEngine = new SearchEngine(DefaultWorkingCopyOwner.PRIMARY); + IJavaScriptSearchScope scope = SearchEngine.createJavaSearchScope(new IJavaScriptElement[] {this.fJavaProject}); + final List matches = new ArrayList(); + try { + searchEngine.search(methodPattern, + new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()}, + scope, + new SearchRequestor() { + public void acceptSearchMatch(SearchMatch match) throws CoreException { + if(match.getElement() instanceof IFunction) { + matches.add(match.getElement()); + } + } + }, + new NullProgressMonitor()); //using a NPM here maybe a bad idea, but nothing better to do right now + } + catch (CoreException e) { + Logger.logException("Failed index search for function: " + functionName, e); //$NON-NLS-1$ + } + + // just use the first match found + if(!matches.isEmpty()) { + func = (IFunction)matches.get(0); } } - } + } + return func; } diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ProposalInfo.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ProposalInfo.java index af5fb3f6..32a7b0c7 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ProposalInfo.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/ProposalInfo.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -68,10 +68,7 @@ public class ProposalInfo { private String computeInfo(IProgressMonitor monitor) { try { final IJavaScriptElement javaElement= getJavaElement(); - if (javaElement instanceof IMember) { - IMember member= (IMember) javaElement; - return extractJavadoc(member, monitor); - } + return extractJavadoc(javaElement, monitor); } catch (JavaScriptModelException e) { JavaScriptPlugin.log(e); } catch (IOException e) { @@ -84,33 +81,35 @@ public class ProposalInfo { * Extracts the javadoc for the given IMember and returns it * as HTML. * - * @param member the member to get the documentation for + * @param element the member to get the documentation for * @param monitor a progress monitor * @return the javadoc for member or null if * it is not available * @throws JavaScriptModelException if accessing the javadoc fails * @throws IOException if reading the javadoc fails */ - private String extractJavadoc(IMember member, IProgressMonitor monitor) throws JavaScriptModelException, IOException { - if (member != null) { - Reader reader= getHTMLContentReader(member, monitor); + private String extractJavadoc(IJavaScriptElement element, IProgressMonitor monitor) throws JavaScriptModelException, IOException { + if (element != null) { + Reader reader = getHTMLContentReader(element, monitor); if (reader != null) return getString(reader); } return null; } - private Reader getHTMLContentReader(IMember member, IProgressMonitor monitor) throws JavaScriptModelException { - Reader contentReader= JSdocContentAccess.getHTMLContentReader(member, true, true); - if (contentReader != null) + private Reader getHTMLContentReader(IJavaScriptElement element, IProgressMonitor monitor) throws JavaScriptModelException { + Reader contentReader= JSdocContentAccess.getHTMLContentReader(element, true, true); + if (contentReader != null) { return contentReader; + } - contentReader= JSdocContentAccess.getContentReader(member, true); - if (contentReader != null) + contentReader= JSdocContentAccess.getContentReader(element, true); + if (contentReader != null) { return new JavaDoc2HTMLTextReader(contentReader); - - if (member.getOpenable().getBuffer() == null) { // only if no source available - String s= member.getAttachedJavadoc(monitor); + } + + if (element.getOpenable().getBuffer() == null) { // only if no source available + String s= element.getAttachedJavadoc(monitor); if (s != null) return new StringReader(s); } diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/RelevanceSorter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/RelevanceSorter.java index 787baedd..817b4aca 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/RelevanceSorter.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/RelevanceSorter.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2007 IBM Corporation and others. + * Copyright (c) 2006, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/AbstractJavaEditorTextHover.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/AbstractJavaEditorTextHover.java index e676f5dd..bf96fb9d 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/AbstractJavaEditorTextHover.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/AbstractJavaEditorTextHover.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -25,7 +25,6 @@ import org.eclipse.jface.text.IInformationControl; import org.eclipse.jface.text.IInformationControlCreator; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextHoverExtension; -import org.eclipse.jface.text.ITextHoverExtension2; import org.eclipse.jface.text.ITextViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.FontData; @@ -46,16 +45,19 @@ import org.osgi.framework.Bundle; /** * Abstract class for providing hover information for Java elements. + * + * */ -public abstract class AbstractJavaEditorTextHover implements IJavaEditorTextHover, ITextHoverExtension, ITextHoverExtension2 { +public abstract class AbstractJavaEditorTextHover implements IJavaEditorTextHover, ITextHoverExtension { /** * The style sheet (css). + * */ private static String fgStyleSheet; private IEditorPart fEditor; - /* (non-Javadoc) - * @see org.eclipse.wst.jsdt.ui.text.java.hover.IJavaEditorTextHover#setEditor(org.eclipse.ui.IEditorPart) + /* + * @see IJavaEditorTextHover#setEditor(IEditorPart) */ public void setEditor(IEditorPart editor) { fEditor= editor; @@ -80,23 +82,15 @@ public abstract class AbstractJavaEditorTextHover implements IJavaEditorTextHove return null; } - /* (non-Javadoc) - * @see org.eclipse.jface.text.ITextHover#getHoverRegion(org.eclipse.jface.text.ITextViewer, int) + /* + * @see ITextHover#getHoverRegion(ITextViewer, int) */ public IRegion getHoverRegion(ITextViewer textViewer, int offset) { return JavaWordFinder.findWord(textViewer.getDocument(), offset); } - /* (non-Javadoc) - * @see org.eclipse.jface.text.ITextHoverExtension2#getHoverInfo2(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion) - * @since 3.3 - */ - public Object getHoverInfo2(ITextViewer textViewer, IRegion hoverRegion) { - return getHoverInfo(textViewer, hoverRegion); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.ITextHover#getHoverInfo(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion) + /* + * @see ITextHover#getHoverInfo(ITextViewer, IRegion) */ public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { @@ -139,8 +133,9 @@ public abstract class AbstractJavaEditorTextHover implements IJavaEditorTextHove return null; } - /* (non-Javadoc) - * @see org.eclipse.jface.text.ITextHoverExtension#getHoverControlCreator() + /* + * @see ITextHoverExtension#getHoverControlCreator() + * */ public IInformationControlCreator getHoverControlCreator() { return new IInformationControlCreator() { diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/AnnotationHover.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/AnnotationHover.java index 326cb086..0b1e624c 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/AnnotationHover.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/AnnotationHover.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/BestMatchHover.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/BestMatchHover.java index d941f91d..c61c6d51 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/BestMatchHover.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/BestMatchHover.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -18,7 +18,6 @@ import org.eclipse.jface.text.IInformationControlCreator; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextHover; import org.eclipse.jface.text.ITextHoverExtension; -import org.eclipse.jface.text.ITextHoverExtension2; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.information.IInformationProviderExtension2; import org.eclipse.ui.IEditorPart; @@ -29,7 +28,7 @@ import org.eclipse.wst.jsdt.ui.text.java.hover.IJavaEditorTextHover; /** * Caution: this implementation is a layer breaker and contains some "shortcuts" */ -public class BestMatchHover extends AbstractJavaEditorTextHover implements IInformationProviderExtension2 { +public class BestMatchHover extends AbstractJavaEditorTextHover implements ITextHoverExtension, IInformationProviderExtension2 { private List fTextHoverSpecifications; private List fInstantiatedTextHovers; @@ -83,8 +82,8 @@ public class BestMatchHover extends AbstractJavaEditorTextHover implements IInfo fInstantiatedTextHovers.add(hover); } - /* (non-Javadoc) - * @see org.eclipse.wst.jsdt.internal.ui.text.java.hover.AbstractJavaEditorTextHover#getHoverInfo(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion) + /* + * @see ITextHover#getHoverInfo(ITextViewer, IRegion) */ public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { @@ -107,8 +106,9 @@ public class BestMatchHover extends AbstractJavaEditorTextHover implements IInfo return null; } - /* (non-Javadoc) - * @see org.eclipse.wst.jsdt.internal.ui.text.java.hover.AbstractJavaEditorTextHover#getHoverControlCreator() + /* + * @see org.eclipse.jface.text.ITextHoverExtension#getHoverControlCreator() + * */ public IInformationControlCreator getHoverControlCreator() { if (fBestHover instanceof ITextHoverExtension) @@ -117,8 +117,9 @@ public class BestMatchHover extends AbstractJavaEditorTextHover implements IInfo return null; } - /* (non-Javadoc) + /* * @see org.eclipse.jface.text.information.IInformationProviderExtension2#getInformationPresenterControlCreator() + * */ public IInformationControlCreator getInformationPresenterControlCreator() { if (fBestHover instanceof IInformationProviderExtension2) @@ -126,37 +127,4 @@ public class BestMatchHover extends AbstractJavaEditorTextHover implements IInfo return null; } - - /* (non-Javadoc) - * @see org.eclipse.jface.text.ITextHoverExtension2#getHoverInfo2(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion) - * @since 3.3 - */ - public Object getHoverInfo2(ITextViewer textViewer, IRegion hoverRegion) { - checkTextHovers(); - fBestHover= null; - - if (fInstantiatedTextHovers == null) - return null; - - for (Iterator iterator= fInstantiatedTextHovers.iterator(); iterator.hasNext(); ) { - ITextHover hover= (ITextHover)iterator.next(); - if (hover == null) - continue; - - if (hover instanceof ITextHoverExtension2) { - Object info= ((ITextHoverExtension2) hover).getHoverInfo2(textViewer, hoverRegion); - if (info != null) { - fBestHover= hover; - return info; - } - } else { - String s= hover.getHoverInfo(textViewer, hoverRegion); - if (s != null && s.trim().length() > 0) { - fBestHover= hover; - return s; - } - } - } - return null; - } } diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaEditorTextHoverProxy.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaEditorTextHoverProxy.java index 872c7a7a..269c795b 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaEditorTextHoverProxy.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaEditorTextHoverProxy.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -14,7 +14,6 @@ package org.eclipse.wst.jsdt.internal.ui.text.java.hover; import org.eclipse.jface.text.IInformationControlCreator; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextHoverExtension; -import org.eclipse.jface.text.ITextHoverExtension2; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.information.IInformationProviderExtension2; import org.eclipse.ui.IEditorPart; @@ -23,8 +22,10 @@ import org.eclipse.wst.jsdt.ui.text.java.hover.IJavaEditorTextHover; /** * Proxy for JavaEditorTextHovers. + * + * */ -public class JavaEditorTextHoverProxy extends AbstractJavaEditorTextHover implements IInformationProviderExtension2 { +public class JavaEditorTextHoverProxy extends AbstractJavaEditorTextHover implements ITextHoverExtension, IInformationProviderExtension2 { private JavaEditorTextHoverDescriptor fHoverDescriptor; private IJavaEditorTextHover fHover; @@ -34,8 +35,8 @@ public class JavaEditorTextHoverProxy extends AbstractJavaEditorTextHover implem setEditor(editor); } - /* (non-Javadoc) - * @see org.eclipse.wst.jsdt.internal.ui.text.java.hover.AbstractJavaEditorTextHover#setEditor(org.eclipse.ui.IEditorPart) + /* + * @see IJavaEditorTextHover#setEditor(IEditorPart) */ public void setEditor(IEditorPart editor) { super.setEditor(editor); @@ -48,8 +49,8 @@ public class JavaEditorTextHoverProxy extends AbstractJavaEditorTextHover implem return true; } - /* (non-Javadoc) - * @see org.eclipse.wst.jsdt.internal.ui.text.java.hover.AbstractJavaEditorTextHover#getHoverRegion(org.eclipse.jface.text.ITextViewer, int) + /* + * @see ITextHover#getHoverRegion(ITextViewer, int) */ public IRegion getHoverRegion(ITextViewer textViewer, int offset) { if (ensureHoverCreated()) @@ -58,8 +59,8 @@ public class JavaEditorTextHoverProxy extends AbstractJavaEditorTextHover implem return null; } - /* (non-Javadoc) - * @see org.eclipse.wst.jsdt.internal.ui.text.java.hover.AbstractJavaEditorTextHover#getHoverInfo(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion) + /* + * @see ITextHover#getHoverInfo(ITextViewer, IRegion) */ public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { if (ensureHoverCreated()) @@ -68,22 +69,6 @@ public class JavaEditorTextHoverProxy extends AbstractJavaEditorTextHover implem return null; } - /* (non-Javadoc) - * @see org.eclipse.wst.jsdt.internal.ui.text.java.hover.AbstractJavaEditorTextHover#getHoverInfo2(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion) - * @since 3.3 - */ - public Object getHoverInfo2(ITextViewer textViewer, IRegion hoverRegion) { - if (ensureHoverCreated()) { - if (fHover instanceof ITextHoverExtension2) { - return ((ITextHoverExtension2) fHover).getHoverInfo2(textViewer, hoverRegion); - } - else { - return fHover.getHoverInfo(textViewer, hoverRegion); - } - } - return null; - } - private boolean ensureHoverCreated() { if (!isEnabled() || fHoverDescriptor == null) return false; @@ -101,8 +86,9 @@ public class JavaEditorTextHoverProxy extends AbstractJavaEditorTextHover implem return isCreated(); } - /* (non-Javadoc) - * @see org.eclipse.wst.jsdt.internal.ui.text.java.hover.AbstractJavaEditorTextHover#getHoverControlCreator() + /* + * @see org.eclipse.jface.text.ITextHoverExtension#getHoverControlCreator() + * */ public IInformationControlCreator getHoverControlCreator() { if (ensureHoverCreated() && (fHover instanceof ITextHoverExtension)) @@ -111,7 +97,7 @@ public class JavaEditorTextHoverProxy extends AbstractJavaEditorTextHover implem return null; } - /* (non-Javadoc) + /* * @see org.eclipse.jface.text.information.IInformationProviderExtension2#getInformationPresenterControlCreator() */ public IInformationControlCreator getInformationPresenterControlCreator() { diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaExpandHover.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaExpandHover.java index add3a5af..78dfac7d 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaExpandHover.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaExpandHover.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaHoverMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaHoverMessages.properties index ea690479..3dc24877 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaHoverMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavaHoverMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2007 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_NONE JavaTextHover_createTextHover= Could not create javaScript text hover diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavadocHover.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavadocHover.java index 7a8185a3..93c386da 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavadocHover.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/JavadocHover.java @@ -25,6 +25,7 @@ import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.editors.text.EditorsUI; import org.eclipse.wst.jsdt.core.IJavaScriptElement; +import org.eclipse.wst.jsdt.core.ILocalVariable; import org.eclipse.wst.jsdt.core.IMember; import org.eclipse.wst.jsdt.core.IOpenable; import org.eclipse.wst.jsdt.core.IPackageFragmentRoot; @@ -210,7 +211,21 @@ public class JavadocHover extends AbstractJavaEditorTextHover implements IInform } hasContents= true; } else if (curr != null && curr.getElementType() == IJavaScriptElement.LOCAL_VARIABLE) { - HTMLPrinter.addSmallHeader(buffer, getInfoText(curr)); + Reader reader = null; + try { + reader= JSdocContentAccess.getHTMLContentReader((ILocalVariable)curr, false, true); + } + catch (JavaScriptModelException e) { + reader= new StringReader(JavaHoverMessages.JavadocHover_error_gettingJavadoc); + JavaScriptPlugin.log(e.getStatus()); + } + if (reader != null) { + HTMLPrinter.addParagraph(buffer, reader); + } + else { + HTMLPrinter.addSmallHeader(buffer, getInfoText(curr)); + } + hasContents= true; } } diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/ProblemHover.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/ProblemHover.java index 427240bd..8293bd0a 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/ProblemHover.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/java/hover/ProblemHover.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/IHtmlTagConstants.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/IHtmlTagConstants.java index 202c8e83..de4e474b 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/IHtmlTagConstants.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/IHtmlTagConstants.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/IJavaDocTagConstants.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/IJavaDocTagConstants.java index b0da8007..6d102911 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/IJavaDocTagConstants.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/IJavaDocTagConstants.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavaDocMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavaDocMessages.properties index 82ee803d..f9c5b1c3 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavaDocMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavaDocMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2007 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,7 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### - +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_NONE JavaDoc2HTMLTextReader_parameters_section=Parameters: JavaDoc2HTMLTextReader_returns_section=Returns: diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavadocContentAssistInvocationContext.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavadocContentAssistInvocationContext.java index 09ba30c2..cee4b850 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavadocContentAssistInvocationContext.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/javadoc/JavadocContentAssistInvocationContext.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2007 IBM Corporation and others. + * Copyright (c) 2005, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/DefaultPhoneticDistanceAlgorithm.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/DefaultPhoneticDistanceAlgorithm.java index ee19af09..d6f6ec74 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/DefaultPhoneticDistanceAlgorithm.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/DefaultPhoneticDistanceAlgorithm.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/DefaultPhoneticHashProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/DefaultPhoneticHashProvider.java index e27ba0f9..a1c0cf6f 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/DefaultPhoneticHashProvider.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/DefaultPhoneticHashProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/DefaultSpellChecker.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/DefaultSpellChecker.java index 6b6b6655..bd633d05 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/DefaultSpellChecker.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/DefaultSpellChecker.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/IPhoneticDistanceAlgorithm.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/IPhoneticDistanceAlgorithm.java index 93ebff23..c7ad6399 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/IPhoneticDistanceAlgorithm.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/IPhoneticDistanceAlgorithm.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/IPhoneticHashProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/IPhoneticHashProvider.java index 3de23a26..f245e154 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/IPhoneticHashProvider.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/IPhoneticHashProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellCheckEngine.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellCheckEngine.java index d7810148..7dc55fbf 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellCheckEngine.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellCheckEngine.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellCheckIterator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellCheckIterator.java index f2af6386..dac85922 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellCheckIterator.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellCheckIterator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellChecker.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellChecker.java index 5c5e9f7f..7564a894 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellChecker.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellChecker.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellDictionary.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellDictionary.java index 96ac4d8f..f778ec8a 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellDictionary.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellDictionary.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellEvent.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellEvent.java index c087146f..b39df29f 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellEvent.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellEvent.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellEventListener.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellEventListener.java index 149ffe25..749e0c24 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellEventListener.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/ISpellEventListener.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/LocaleSensitiveSpellDictionary.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/LocaleSensitiveSpellDictionary.java index f627f67d..ee7247ca 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/LocaleSensitiveSpellDictionary.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/LocaleSensitiveSpellDictionary.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/RankedWordProposal.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/RankedWordProposal.java index a19d721f..a976d71b 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/RankedWordProposal.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/RankedWordProposal.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/SpellEvent.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/SpellEvent.java index a4f38c2c..4b2984f2 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/SpellEvent.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/spelling/engine/SpellEvent.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/InclusivePositionUpdater.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/InclusivePositionUpdater.java index e3391323..bc555682 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/InclusivePositionUpdater.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/InclusivePositionUpdater.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/MultiVariable.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/MultiVariable.java index 41dfc204..106c90e7 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/MultiVariable.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/MultiVariable.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/MultiVariableGuess.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/MultiVariableGuess.java index 3a7f484a..e4f18baa 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/MultiVariableGuess.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/MultiVariableGuess.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/TemplateContentAssistMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/TemplateContentAssistMessages.properties index d6328064..cc4f2bc3 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/TemplateContentAssistMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/TemplateContentAssistMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2007 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR # template proposal # The first argument is the name and the second is the description diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/TemplateInformationControlCreator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/TemplateInformationControlCreator.java index 00d1ee76..2f0bf12e 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/TemplateInformationControlCreator.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/contentassist/TemplateInformationControlCreator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/preferences/TemplatePreferencesMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/preferences/TemplatePreferencesMessages.properties index 3911a0f0..860db50e 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/preferences/TemplatePreferencesMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/text/template/preferences/TemplatePreferencesMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2007 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,5 +8,7 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_NONE TemplateVariableProposal_error_title=Error applying template variable proposal diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/MethodsViewer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/MethodsViewer.java index 0dd3a7db..3e11a74f 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/MethodsViewer.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/MethodsViewer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/ToggleLinkingAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/ToggleLinkingAction.java index eff02c4c..26fad213 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/ToggleLinkingAction.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/ToggleLinkingAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/TypeHierarchyMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/TypeHierarchyMessages.properties index 6cf712cb..067ac167 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/TypeHierarchyMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/typehierarchy/TypeHierarchyMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2007 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR EnableMemberFilterAction_label=Members in Hierarchy EnableMemberFilterAction_tooltip=Lock View and Show Members in Hierarchy diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/ConvertAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/ConvertAction.java index 586f576f..684b3e08 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/ConvertAction.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/ConvertAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2011 IBM Corporation and others. + * Copyright (c) 2007, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -11,7 +11,6 @@ package org.eclipse.wst.jsdt.internal.ui.util; -import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -23,11 +22,12 @@ import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.IExtension; import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.SubProgressMonitor; +import org.eclipse.core.runtime.Status; +import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.action.IAction; -import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.preference.PreferenceDialog; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; @@ -38,7 +38,6 @@ import org.eclipse.ui.IObjectActionDelegate; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.dialogs.PreferencesUtil; -import org.eclipse.ui.progress.IProgressService; import org.eclipse.wst.jsdt.core.IIncludePathEntry; import org.eclipse.wst.jsdt.core.IJavaScriptProject; import org.eclipse.wst.jsdt.core.IPackageFragmentRoot; @@ -59,16 +58,15 @@ public class ConvertAction implements IObjectActionDelegate, IActionDelegate { private static final String FACET_NATURE = "org.eclipse.wst.common.project.facet.core.nature"; //$NON-NLS-1$ private static final String FACET_PROPERTY_PAGE = "org.eclipse.wst.common.project.facet.ui.FacetsPropertyPage"; //$NON-NLS-1$ - private void doInstall(IProject project, final boolean openProperties, IProgressMonitor monitor) { + private void doInstall(IProject project) { boolean configured = false; - monitor.beginTask(Messages.converter_ConfiguringForJavaScript, 5); ConvertUtility convertor = new ConvertUtility(project); try { boolean hadBasicNature = ConvertUtility.hasNature(project); - convertor.configure(new SubProgressMonitor(monitor, 1)); - convertor.addBrowserSupport(!hadBasicNature, new SubProgressMonitor(monitor, 1)); + convertor.configure(new NullProgressMonitor()); + convertor.addBrowserSupport(!hadBasicNature, new NullProgressMonitor()); if (!hadBasicNature) { /* @@ -98,7 +96,7 @@ public class ConvertAction implements IObjectActionDelegate, IActionDelegate { try { - jp.setRawIncludepath(newEntries, project.getFullPath(), new SubProgressMonitor(monitor, 1)); + jp.setRawIncludepath(newEntries, project.getFullPath(), new NullProgressMonitor()); } catch (JavaScriptModelException ex1) { Logger.log(Logger.ERROR_DEBUG, null, ex1); @@ -109,11 +107,6 @@ public class ConvertAction implements IObjectActionDelegate, IActionDelegate { catch (CoreException ex) { Logger.logException(ex); } - - if (configured && openProperties) { - showPropertiesOn(project, new SubProgressMonitor(monitor, 1)); - } - monitor.done(); } private void doUninstall(IProject project, IProgressMonitor monitor) { @@ -144,75 +137,56 @@ public class ConvertAction implements IObjectActionDelegate, IActionDelegate { } } - private void install(final IProject project, final boolean openProperties) { - IProgressService service = null; - if (fPart != null) { - service = (IProgressService) fPart.getSite().getService(IProgressService.class); - } - if (service == null) { - doInstall(project, openProperties, new NullProgressMonitor()); - } - else { - IRunnableWithProgress runnable = new IRunnableWithProgress() { - public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { - doInstall(project, openProperties, monitor); - } - }; - try { - service.run(false, false, runnable); - } - catch (InvocationTargetException e) { - Logger.logException(e); - } - catch (InterruptedException e) { - Logger.logException(e); - } - } + private void install(final IProject project) { + doInstall(project); } public void run(IAction action) { if (fTarget == null) return; - for (int i = 0; i < fTarget.length; i++) { - if (fTarget[i] instanceof IResource) { - final IProject project = ((IResource) fTarget[i]).getProject(); - if (!project.isAccessible()) - continue; + new Job(Messages.converter_ConfiguringForJavaScript) { + protected IStatus run(IProgressMonitor arg0) { + for (int i = 0; i < fTarget.length; i++) { + if (fTarget[i] instanceof IResource) { + final IProject project = ((IResource) fTarget[i]).getProject(); - // Temporary until https://bugs.eclipse.org/bugs/show_bug.cgi?id=298483 is resolved -// enableForFacets(project); - - if (!ConvertUtility.hasNature(project)) { - /* Doesn't have nature, do a full install. */ - install(project, i == fTarget.length - 1); - } - else { - /* - * Has nature, check for browser library on include path - * and setup if not found. - */ - IJavaScriptProject jp = JavaScriptCore.create(project); - IIncludePathEntry[] rawClasspath = null; - try { - rawClasspath = jp.getRawIncludepath(); - } - catch (JavaScriptModelException ex1) { - Logger.log(Logger.ERROR_DEBUG, null, ex1); - } + /* Temporary until https://bugs.eclipse.org/bugs/show_bug.cgi?id=298483 is resolved */ + // enableForFacets(project); - boolean browserFound = false; - for (int k = 0; rawClasspath != null && !browserFound && k < rawClasspath.length; k++) { - if (rawClasspath[k].getPath().equals(ConvertUtility.BROWSER_LIBRARY_PATH)) { - browserFound = true; + if (!ConvertUtility.hasNature(project)) { + /* Doesn't have nature, do a full install. */ + install(project); + } + else { + /* + * Has nature, check for browser library on + * include path and setup if not found. + */ + IJavaScriptProject jp = JavaScriptCore.create(project); + IIncludePathEntry[] rawClasspath = null; + try { + rawClasspath = jp.getRawIncludepath(); + } + catch (JavaScriptModelException ex1) { + Logger.log(Logger.ERROR_DEBUG, null, ex1); + } + + boolean browserFound = false; + for (int k = 0; rawClasspath != null && !browserFound && k < rawClasspath.length; k++) { + if (rawClasspath[k].getPath().equals(ConvertUtility.BROWSER_LIBRARY_PATH)) { + browserFound = true; + } + } + if (!browserFound) { + install(project); + } } - } - if (!browserFound) { - install(project, false); } } + return Status.OK_STATUS; } - } + }.schedule(); } diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/CoreUtility.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/CoreUtility.java index 6b83eb66..6a59ab94 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/CoreUtility.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/CoreUtility.java @@ -152,12 +152,11 @@ public class CoreUtility { } else { IJavaScriptProject[] projects = JavaScriptCore.create(JavaScriptPlugin.getWorkspace().getRoot()).getJavaScriptProjects(); if(projects.length > 0) { - monitor.beginTask(JavaUIMessages.CoreUtility_buildall_taskname, 2*projects.length); + monitor.beginTask(JavaUIMessages.CoreUtility_buildall_taskname, projects.length); for (int i = 0; i < projects.length; i++) { IProject project = projects[i].getProject(); - if (project.isAccessible()) { - project.build(IncrementalProjectBuilder.FULL_BUILD, JavaScriptCore.BUILDER_ID, null, new SubProgressMonitor(monitor, 2)); - } + if(project.isAccessible()) + projects[i].getProject().build(IncrementalProjectBuilder.FULL_BUILD, JavaScriptCore.BUILDER_ID, null, new SubProgressMonitor(monitor, 1)); } } } diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/TableLayoutComposite.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/TableLayoutComposite.java index 3c6b2745..9237a264 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/TableLayoutComposite.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/util/TableLayoutComposite.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/JavaElementImageProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/JavaElementImageProvider.java index c765a834..9ac1dd74 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/JavaElementImageProvider.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/JavaElementImageProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -350,7 +350,8 @@ public class JavaElementImageProvider { if (Flags.isPrivate(flags)) return JavaPluginImages.DESC_MISC_PRIVATE; - return JavaPluginImages.DESC_MISC_DEFAULT; + // by default return public method image + return JavaPluginImages.DESC_MISC_PUBLIC; } public static ImageDescriptor getFieldImageDescriptor(boolean isInInterfaceOrAnnotation, int flags) { @@ -361,7 +362,8 @@ public class JavaElementImageProvider { if (Flags.isPrivate(flags)) return JavaPluginImages.DESC_FIELD_PRIVATE; - return JavaPluginImages.DESC_FIELD_DEFAULT; + // by default return public field image + return JavaPluginImages.DESC_FIELD_PUBLIC; } public static ImageDescriptor getTypeImageDescriptor(boolean isInner, boolean isInInterfaceOrAnnotation, int flags, boolean useLightIcons) { diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/SelectionListenerWithASTManager.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/SelectionListenerWithASTManager.java index 8ceaa3b7..7dfbc57a 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/SelectionListenerWithASTManager.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/viewsupport/SelectionListenerWithASTManager.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -11,7 +11,6 @@ package org.eclipse.wst.jsdt.internal.ui.viewsupport; import java.util.HashMap; -import java.util.Iterator; import java.util.Map; import org.eclipse.core.runtime.IProgressMonitor; @@ -51,9 +50,10 @@ public class SelectionListenerWithASTManager { fgDefault= new SelectionListenerWithASTManager(); } return fgDefault; - } + } + - private final class PartListenerGroup { + private final static class PartListenerGroup { private ITextEditor fPart; private ISelectionListener fPostSelectionListener; private ISelectionChangedListener fSelectionListener; @@ -112,14 +112,15 @@ public class SelectionListenerWithASTManager { } public void fireSelectionChanged(final ITextSelection selection) { - //cancel any previous selection calculations, no need to finish now that selection has changed - SelectionListenerWithASTManager.this.cancelExistingSelectionCalculations(); + if (fCurrentJob != null) { + fCurrentJob.cancel(); + } } - public synchronized void firePostSelectionChanged(final ITextSelection selection) { - //cancel any previous selection calculations, no need to finish now that selection has changed - SelectionListenerWithASTManager.this.cancelExistingSelectionCalculations(); - + public void firePostSelectionChanged(final ITextSelection selection) { + if (fCurrentJob != null) { + fCurrentJob.cancel(); + } final IJavaScriptElement input= EditorUtility.getEditorInputJavaElement(fPart, false); if (input == null) { return; @@ -207,20 +208,4 @@ public class SelectionListenerWithASTManager { } } } - - /** - *

This method will cancel all existing selection calculations both in the current - * editor and any other open editor. This should be done when ever the selection is changed - * because there is no need to keep calculating the selection after it has changed.

- */ - private void cancelExistingSelectionCalculations() { - Iterator keysIter = this.fListenerGroups.keySet().iterator(); - while(keysIter.hasNext()) { - ITextEditor key = (ITextEditor)keysIter.next(); - PartListenerGroup group = (PartListenerGroup)this.fListenerGroups.get(key); - if(group.fCurrentJob != null) { - group.fCurrentJob.cancel(); - } - } - } } diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/JavaProjectWizardFirstPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/JavaProjectWizardFirstPage.java index fb021d66..d27516e3 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/JavaProjectWizardFirstPage.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/JavaProjectWizardFirstPage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewJSFileWizardPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewJSFileWizardPage.java index 0872a642..d2ffb0d5 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewJSFileWizardPage.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewJSFileWizardPage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2010 IBM Corporation and others. + * Copyright (c) 2006, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -26,85 +26,42 @@ import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.content.IContentType; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.jface.preference.PreferenceDialog; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.osgi.util.NLS; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.events.SelectionListener; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Link; -import org.eclipse.ui.dialogs.PreferencesUtil; import org.eclipse.ui.dialogs.WizardNewFileCreationPage; +import org.eclipse.wst.jsdt.core.IBuffer; +import org.eclipse.wst.jsdt.core.IIncludePathEntry; +import org.eclipse.wst.jsdt.core.IJavaScriptProject; import org.eclipse.wst.jsdt.core.IJavaScriptUnit; import org.eclipse.wst.jsdt.core.JavaScriptCore; +import org.eclipse.wst.jsdt.core.JavaScriptModelException; import org.eclipse.wst.jsdt.internal.corext.codemanipulation.StubUtility; import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin; -import org.eclipse.wst.jsdt.internal.ui.preferences.CodeTemplatePreferencePage; -import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.wst.jsdt.ui.CodeGeneration; class NewJSFileWizardPage extends WizardNewFileCreationPage { private IContentType fContentType; private List fValidExtensions = null; - private Button commentsButton; public NewJSFileWizardPage(String pageName, IStructuredSelection selection) { super(pageName, selection); } - private void typePageLinkActivated() { - IProject project = getProjectFromPath(getContainerFullPath()); - if (project != null && isWebProject(project)) { - PreferenceDialog dialog = PreferencesUtil.createPropertyDialogOn(getShell(), project.getProject(), - CodeTemplatePreferencePage.PROP_ID, null, null); - dialog.open(); - } else { - String title = NewWizardMessages.NewTypeWizardPage_configure_templates_title; - String message = NewWizardMessages.NewTypeWizardPage_configure_templates_message; - MessageDialog.openInformation(getShell(), title, message); - } - } - - protected void createAdvancedControls(Composite parent) { - Link link = new Link(parent, SWT.NONE); - link.setText(NewWizardMessages.NewTypeWizardPage_addcomment_description); - link.addSelectionListener(new SelectionListener() { - - public void widgetSelected(SelectionEvent arg0) { - typePageLinkActivated(); - } - - public void widgetDefaultSelected(SelectionEvent arg0) { - typePageLinkActivated(); - } - }); - DialogField.createEmptySpace(parent); - commentsButton = new Button(parent, SWT.CHECK); - commentsButton.setFont(parent.getFont()); - commentsButton.setText(NewWizardMessages.NewTypeWizardPage_addcomment_label); - DialogField.createEmptySpace(parent); - super.createAdvancedControls(parent); - } - /** - * This method is overriden to set the selected folder to web contents - * folder if the current selection is outside the web contents folder. + * This method is overridden to set the selected folder to source + * folder if the current selection is outside the source folder. */ protected void initialPopulateContainerNameField() { - super.initialPopulateContainerNameField(); IPath fullPath = getContainerFullPath(); if (fullPath != null && fullPath.segmentCount() > 0) { IProject project = getProjectFromPath(fullPath); - IPath webContentPath = getWebContentPath(project); + IPath sourcePath = getSourcePath(project); IPath projectPath = project.getFullPath(); if (projectPath.equals(fullPath)) - setContainerFullPath(webContentPath); + setContainerFullPath(sourcePath); else setContainerFullPath(fullPath); } @@ -159,10 +116,10 @@ class NewJSFileWizardPage extends WizardNewFileCreationPage { // get the IProject for the selection path IProject project = getProjectFromPath(fullPath); // if inside web project, check if inside webContent folder - if (project != null && isWebProject(project)) { + if (project != null && isJSProject(project)) { // check that the path is inside the webContent folder - IPath webContentPath = getWebContentPath(project); - if (!webContentPath.isPrefixOf(fullPath)) { + IPath sourcePath = getSourcePath(project); + if (!sourcePath.isPrefixOf(fullPath)) { setMessage(NewWizardMessages.Javascript_Warning_Folder_Must_Be_Inside_Web_Content, WARNING); } } @@ -268,56 +225,57 @@ newFileName.append("js"); //$NON-NLS-1$ * @param project project to be checked * @return true if the project is web project, otherwise false */ - private boolean isWebProject(IProject project) { -/* - IFacetedProject faceted = null; + private boolean isJSProject(IProject project) { try { - faceted = ProjectFacetsManager.create(project); - } catch (CoreException e) { - Logger.log(Logger.WARNING_DEBUG, e.getMessage(), e); + return project.hasNature(JavaScriptCore.NATURE_ID); } - - if (faceted != null && - (faceted.hasProjectFacet(ProjectFacetsManager.getProjectFacet(IModuleConstants.WST_WEB_MODULE)) || - faceted.hasProjectFacet(ProjectFacetsManager.getProjectFacet(IModuleConstants.JST_WEB_MODULE)))) { - return true; + catch (CoreException e) { + return false; } - - return false; -*/ -return true; } /** - * Returns the web contents folder of the specified project + * Returns the source folder of the specified project * - * @param project the project which web contents path is needed - * @return IPath of the web contents folder + * @param project the project which source path is needed + * @return IPath of the source folder */ - private IPath getWebContentPath(IProject project) { + private IPath getSourcePath(IProject project) { IPath path = null; - - if (project != null && isWebProject(project)) { - path = project.getFullPath(); -// IVirtualComponent component = ComponentCore.createComponent(project); -// path = component.getRootFolder().getWorkspaceRelativePath(); -path.append("/"); //$NON-NLS-1$ + + if (project != null && isJSProject(project)) { + IJavaScriptProject p = JavaScriptCore.create(project); + try { + IIncludePathEntry[] includepath = p.getResolvedIncludepath(true); + for (int i = 0; i < includepath.length; i++) { + if (includepath[i].getEntryKind() == IIncludePathEntry.CPE_SOURCE) + return includepath[i].getPath(); + } + } + catch (JavaScriptModelException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } } - + return path; } public void addFileComment(IFile file) { - if (commentsButton.getSelection()) { - IJavaScriptUnit cu= JavaScriptCore.createCompilationUnitFrom(file); - try { - cu.becomeWorkingCopy(new NullProgressMonitor()); - cu.getBuffer().setContents(CodeGeneration.getFileComment(cu, StubUtility.getLineDelimiterUsed(cu))); + addFileComment(file, true); + } + public void addFileComment(IFile file, boolean overwrite) { + IJavaScriptUnit cu= JavaScriptCore.createCompilationUnitFrom(file); + try { + cu.becomeWorkingCopy(new NullProgressMonitor()); + IBuffer buffer = cu.getBuffer(); + if (overwrite || buffer.getLength() == 0) { + buffer.setContents(CodeGeneration.getFileComment(cu, StubUtility.getLineDelimiterUsed(cu))); cu.commitWorkingCopy(true, new NullProgressMonitor()); - cu.discardWorkingCopy(); - } catch (CoreException e) { - JavaScriptPlugin.log(e); } + cu.discardWorkingCopy(); + } catch (CoreException e) { + JavaScriptPlugin.log(e); } } } diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewJSWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewJSWizard.java index 2c55a2ed..06f80248 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewJSWizard.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewJSWizard.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2011 IBM Corporation and others. + * Copyright (c) 2005, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -78,7 +78,7 @@ public class NewJSWizard extends Wizard implements INewWizard { // create a new empty file IFile file = fNewFilePage.createNewFile(); // add comment to created file - fNewFilePage.addFileComment(file); + fNewFilePage.addFileComment(file, false); // if there was problem with creating file, it will be null, so make // sure to check if (file != null) { diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewWizardMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewWizardMessages.properties index b083318b..e5ede0c3 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewWizardMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/NewWizardMessages.properties @@ -8,6 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR # ------- AbstractOpenWizardAction ------- @@ -170,7 +172,7 @@ NewInterfaceWizardPage_description=Create a new JavaScript interface. # ------- JavaCapabilityConfigurationPage ------- JavaCapabilityConfigurationPage_title=JavaScript Settings -JavaCapabilityConfigurationPage_description=Define the JavaScript project's build settings. This will determine which files will be validated and made available for content assist. +JavaCapabilityConfigurationPage_description=Define the JavaScript project's Include Path. This will determine which files will be validated and made available for content assist. JavaCapabilityConfigurationPage_op_desc_java=Configuring JavaScript project... @@ -533,13 +535,13 @@ ExclusionInclusionDialog_Info_Output=Removing is not possible because this entry ExclusionInclusionEntryDialog_exclude_add_title=Add Exclusion Pattern ExclusionInclusionEntryDialog_exclude_edit_title=Edit Exclusion Pattern -ExclusionInclusionEntryDialog_exclude_description=Enter a pattern for excluding files from the source folder. Allowed wildcards are '*', '?' and '**'. Examples: 'java/util/A*.java', 'java/util/', '**/Test*'. +ExclusionInclusionEntryDialog_exclude_description=Enter a pattern for excluding files from the source folder. Allowed wildcards are '*', '?' and '**'. Examples: 'scripts/util/A*.js', 'scripts/util/', '**/Test*'. ExclusionInclusionEntryDialog_exclude_pattern_label=E&xclusion pattern (Path relative to ''{0}''): ExclusionInclusionEntryDialog_include_add_title=Add Inclusion Pattern ExclusionInclusionEntryDialog_include_edit_title=Edit Inclusion Pattern -ExclusionInclusionEntryDialog_include_description=Enter a pattern for including files to the source folder. Allowed wildcards are '*', '?' and '**'. Examples: 'java/util/A*.java', 'java/util/', '**/Test*'. +ExclusionInclusionEntryDialog_include_description=Enter a pattern for including files to the source folder. Allowed wildcards are '*', '?' and '**'. Examples: 'scripts/util/A*.js', 'scripts/util/', '**/Test*'. ExclusionInclusionEntryDialog_include_pattern_label=I&nclusion pattern (Path relative to ''{0}''): diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/OpenJavaScriptFileWizardToolbarAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/OpenJavaScriptFileWizardToolbarAction.java index f6b4ec3c..828c7ccd 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/OpenJavaScriptFileWizardToolbarAction.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/OpenJavaScriptFileWizardToolbarAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/OpenJavaScriptProjectWizardToolbarAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/OpenJavaScriptProjectWizardToolbarAction.java index ed551c0a..c92d70b5 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/OpenJavaScriptProjectWizardToolbarAction.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/OpenJavaScriptProjectWizardToolbarAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/TypedViewerFilter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/TypedViewerFilter.java index e7a22965..f3013916 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/TypedViewerFilter.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/TypedViewerFilter.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/AddSourceFolderWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/AddSourceFolderWizard.java index 27765720..f7696662 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/AddSourceFolderWizard.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/AddSourceFolderWizard.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/BuildPathWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/BuildPathWizard.java index 4b2faf1a..5188a35b 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/BuildPathWizard.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/BuildPathWizard.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CPListElement.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CPListElement.java index 9d2a2988..40a5c528 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CPListElement.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CPListElement.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CPListElementSorter.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CPListElementSorter.java index 5cf735ef..e94aac47 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CPListElementSorter.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CPListElementSorter.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CPListLabelProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CPListLabelProvider.java index cf992afb..b9c249b2 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CPListLabelProvider.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CPListLabelProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CPUserLibraryElement.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CPUserLibraryElement.java index b7e29625..011fb101 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CPUserLibraryElement.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CPUserLibraryElement.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CreateMultipleSourceFoldersDialog.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CreateMultipleSourceFoldersDialog.java index 92427efe..72f6b534 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CreateMultipleSourceFoldersDialog.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/CreateMultipleSourceFoldersDialog.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/EditFilterWizard.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/EditFilterWizard.java index 4995229e..54a05d1e 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/EditFilterWizard.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/EditFilterWizard.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/JsGlobalScopeContainerSelectionPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/JsGlobalScopeContainerSelectionPage.java index f2cc53ad..15c2308e 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/JsGlobalScopeContainerSelectionPage.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/JsGlobalScopeContainerSelectionPage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/ProjectsWorkbookPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/ProjectsWorkbookPage.java index cd79b8f9..0046eaa2 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/ProjectsWorkbookPage.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/ProjectsWorkbookPage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/SourceAttachmentBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/SourceAttachmentBlock.java index 5d0c1e82..9327f2d4 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/SourceAttachmentBlock.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/SourceAttachmentBlock.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/UserLibraryWizardPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/UserLibraryWizardPage.java index 493c3815..4abdb878 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/UserLibraryWizardPage.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/UserLibraryWizardPage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/AddFolderToBuildpathAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/AddFolderToBuildpathAction.java index 677241ef..1cb8971b 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/AddFolderToBuildpathAction.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/AddFolderToBuildpathAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/BuildpathModifierAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/BuildpathModifierAction.java index a98a04f1..507b65cf 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/BuildpathModifierAction.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/BuildpathModifierAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/ClasspathModifierQueries.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/ClasspathModifierQueries.java index e8e4548e..9a07d55f 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/ClasspathModifierQueries.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/ClasspathModifierQueries.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/CreateLinkedSourceFolderAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/CreateLinkedSourceFolderAction.java index a9efb664..c9113f4c 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/CreateLinkedSourceFolderAction.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/CreateLinkedSourceFolderAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/CreateSourceFolderAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/CreateSourceFolderAction.java index 21667bf6..6ef1563f 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/CreateSourceFolderAction.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/CreateSourceFolderAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/DialogPackageExplorer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/DialogPackageExplorer.java index a26ea4b7..fa2bc42a 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/DialogPackageExplorer.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/DialogPackageExplorer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/DialogPackageExplorerActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/DialogPackageExplorerActionGroup.java index 31e4af6a..9c68d5bb 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/DialogPackageExplorerActionGroup.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/DialogPackageExplorerActionGroup.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/EditFilterAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/EditFilterAction.java index 1879fbdb..2db13148 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/EditFilterAction.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/EditFilterAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/HintTextGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/HintTextGroup.java index 1d2ff465..0c771248 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/HintTextGroup.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/HintTextGroup.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/NewSourceContainerWorkbookPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/NewSourceContainerWorkbookPage.java index 03aa5e90..f137d216 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/NewSourceContainerWorkbookPage.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/NewSourceContainerWorkbookPage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/ResetAllAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/ResetAllAction.java index 3041e51a..0e6d4843 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/ResetAllAction.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/buildpaths/newsourcepage/ResetAllAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/ListDialogField.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/ListDialogField.java index 1ce79dd6..ea75ebe4 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/ListDialogField.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/wizards/dialogfields/ListDialogField.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/AbstractWorkingSetWizardPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/AbstractWorkingSetWizardPage.java index adc2a789..7c66ea6d 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/AbstractWorkingSetWizardPage.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/AbstractWorkingSetWizardPage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/ClearWorkingSetAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/ClearWorkingSetAction.java index a92b8ba0..6d2a7527 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/ClearWorkingSetAction.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/ClearWorkingSetAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetFilterActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetFilterActionGroup.java index 357a971e..f6e37b7e 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetFilterActionGroup.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetFilterActionGroup.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetMenuContributionItem.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetMenuContributionItem.java index e0e87a77..0d6cbc71 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetMenuContributionItem.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetMenuContributionItem.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetMessages.properties index fcb9e427..d9cce213 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/workingsets/WorkingSetMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2007 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR AbstractWorkingSetPage_workingSet_name= &Working set name: AbstractWorkingSetPage_warning_nameMustNotBeEmpty= The name must not be empty. diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/libraries/BasicBrowserLibraryContainerUIExtension.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/libraries/BasicBrowserLibraryContainerUIExtension.java index 2055e4ef..2c4c3f4b 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/libraries/BasicBrowserLibraryContainerUIExtension.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/libraries/BasicBrowserLibraryContainerUIExtension.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2010 IBM Corporation and others. + * Copyright (c) 2007, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/IJavaScriptElementSearchConstants.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/IJavaScriptElementSearchConstants.java index 17f6826b..6591c2ec 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/IJavaScriptElementSearchConstants.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/IJavaScriptElementSearchConstants.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/ISharedImages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/ISharedImages.java index 4ce7efe5..6af0346b 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/ISharedImages.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/ISharedImages.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JSdocContentAccess.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JSdocContentAccess.java index 77b9b4cd..4e127805 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JSdocContentAccess.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JSdocContentAccess.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -37,6 +37,7 @@ import org.eclipse.wst.jsdt.internal.core.MetadataFile; import org.eclipse.wst.jsdt.internal.corext.javadoc.JavaDocCommentReader; import org.eclipse.wst.jsdt.internal.corext.util.MethodOverrideTester; import org.eclipse.wst.jsdt.internal.ui.JavaScriptPlugin; +import org.eclipse.wst.jsdt.internal.ui.Logger; import org.eclipse.wst.jsdt.internal.ui.text.javadoc.JavaDoc2HTMLTextReader; import org.eclipse.wst.jsdt.internal.ui.text.javadoc.OAADocReader; @@ -65,6 +66,33 @@ public class JSdocContentAccess { // do not instantiate } + /** + *

Gets the content reader for either an {@link IMember} or {@link ILocalVariable}.

+ * + * @param element {@link IJavaScriptElement} to get the content reader for + * @param allowInherited For methods with no (Javadoc) comment, the comment of the overridden class + * is returned if allowInherited is true. + * + * @return a reader for the Javadoc comment content or null if the element + * does not contain a Javadoc comment or if no source is available + * + * @throws JavaScriptModelException is thrown when the elements javadoc can not be accessed + * + * @see #getContentReader(ILocalVariable, boolean) + * @see #getContentReader(IMember, boolean) + */ + public static Reader getContentReader(IJavaScriptElement element, boolean allowInherited) throws JavaScriptModelException { + Reader reader = null; + + if(element instanceof IMember) { + reader = getContentReader((IMember)element, allowInherited); + } else if(element instanceof ILocalVariable) { + reader = getContentReader((ILocalVariable)element, allowInherited); + } + + return reader; + } + /** * Gets a reader for an IMember's Javadoc comment content from the source attachment. * The content does contain only the text from the comment without the Javadoc leading star characters. @@ -117,7 +145,7 @@ public class JSdocContentAccess { } } catch (JavaScriptModelException e) { - // doesn't exist + Logger.logException(Logger.ERROR_DEBUG, e); } } @@ -128,6 +156,49 @@ public class JSdocContentAccess { } return null; } + + /** + * Gets a reader for an ILocalDeclaration's doc comment content from the + * source attachment. Returns null if the declaration does + * not have a doc comment or if no source is available. + * + * @param declaration + * The declaration to get the doc of. + * @param allowInherited + * For methods with no doc comment, the comment of the + * overridden class is returned if allowInherited + * is true and this is an argument. + * @return Returns a reader for the doc comment content or + * null if the declaration does not contain a doc + * comment or if no source is available + * @throws JavaScriptModelException + * is thrown when the declaration's doc can not be accessed + */ + public static Reader getContentReader(ILocalVariable declaration, boolean allowInherited) throws JavaScriptModelException { + List readers = new ArrayList(2); + IDocumentationReader[] docReaders = getDocReaders(declaration); + for (int i = 0; i < docReaders.length; i++) { + Reader contentReader = docReaders[i].getContentReader(declaration, allowInherited); + if (contentReader != null) { + readers.add(contentReader); + } + } + + if (!readers.isEmpty()) { + if (readers.size() == 1) + return (Reader) readers.get(0); + return new SequenceReader((Reader[]) readers.toArray(new Reader[readers.size()])); + } + IOpenable openable = declaration.getOpenable(); + if (!(openable instanceof MetadataFile)) { + IBuffer buf = openable.getBuffer(); + JavaDocCommentReader r = new JavaDocCommentReader(buf, declaration.getNameRange().getOffset() - 1); + if(r.getOffset() != declaration.getNameRange().getOffset() - 1) { + return r; + } + } + return null; + } /** * Checks whether the given reader only returns @@ -148,6 +219,35 @@ public class JSdocContentAccess { return new String(content).trim().equals("{@inheritDoc}"); //$NON-NLS-1$ } + + /** + *

Gets the HTML content reader for either an {@link IMember} or {@link ILocalVariable}.

+ * + * @param element {@link IJavaScriptElement} to get the Javadoc of + * @param allowInherited for methods with no (Javadoc) comment, the comment of the overridden + * class is returned if allowInherited is true + * @param useAttachedJavadoc if true Javadoc will be extracted from attached Javadoc + * if there's no source + * + * @return a reader for the Javadoc comment content in HTML or null if the element + * does not contain a Javadoc comment or if no source is available + * + * @throws JavaScriptModelException is thrown when the elements Javadoc can not be accessed + * + * @see #getHTMLContentReader(ILocalVariable, boolean, boolean) + * @see #getHTMLContentReader(IMember, boolean, boolean) + */ + public static Reader getHTMLContentReader(IJavaScriptElement element, boolean allowInherited, boolean useAttachedJavadoc) throws JavaScriptModelException { + Reader reader = null; + + if(element instanceof IMember) { + reader = getHTMLContentReader((IMember)element, allowInherited, useAttachedJavadoc); + } else if(element instanceof ILocalVariable) { + reader = getHTMLContentReader((ILocalVariable)element, allowInherited, useAttachedJavadoc); + } + + return reader; + } /** * Gets a reader for an IMember's Javadoc comment content from the source attachment. @@ -211,9 +311,8 @@ public class JSdocContentAccess { */ public static Reader getHTMLContentReader(ILocalVariable variable, boolean allowInherited, boolean useAttachedDoc) throws JavaScriptModelException { Reader contentReader= getContentReader(variable, allowInherited); - if (contentReader != null) - { - IDocumentationReader[] docReaders = new IDocumentationReader[0];//getDocReaders(declaration); + if (contentReader != null) { + IDocumentationReader[] docReaders = getDocReaders(variable); if (docReaders.length > 0) { List htmlReaders = new ArrayList(docReaders.length); for (int i = 0; i < docReaders.length; i++) { @@ -233,43 +332,6 @@ public class JSdocContentAccess { return null; } - - - /** - * Gets a reader for an ILocalDeclaration's doc comment content from the - * source attachment. Returns null if the declaration does - * not have a doc comment or if no source is available. - * - * @param declaration - * The declaration to get the doc of. - * @param allowInherited - * For methods with no doc comment, the comment of the - * overridden class is returned if allowInherited - * is true and this is an argument. - * @return Returns a reader for the doc comment content or - * null if the declaration does not contain a doc - * comment or if no source is available - * @throws JavaScriptModelException - * is thrown when the declaration's doc can not be accessed - */ - public static Reader getContentReader(ILocalVariable declaration, boolean allowInherited) throws JavaScriptModelException { - List readers = new ArrayList(2); - IDocumentationReader[] docReaders = getDocReaders(declaration); - for (int i = 0; i < docReaders.length; i++) { - Reader contentReader = docReaders[i].getContentReader(declaration, allowInherited); - if (contentReader != null) { - readers.add(contentReader); - } - } - - if (!readers.isEmpty()) { - if (readers.size() == 1) - return (Reader) readers.get(0); - return new SequenceReader((Reader[]) readers.toArray(new Reader[readers.size()])); - } - return null; - } - private static Reader findDocInHierarchy(IFunction method) throws JavaScriptModelException { IType type= method.getDeclaringType(); if (type==null) diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptElementComparator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptElementComparator.java index cc245b42..7bda7ade 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptElementComparator.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptElementComparator.java @@ -219,7 +219,7 @@ public class JavaScriptElementComparator extends ViewerComparator { } // only JavaScript elements from this point - if (e1 instanceof IMember) { + if (e1 instanceof IMember && e2 instanceof IMember) { if (fMemberOrderCache.isSortByVisibility()) { try { int flags1= JdtFlags.getVisibilityCode((IMember) e1); @@ -236,7 +236,7 @@ public class JavaScriptElementComparator extends ViewerComparator { String name1= getElementName(e1); String name2= getElementName(e2); - if (e1 instanceof IType) { // handle anonymous types + if (e1 instanceof IType && e2 instanceof IType) { // handle anonymous types if (name1.length() == 0) { if (name2.length() == 0) { try { @@ -257,7 +257,7 @@ public class JavaScriptElementComparator extends ViewerComparator { return cmp; } - if (e1 instanceof IFunction) { + if (e1 instanceof IFunction && e2 instanceof IFunction) { String[] params1= ((IFunction) e1).getParameterTypes(); String[] params2= ((IFunction) e2).getParameterTypes(); int len= Math.min(params1.length, params2.length); @@ -269,6 +269,7 @@ public class JavaScriptElementComparator extends ViewerComparator { } return params1.length - params2.length; } + return 0; } diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptElementLabels.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptElementLabels.java index 2b4caf9c..1c58e07e 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptElementLabels.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptElementLabels.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -354,6 +354,8 @@ public class JavaScriptElementLabels { private final static long QUALIFIER_FLAGS= P_COMPRESSED | USE_RESOLVED; + private static final IPath LIBCACHE_LOCATION = new Path(JavaScriptCore.getJavaScriptCore().getStateLocation().append(new String(SystemLibraryLocation.LIBRARY_RUNTIME_DIRECTORY)).toOSString()); + /* * Package name compression */ @@ -363,8 +365,6 @@ public class JavaScriptElementLabels { private static int fgPkgNameChars; private static int fgPkgNameLength= -1; - private static final IPath LIBCACHE_LOCATION = new Path(JavaScriptCore.getJavaScriptCore().getStateLocation().append(new String(SystemLibraryLocation.LIBRARY_RUNTIME_DIRECTORY)).toOSString()); - private JavaScriptElementLabels() { } @@ -989,7 +989,7 @@ public class JavaScriptElementLabels { } buf.append(name.substring(start)); } else { -// buf.append(pack.getDisplayName()); + buf.append(pack.getDisplayName()); } if (getFlag(flags, P_POST_QUALIFIED)) { buf.append(CONCAT_STRING); @@ -1094,6 +1094,8 @@ public class JavaScriptElementLabels { boolean rootQualified= getFlag(flags, ROOT_QUALIFIED); boolean referencedQualified= getFlag(flags, REFERENCED_ROOT_POST_QUALIFIED) && isReferenced(root); if (rootQualified) { +// buf.append(root.getPath().makeRelative().toString()); + // for libraries stored in our metadata area, just show the filename if (LIBCACHE_LOCATION.isPrefixOf(root.getPath())) { buf.append(root.getPath().lastSegment().toString()); } diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptUI.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptUI.java index 01bdb8b6..3b915b15 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptUI.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/JavaScriptUI.java @@ -182,7 +182,7 @@ public final class JavaScriptUI { public static final String ID_SOURCE_VIEW= "org.eclipse.wst.jsdt.ui.SourceView"; //$NON-NLS-1$ /** - * The view part id of the JavaScript Documentation view + * The view part id of the Javadoc view * (value "org.eclipse.wst.jsdt.ui.JavadocView"). * * @see org.eclipse.ui.IWorkbenchPage#findView(java.lang.String) diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/ProblemsLabelDecorator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/ProblemsLabelDecorator.java index af48b6b2..4b3dbd1d 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/ProblemsLabelDecorator.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/ProblemsLabelDecorator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/ProjectLibraryRoot.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/ProjectLibraryRoot.java index 9700d830..84bf16d3 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/ProjectLibraryRoot.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/ProjectLibraryRoot.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2010 IBM Corporation and others. + * Copyright (c) 2007, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -17,6 +17,7 @@ import java.util.ArrayList; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.core.runtime.Platform; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.ui.model.IWorkbenchAdapter; import org.eclipse.wst.jsdt.core.IIncludePathAttribute; @@ -166,7 +167,7 @@ public class ProjectLibraryRoot implements IAdaptable{ return getProject().getProject(); } - return null; + return Platform.getAdapterManager().getAdapter(this, adapter); } public boolean equals(Object obj) { diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/StandardJavaScriptElementContentProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/StandardJavaScriptElementContentProvider.java index 4133e4f3..37f9b949 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/StandardJavaScriptElementContentProvider.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/StandardJavaScriptElementContentProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -35,6 +35,8 @@ import org.eclipse.wst.jsdt.core.IType; import org.eclipse.wst.jsdt.core.ITypeRoot; import org.eclipse.wst.jsdt.core.JavaScriptCore; import org.eclipse.wst.jsdt.core.JavaScriptModelException; +import org.eclipse.wst.jsdt.internal.ui.packageview.NamespaceGroup; +import org.eclipse.wst.jsdt.internal.ui.packageview.PackageFragmentRootContainer; /** * A base content provider for JavaScriptelements. It provides access to the @@ -281,6 +283,10 @@ public class StandardJavaScriptElementContentProvider implements ITreeContentPro return true; } } + + if(element instanceof NamespaceGroup || element instanceof PackageFragmentRootContainer) { + return true; + } Object[] children= getChildren(element); return (children != null) && children.length > 0; } diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/CCPActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/CCPActionGroup.java index 6e084a95..56a5c7b0 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/CCPActionGroup.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/CCPActionGroup.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/DeclarationsSearchGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/DeclarationsSearchGroup.java index b89edac0..1edf4ab7 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/DeclarationsSearchGroup.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/DeclarationsSearchGroup.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ExtractMethodAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ExtractMethodAction.java index ef26d148..b6fb3e13 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ExtractMethodAction.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ExtractMethodAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/GenerateActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/GenerateActionGroup.java index 05d098bd..ad616cb8 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/GenerateActionGroup.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/GenerateActionGroup.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/IJavaEditorActionDefinitionIds.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/IJavaEditorActionDefinitionIds.java index 5b60dbab..f6cff1e2 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/IJavaEditorActionDefinitionIds.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/IJavaEditorActionDefinitionIds.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ImplementorsSearchGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ImplementorsSearchGroup.java index 5a09fb77..453a4e2b 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ImplementorsSearchGroup.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ImplementorsSearchGroup.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/JavaSearchActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/JavaSearchActionGroup.java index 3eb32021..dad8f5ba 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/JavaSearchActionGroup.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/JavaSearchActionGroup.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/JdtActionConstants.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/JdtActionConstants.java index 7792deda..d1998854 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/JdtActionConstants.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/JdtActionConstants.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OccurrencesSearchGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OccurrencesSearchGroup.java index 230942f9..da4fce98 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OccurrencesSearchGroup.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OccurrencesSearchGroup.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenEditorActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenEditorActionGroup.java index f5099ede..2c8dbfe0 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenEditorActionGroup.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenEditorActionGroup.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenNewClassWizardAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenNewClassWizardAction.java index c203641d..61b7657b 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenNewClassWizardAction.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenNewClassWizardAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenViewActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenViewActionGroup.java index 9074ec09..3c89ce10 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenViewActionGroup.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/OpenViewActionGroup.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ReadReferencesSearchGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ReadReferencesSearchGroup.java index e37e4d99..1a5d02f9 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ReadReferencesSearchGroup.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ReadReferencesSearchGroup.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ReferencesSearchGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ReferencesSearchGroup.java index 8c62ce09..35a7f1eb 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ReferencesSearchGroup.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ReferencesSearchGroup.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/SelectionDispatchAction.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/SelectionDispatchAction.java index 6a269cf5..b4bf9cb3 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/SelectionDispatchAction.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/SelectionDispatchAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ShowActionGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ShowActionGroup.java index 8569e62d..8f29965c 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ShowActionGroup.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/ShowActionGroup.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/WriteReferencesSearchGroup.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/WriteReferencesSearchGroup.java index 2286177f..ffa18f8a 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/WriteReferencesSearchGroup.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/actions/WriteReferencesSearchGroup.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/messages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/messages.properties index 7686a549..fc2ea8f0 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/messages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/messages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2007, 2009 IBM Corporation and others. +# Copyright (c) 2007, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,4 +8,7 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_NONE + ProjectLibraryRoot.0=JavaScript Resources diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/search/ISearchRequestor.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/search/ISearchRequestor.java index e4895e7f..093067a0 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/search/ISearchRequestor.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/search/ISearchRequestor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/JavaScriptSourceViewerConfiguration.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/JavaScriptSourceViewerConfiguration.java index 627363a2..c6110610 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/JavaScriptSourceViewerConfiguration.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/JavaScriptSourceViewerConfiguration.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/folding/IJavaFoldingPreferenceBlock.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/folding/IJavaFoldingPreferenceBlock.java index 0bcfdcad..7a54fa10 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/folding/IJavaFoldingPreferenceBlock.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/folding/IJavaFoldingPreferenceBlock.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/folding/IJavaFoldingStructureProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/folding/IJavaFoldingStructureProvider.java index 54d25a1f..4e3c25b3 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/folding/IJavaFoldingStructureProvider.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/folding/IJavaFoldingStructureProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/CompletionProposalCollector.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/CompletionProposalCollector.java index d5ce9df5..0495e87d 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/CompletionProposalCollector.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/CompletionProposalCollector.java @@ -90,6 +90,13 @@ public class CompletionProposalCollector extends CompletionRequestor { /** Tells whether this class is in debug mode. */ private static final boolean DEBUG= "true".equalsIgnoreCase(Platform.getDebugOption("org.eclipse.wst.jsdt.ui/debug/ResultCollector")); //$NON-NLS-1$//$NON-NLS-2$ + /** + *

+ * true if this collector allows duplicates, false (default), if it does not. + *

+ */ + private static final boolean ALLOW_DUPLICATES = "true".equalsIgnoreCase(System.getProperty("org.eclipse.wst.jsdt.ui/ContentAssist/allowDuplicates")); //$NON-NLS-1$//$NON-NLS-2$; + /** Triggers for method proposals without parameters. Do not modify. */ protected final static char[] METHOD_TRIGGERS= new char[] { ';', ',', '.', '\t', '[', ' ' }; /** Triggers for method proposals. Do not modify. */ @@ -213,7 +220,10 @@ public class CompletionProposalCollector extends CompletionRequestor { } else { IJavaCompletionProposal javaProposal= createJavaCompletionProposal(proposal); if (javaProposal != null) { - fJavaProposals.add(javaProposal); + if(!this.fJavaProposals.contains(javaProposal) || ALLOW_DUPLICATES) { + fJavaProposals.add(javaProposal); + } + if (proposal.getKind() == CompletionProposal.KEYWORD) fKeywords.add(javaProposal); } @@ -554,12 +564,7 @@ public class CompletionProposalCollector extends CompletionRequestor { case CompletionProposal.ANONYMOUS_CLASS_DECLARATION: case CompletionProposal.FIELD_REF: case CompletionProposal.JSDOC_FIELD_REF: - char[] declaration= proposal.getDeclarationSignature(); - // special methods may not have a declaring type: methods defined on arrays etc. - // Currently known: class literals don't have a declaring type - use Object - if (declaration == null) - return "java.lang.Object".toCharArray(); //$NON-NLS-1$ - return Signature.toCharArray(declaration); + return proposal.getDeclarationTypeName(); case CompletionProposal.PACKAGE_REF: return proposal.getDeclarationSignature(); case CompletionProposal.JSDOC_TYPE_REF: @@ -686,7 +691,7 @@ public class CompletionProposalCollector extends CompletionRequestor { int start= proposal.getReplaceStart(); int length= getLength(proposal); Image image= getImage(fLabelProvider.createLocalImageDescriptor(proposal)); - String label= fLabelProvider.createSimpleLabelWithType(proposal); + String label = fLabelProvider.createLabelWithTypeAndDeclaration(proposal); int relevance= computeRelevance(proposal); final JavaCompletionProposal javaProposal= new JavaCompletionProposal(completion, start, length, image, label, relevance); diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/CompletionProposalComparator.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/CompletionProposalComparator.java index 800a0369..b8910186 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/CompletionProposalComparator.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/CompletionProposalComparator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/CompletionProposalLabelProvider.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/CompletionProposalLabelProvider.java index 66c9505d..7f2c4843 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/CompletionProposalLabelProvider.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/CompletionProposalLabelProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2011 IBM Corporation and others. + * Copyright (c) 2005, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -22,6 +22,9 @@ import org.eclipse.wst.jsdt.core.IJavaScriptProject; import org.eclipse.wst.jsdt.core.JSDScopeUtil; import org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer; import org.eclipse.wst.jsdt.core.Signature; +import org.eclipse.wst.jsdt.core.compiler.CharOperation; +import org.eclipse.wst.jsdt.internal.core.search.indexing.IIndexConstants; +import org.eclipse.wst.jsdt.internal.core.util.Util; import org.eclipse.wst.jsdt.internal.corext.template.java.SignatureUtil; import org.eclipse.wst.jsdt.internal.corext.util.Messages; import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages; @@ -43,10 +46,11 @@ import org.eclipse.wst.jsdt.ui.JavaScriptElementLabels; * (repeatedly) as the API evolves. */ public class CompletionProposalLabelProvider { + /** Used to filter out parameter type names of the ANY type */ + private static final char[] C_ANY = new char[] {Signature.C_ANY}; + /** * The completion context. - * - * */ private CompletionContext fContext; @@ -92,20 +96,17 @@ public class CompletionProposalLabelProvider { * @return the modified buffer */ private StringBuffer appendUnboundedParameterList(StringBuffer buffer, CompletionProposal methodProposal) { - // TODO remove once https://bugs.eclipse.org/bugs/show_bug.cgi?id=85293 - // gets fixed. char[] signature= methodProposal.getSignature(); char[][] parameterNames= methodProposal.getParamaterNames(); - char[][] parameterTypes; + char[][] parameterTypes = methodProposal.getParameterTypeNames(); - //if there is a signature use that, else get type names from proposal - if(signature != null && signature.length > 0) { + /* TODO: remove this because it uses signatures + * if did not get parameter types attempt to use signature */ + if((parameterTypes == null || parameterTypes.length == 0) && signature != null && signature.length > 0) { parameterTypes = Signature.getParameterTypes(signature); for (int i= 0; i < parameterTypes.length; i++) { parameterTypes[i]= createTypeDisplayName(parameterTypes[i]); } - } else { - parameterTypes = methodProposal.getParameterTypeNames(); } if (Flags.isVarargs(methodProposal.getFlags())) { @@ -197,18 +198,23 @@ public class CompletionProposalLabelProvider { * @return the display string of the parameter list defined by the passed arguments */ private final StringBuffer appendParameterSignature(StringBuffer buffer, char[][] parameterTypes, char[][] parameterNames) { - if (parameterTypes != null) { - for (int i = 0; i < parameterTypes.length; i++) { + if (parameterNames != null) { + for (int i = 0; i < parameterNames.length; i++) { if (i > 0) { buffer.append(','); buffer.append(' '); } - if (parameterTypes[i].length > 0 & !Arrays.equals(Signature.ANY, parameterTypes[i])) { - buffer.append(parameterTypes[i]); + //do not display the ANY type + if (parameterTypes != null && parameterTypes.length > i && + parameterTypes[i] != null && parameterTypes[i].length > 0 && + !Arrays.equals(Signature.ANY, parameterTypes[i]) && + !Arrays.equals(C_ANY, parameterTypes[i])) { + + Util.insertTypeLabel(parameterTypes[i], buffer); buffer.append(' '); } - if (parameterNames != null && parameterNames[i] != null) { + if (parameterNames[i] != null) { buffer.append(parameterNames[i]); } } @@ -249,22 +255,23 @@ public class CompletionProposalLabelProvider { // return type if (!methodProposal.isConstructor()) { - // TODO remove SignatureUtil.fix83600 call when bugs are fixed - char[] returnType= createTypeDisplayName(Signature.getReturnType(methodProposal.getSignature())); - if (!Arrays.equals(Signature.ANY,returnType)) - { - nameBuffer.append(" "); //$NON-NLS-1$ + char[] returnType= methodProposal.getReturnType(); + if (returnType != null && returnType.length > 0 && !Arrays.equals(Signature.ANY,returnType) && !Arrays.equals(Signature.VOID,returnType)) { + nameBuffer.append(" : "); //$NON-NLS-1$ //@GINO: Anonymous UI Label org.eclipse.wst.jsdt.internal.core.util.Util.insertTypeLabel( returnType, nameBuffer ); } } // declaring type - nameBuffer.append(" - "); //$NON-NLS-1$ String declaringType= extractDeclaringTypeFQN(methodProposal); - - //@GINO: Anonymous UI Label - org.eclipse.wst.jsdt.internal.core.util.Util.insertTypeLabel( declaringType, nameBuffer ); + if(declaringType != null) { + nameBuffer.append(" - "); //$NON-NLS-1$ + if(CharOperation.equals(declaringType.toCharArray(), IIndexConstants.GLOBAL_SYMBOL)) { + declaringType = JavaTextMessages.Global; + } + org.eclipse.wst.jsdt.internal.core.util.Util.insertTypeLabel( declaringType, nameBuffer ); + } return nameBuffer.toString(); } @@ -336,21 +343,23 @@ public class CompletionProposalLabelProvider { * @return the qualified name of the declaring type */ private String extractDeclaringTypeFQN(CompletionProposal methodProposal) { - char[] declaringTypeSignature= methodProposal.getDeclarationSignature(); + String qualifedName = null; + char[] compUnit = methodProposal.getDeclarationTypeName(); - IJavaScriptProject project = methodProposal.getJavaProject(); - JsGlobalScopeContainerInitializer init = JSDScopeUtil.findLibraryInitializer(new Path(new String(compUnit)),project); - if(init!=null) { - String description = init.getDescription(new Path(new String(compUnit)),project); - if( description!=null) return "[" + description + "]"; //$NON-NLS-1$ //$NON-NLS-2$ - + if(compUnit != null) { + IJavaScriptProject project = methodProposal.getJavaProject(); + JsGlobalScopeContainerInitializer init = JSDScopeUtil.findLibraryInitializer(new Path(new String(compUnit)),project); + if(init!=null) { + String description = init.getDescription(new Path(new String(compUnit)),project); + if( description!=null) return "[" + description + "]"; //$NON-NLS-1$ //$NON-NLS-2$ + } + } + + if(methodProposal.getDeclarationTypeName() != null){ + qualifedName = new String(methodProposal.getDeclarationTypeName()); } - // special methods may not have a declaring type: methods defined on arrays etc. - // TODO remove when bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=84690 gets fixed - if (declaringTypeSignature == null) - return "java.lang.Object"; //$NON-NLS-1$ - return SignatureUtil.stripSignatureToFQN(String.valueOf(declaringTypeSignature)); + return qualifedName; } /** @@ -379,13 +388,6 @@ public class CompletionProposalLabelProvider { buf.append(declarationSignature); } return buf.toString(); -// char[] signature; -// if (fContext != null && fContext.isInJavadoc()) -// signature= Signature.getTypeErasure(typeProposal.getSignature()); -// else -// signature= typeProposal.getSignature(); -// char[] fullName= Signature.toCharArray(signature); -// return createTypeProposalLabel(fullName); } String createJavadocTypeProposalLabel(CompletionProposal typeProposal) { @@ -393,26 +395,6 @@ public class CompletionProposalLabelProvider { return createJavadocTypeProposalLabel(fullName); } - String createJavadocSimpleProposalLabel(CompletionProposal proposal) { - // TODO get rid of this - return createSimpleLabel(proposal); - } - - String createTypeProposalLabel(char[] fullName) { - // only display innermost type name as type name, using any - // enclosing types as qualification -// int qIndex= findSimpleNameStart(fullName); -// - StringBuffer buf= new StringBuffer(); -// buf.append(fullName, qIndex, fullName.length - qIndex); -// if (qIndex > 0) { -// buf.append(JavaScriptElementLabels.CONCAT_STRING); -// buf.append(fullName, 0, qIndex - 1); -// } - buf.append(fullName); - return buf.toString(); - } - String createJavadocTypeProposalLabel(char[] fullName) { // only display innermost type name as type name, using any // enclosing types as qualification @@ -447,7 +429,7 @@ public class CompletionProposalLabelProvider { char[] typeName= Signature.getSignatureSimpleName(proposal.getSignature()); if (typeName.length > 0) { - buf.append(" "); //$NON-NLS-1$ + buf.append(" : "); //$NON-NLS-1$ //@GINO: Anonymous UI Label org.eclipse.wst.jsdt.internal.core.util.Util.insertTypeLabel( typeName, buf ); @@ -474,22 +456,33 @@ public class CompletionProposalLabelProvider { StringBuffer buf= new StringBuffer(); buf.append(name); - char[] typeName= Signature.getSignatureSimpleName(proposal.getSignature()); - if (typeName.length > 0&& !(Arrays.equals(Signature.ANY, typeName))) { - buf.append(" "); //$NON-NLS-1$ + char[] returnType = proposal.getReturnType(); + if (returnType != null && returnType.length > 0&& !(Arrays.equals(Signature.ANY, returnType))) { + buf.append(" : "); //$NON-NLS-1$ //@GINO: Anonymous UI Label - org.eclipse.wst.jsdt.internal.core.util.Util.insertTypeLabel( typeName, buf ); + org.eclipse.wst.jsdt.internal.core.util.Util.insertTypeLabel( returnType, buf ); } - char[] declaration= proposal.getDeclarationSignature(); - if (declaration != null) { - declaration= Signature.getSignatureSimpleName(declaration); - if (declaration.length > 0) { - buf.append(" - "); //$NON-NLS-1$ - - //@GINO: Anonymous UI Label - org.eclipse.wst.jsdt.internal.core.util.Util.insertTypeLabel( declaration, buf ); - } + + //get the declaration type + char[] declarationType = null; + if(proposal.getDeclarationTypeName() != null) { + declarationType = proposal.getDeclarationTypeName(); + } else if (proposal.getDeclarationSignature() != null) { + declarationType = Signature.getSignatureSimpleName(proposal.getDeclarationSignature()); + } + + //deal with if global type + if(CharOperation.equals(declarationType, IIndexConstants.GLOBAL_SYMBOL)) { + declarationType = JavaTextMessages.Global.toCharArray(); + } + + //append declaration type + if (declarationType != null && declarationType.length > 0) { + buf.append(" - "); //$NON-NLS-1$ + + //@GINO: Anonymous UI Label + org.eclipse.wst.jsdt.internal.core.util.Util.insertTypeLabel( declarationType, buf ); } return buf.toString(); @@ -545,7 +538,7 @@ public class CompletionProposalLabelProvider { case CompletionProposal.JSDOC_BLOCK_TAG: case CompletionProposal.JSDOC_INLINE_TAG: case CompletionProposal.JSDOC_PARAM_REF: - return createJavadocSimpleProposalLabel(proposal); + return createSimpleLabel(proposal); case CompletionProposal.JSDOC_METHOD_REF: return createJavadocMethodProposalLabel(proposal); case CompletionProposal.PACKAGE_REF: diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/IJavaCompletionProposalComputer.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/IJavaCompletionProposalComputer.java index 9690695f..289b2794 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/IJavaCompletionProposalComputer.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/IJavaCompletionProposalComputer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/JavaTextMessages.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/JavaTextMessages.java index 277d181b..18b58b88 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/JavaTextMessages.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/JavaTextMessages.java @@ -30,6 +30,7 @@ final class JavaTextMessages extends NLS { public static String ResultCollector_anonymous_type; public static String ResultCollector_overridingmethod; + public static String Global; static { NLS.initializeMessages(BUNDLE_NAME, JavaTextMessages.class); diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/JavaTextMessages.properties b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/JavaTextMessages.properties index a039bc28..e50061d0 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/JavaTextMessages.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/text/java/JavaTextMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2007 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,10 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR ResultCollector_anonymous_type=Anonymous Inner Type ResultCollector_overridingmethod=Override function in ''{0}'' + +Global=Global diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/BaseLibraryWizardPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/BaseLibraryWizardPage.java index 145e4f11..6eb988b3 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/BaseLibraryWizardPage.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/BaseLibraryWizardPage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2011 IBM Corporation and others. + * Copyright (c) 2007, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -10,7 +10,6 @@ *******************************************************************************/ package org.eclipse.wst.jsdt.ui.wizards; -import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.swt.SWT; @@ -20,110 +19,55 @@ import org.eclipse.wst.jsdt.core.IJavaScriptProject; import org.eclipse.wst.jsdt.core.JavaScriptCore; import org.eclipse.wst.jsdt.internal.ui.JavaPluginImages; import org.eclipse.wst.jsdt.internal.ui.wizards.NewWizardMessages; -import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.ComboDialogField; import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.wst.jsdt.internal.ui.wizards.dialogfields.LayoutUtil; /** - * NOT API - */ -public class BaseLibraryWizardPage extends NewElementWizardPage implements IJsGlobalScopeContainerPage, IJsGlobalScopeContainerPageExtension, IJsGlobalScopeContainerPageExtension2 { - private static final String HTML5 = "html5"; //$NON-NLS-1$ - private static final String STANDARD_BROWSER = "/StandardBrowser/"; //$NON-NLS-1$ - - private static IPath newDefaultPath() { - return newV401Path(); + * Wizard page for adding base library support to the project. + * + * Provisional API: This class/interface is part of an interim API that is still under development and expected to + * change significantly before reaching stability. It is being made available at this early stage to solicit feedback + * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken + * (repeatedly) as the API evolves. */ +public class BaseLibraryWizardPage extends NewElementWizardPage implements IJsGlobalScopeContainerPage, IJsGlobalScopeContainerPageExtension, IJsGlobalScopeContainerPageExtension2 { + + private static final String CONTAINER_ID="org.eclipse.wst.jsdt.launching.baseBrowserLibrary"; //$NON-NLS-1$ + + public BaseLibraryWizardPage() { + super("BaseicLibraryWizzardPage"); //$NON-NLS-1$ + setTitle(NewWizardMessages.BaseLibraryWizardPage_title); + setImageDescriptor(JavaPluginImages.DESC_WIZBAN_ADD_LIBRARY); } - private static Path newV401Path() { - return new Path(org.eclipse.wst.jsdt.launching.JavaRuntime.BASE_BROWSER_LIB); + public boolean finish() { + return true; } - private static Path newV5Path() { - return new Path(org.eclipse.wst.jsdt.launching.JavaRuntime.BASE_BROWSER_LIB + STANDARD_BROWSER + HTML5); + public IIncludePathEntry getSelection() { + System.out.println("Unimplemented method:BaseLibraryWizardPage.getSelection"); //$NON-NLS-1$ + return null; } - private IPath fPath = Path.ROOT; - - private ComboDialogField fVersionField; - - public BaseLibraryWizardPage() { - super("BasicLibraryWizardPage"); //$NON-NLS-1$ - setTitle(NewWizardMessages.BaseLibraryWizardPage_title); - setImageDescriptor(JavaPluginImages.DESC_WIZBAN_ADD_LIBRARY); - } + public void setSelection(IIncludePathEntry containerEntry) {} public void createControl(Composite parent) { - Composite composite = new Composite(parent, SWT.NONE); + Composite composite= new Composite(parent, SWT.NONE); composite.setFont(parent.getFont()); DialogField field = new DialogField(); - + field.setLabelText(NewWizardMessages.BaseLibraryWizardPage_DefaultBrowserLibraryAdded); - LayoutUtil.doDefaultLayout(composite, new DialogField[]{field}, false, SWT.DEFAULT, SWT.DEFAULT); - - fVersionField = new ComboDialogField(SWT.READ_ONLY); - fVersionField.setLabelText(NewWizardMessages.BaseLibraryWizardPage_DOM_objects_version); - fVersionField.setItems(new String[]{NewWizardMessages.BaseLibraryWizardPage_HTML401, NewWizardMessages.BaseLibraryWizardPage_HTML5}); - if (fPath.segmentCount() > 2 && fPath.lastSegment().equals(HTML5)) { - fVersionField.selectItem(1); - } - else { - fVersionField.selectItem(0); - } - - LayoutUtil.doDefaultLayout(composite, new DialogField[]{field, fVersionField}, false, SWT.DEFAULT, SWT.DEFAULT); - + LayoutUtil.doDefaultLayout(composite, new DialogField[] {field }, false, SWT.DEFAULT, SWT.DEFAULT); Dialog.applyDialogFont(composite); setControl(composite); setDescription(NewWizardMessages.BaseLibraryWizardPage_WebBrowserSupport); } - public boolean finish() { - if (fVersionField == null) { - fPath = newDefaultPath(); - } - else { - switch (fVersionField.getSelectionIndex()) { - case 0 : - fPath = newV401Path(); - break; - case 1 : - fPath = newV5Path(); - break; - default : - fPath = newDefaultPath(); - break; - } - } - return true; - } - - public IIncludePathEntry[] getNewContainers() { - if (fPath == null || fPath.isRoot()) - fPath = newDefaultPath(); - - IIncludePathEntry library = JavaScriptCore.newContainerEntry(fPath); - return new IIncludePathEntry[]{library}; - } - - public IIncludePathEntry getSelection() { - return JavaScriptCore.newContainerEntry(fPath); - } - public void initialize(IJavaScriptProject project, IIncludePathEntry[] currentEntries) { - fPath = newDefaultPath(); - - for (int i = 0; i < currentEntries.length; i++) { - IPath path = currentEntries[i].getPath(); - if (!path.isEmpty() && org.eclipse.wst.jsdt.launching.JavaRuntime.BASE_BROWSER_LIB.equals(path.segment(0))) { - fPath = path; - } - } + // nothing to initialize } - public void setSelection(IIncludePathEntry containerEntry) { - if (containerEntry != null) { - fPath = containerEntry.getPath(); - } + public IIncludePathEntry[] getNewContainers() { + IIncludePathEntry library = JavaScriptCore.newContainerEntry( new Path(CONTAINER_ID)); + return new IIncludePathEntry[] {library}; } } diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/BuildPathDialogAccess.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/BuildPathDialogAccess.java index cb74eb4a..c79eae8f 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/BuildPathDialogAccess.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/BuildPathDialogAccess.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/IJsGlobalScopeContainerPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/IJsGlobalScopeContainerPage.java index 2fb8ccbf..72611d14 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/IJsGlobalScopeContainerPage.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/IJsGlobalScopeContainerPage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -14,11 +14,11 @@ import org.eclipse.jface.wizard.IWizardPage; import org.eclipse.wst.jsdt.core.IIncludePathEntry; /** - * A includepath container page allows the user to create a new or edit an - * existing includepath container entry. + * A classpath container page allows the user to create a new or edit an + * existing classpath container entry. *

* Clients should implement this interface and include the name of their - * class in an extension contributed to the jdt.ui's includepath container page + * class in an extension contributed to the jdt.ui's classpath container page * extension point (named org.eclipse.wst.jsdt.ui.JsGlobalScopeContainerPage * ). *

@@ -38,9 +38,9 @@ import org.eclipse.wst.jsdt.core.IIncludePathEntry; public interface IJsGlobalScopeContainerPage extends IWizardPage { /** - * Called when the includepath container wizard is closed by selecting + * Called when the classpath container wizard is closed by selecting * the finish button. Implementers typically override this method to - * store the page result (new/changed includepath entry returned in + * store the page result (new/changed classpath entry returned in * getSelection) into its model. * * @return if the operation was successful. Only when returned @@ -49,21 +49,21 @@ public interface IJsGlobalScopeContainerPage extends IWizardPage { public boolean finish(); /** - * Returns the edited or created includepath container entry. This method - * may return null if no includepath container entry exists. - * The returned includepath entry is of kind IIncludePathEntry.CPE_CONTAINER + * Returns the edited or created classpath container entry. This method + * may return null if no classpath container entry exists. + * The returned classpath entry is of kind IIncludePathEntry.CPE_CONTAINER * . * - * @return the includepath entry edited or created on the page. + * @return the classpath entry edited or created on the page. */ public IIncludePathEntry getSelection(); /** - * Sets the includepath container entry to be edited or null + * Sets the classpath container entry to be edited or null * if a new entry should be created. * - * @param containerEntry the includepath entry to edit or null. - * If not null then the includepath entry must be of + * @param containerEntry the classpath entry to edit or null. + * If not null then the classpath entry must be of * kind IIncludePathEntry.CPE_CONTAINER */ public void setSelection(IIncludePathEntry containerEntry); diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/JavaCapabilityConfigurationPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/JavaCapabilityConfigurationPage.java index c8bc8bfb..be49dcf5 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/JavaCapabilityConfigurationPage.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/JavaCapabilityConfigurationPage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/NewElementWizardPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/NewElementWizardPage.java index 90a4d303..1521a265 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/NewElementWizardPage.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/NewElementWizardPage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/NewTypeWizardPage.java b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/NewTypeWizardPage.java index 7cdfba1b..84b55b09 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/NewTypeWizardPage.java +++ b/bundles/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/ui/wizards/NewTypeWizardPage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/bundles/org.eclipse.wst.jsdt.ui/templates/default-templates.properties b/bundles/org.eclipse.wst.jsdt.ui/templates/default-templates.properties index cd5ec91e..b3c1a0a3 100644 --- a/bundles/org.eclipse.wst.jsdt.ui/templates/default-templates.properties +++ b/bundles/org.eclipse.wst.jsdt.ui/templates/default-templates.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2008 IBM Corporation and others. +# Copyright (c) 2000, 2011 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -8,6 +8,8 @@ # Contributors: # IBM Corporation - initial API and implementation ############################################################################### +# NLS_ENCODING=UTF-8 +# NLS_MESSAGEFORMAT_VAR Templates.for_array=iterate over array Templates.for_temp=iterate over array with temporary variable diff --git a/development/org.eclipse.wst.jsdt.unittests/src/org/eclipse/wst/jsdt/unittests/internal/MasterJSDTTestSuite.java b/development/org.eclipse.wst.jsdt.unittests/src/org/eclipse/wst/jsdt/unittests/internal/MasterJSDTTestSuite.java index b57cc85a..b97ecff7 100644 --- a/development/org.eclipse.wst.jsdt.unittests/src/org/eclipse/wst/jsdt/unittests/internal/MasterJSDTTestSuite.java +++ b/development/org.eclipse.wst.jsdt.unittests/src/org/eclipse/wst/jsdt/unittests/internal/MasterJSDTTestSuite.java @@ -1,5 +1,5 @@ /***************************************************************************** - * Copyright (c) 2004,2009 IBM Corporation and others. + * Copyright (c) 2004,2013 IBM Corporation and others. * * All rights reserved. This program and the accompanying materials are made * available under the terms of the Eclipse Public License v1.0 which @@ -18,6 +18,9 @@ import junit.framework.TestSuite; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.Platform; +import org.eclipse.wst.jsdt.core.tests.RunJSDTCoreTests; +import org.eclipse.wst.jsdt.core.tests.compiler.JSDTCompilerTests; +import org.eclipse.wst.jsdt.ui.tests.JSDTUITests; import org.eclipse.wst.jsdt.web.core.tests.AllWebCoreTests; import org.eclipse.wst.jsdt.web.ui.tests.AllWebUITests; import org.osgi.framework.Bundle; @@ -32,12 +35,17 @@ public class MasterJSDTTestSuite extends TestSuite { System.setProperty("wtp.autotest.noninteractive", "true"); -// addTest(JSDTCompilerTests.suite()); -// addTest(RunJSDTCoreTests.suite()); + System.setProperty("org.eclipse.wst.jsdt.ui/ContentAssist/allowDuplicates", "true"); + + // JSDT Core and UI + addTest(JSDTCompilerTests.suite()); + addTest(RunJSDTCoreTests.suite()); + addTest(JSDTUITests.suite()); + + // JSDT Web Core and Web UI addTest(AllWebCoreTests.suite()); addTest(AllWebUITests.suite()); -// addTest(JSDTUITests.suite()); - + IConfigurationElement[] elements = Platform.getExtensionRegistry().getConfigurationElementsFor(EXTENSION_POINT_ID); for (int i = 0; i < elements.length; i++) { if (elements[i].getName().equals("suite")) { diff --git a/features/org.eclipse.wst.jsdt.feature/feature.xml b/features/org.eclipse.wst.jsdt.feature/feature.xml index 02045d61..1dab9e43 100644 --- a/features/org.eclipse.wst.jsdt.feature/feature.xml +++ b/features/org.eclipse.wst.jsdt.feature/feature.xml @@ -1,122 +1,121 @@ - - - - - %description - - - - %copyright - - - - %license - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + %description + + + + %copyright + + + + %license + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + -- cgit v1.2.3